text:
Q: SpriteKit Nodes appear smaller in iPhone 6 plus and iPhone 6s plus simulator In iPhone 6 Plus and 6s Plus simulator, the nodes in my GameScene look much smaller than how they're supposed to do (even though the screen fits perfectly - no black bars, empty space, ...).  Strangely, the nodes in my MenuScene and my TutorialScene (in the same simulator) are all normal-sized. My app runs perfectly (with normal-sized nodes in all Scenes) on all other simulators (iPad air, iPad pro, iPhone 5,5s,6,6s).
P
I've tried the following things:

*

*I create launch images for all sizes --> in App Icons and Launch Images, I migrate launch images to an asset catalog --> delete the line in the "launch screen file" --> doesn't work

*I tried the same thing above but this time I deleted the Launch Screen.storyboard (if I have created launch images for all iPhone sizes, why would I need this?)  --> doesn't work

*I delete my launch images and restore launch screen.storyboard (basically reset everything) --> doesn't work
What is wrong with my iPhone 6 Plus and iPhone 6s Plus simulator?

A: UPDATE: Problem solved! (but I still don't know how)
After testing my app on all simulators, I found out that the only devices in which my nodes appear smaller are iPhone 6+ and 6s+. These devices use 3x images. So I figured there's something wrong with my 3x images.
After checking, I didn't find anything wrong with those images (they were the exact same images as the 1x and 2x ones, except their names has the @3x suffix).
So I deleted all 3x images in my images.xcassets  --> problem solved
I still want to know how this solved my problem though. Please comment if you can explain it :)

A: This might help,
The assets folder have 1x, 2x and 3x images. If you only have an image set in the 1x image then all devices will use that image and scale it appropriately.
If you have set the 2x and 3x images then the devices will use theses images but won't scale them.
The 2x image should be twice as big as the 1x image.
If your 1x image is 100px x 100px then your 2x image should be 200px x 200px.
The 3x image should be three times as big as the 1x image.
If your 1x image is 100px x 100px then your 3x image should be 300px x 300px
So you set the same image in all the 1x, 2x and 3x image boxes. So the device will use the right one for its screen size which will make it look smaller on the larger screen (iPhone 6s) because you haven't scaled them.
You can read more about it here in iOS Human Interface Guidelines


text:
Q: hamburger icon rendering as "X" is a few mobile phones otherwise okay on desktop and many other mobile phones. Problem Specifically spotted on Xiaomi The three horizontal lines of the hamburger icon render as "X" on a few mobile phones. In other mobile phones and desktop the hamburger icon renders correctly as three horizontal lines. To be more specific it is on all XIAOMI mobile phones on all browsers.
The  code is
</style>

And the  code is

☰Menu

ABCD

I had to insert an ugly text "MENU".
Snapshot attached.enter image description here

A: The symbol you're seeing - which looks a bit like an X in a box - is the Android symbol for "I can't find this character in my built in fonts."
You need to provide a font - or Icon Font - for that specific character (U+2630).
As for why Xiaomi doesn't support that... It might be because ☰ is the Chinese "trigram for heaven" symbol. They might not have included Chinese fonts on a non-Chinese phone.

A: You could instead draw the icon with CSS instead of hoping that each client has the font.

.hamburger {
 display: inline-block;
 }

.hamburger span {
  display: block;
  width: 33px;
  height: 4px;
  margin-bottom: 5px;
  position: relative;

  background: #cdcdcd;
  border-radius: 3px;

  z-index: 1;
}

A: If you're Client doesnt have a certain Font, there are certain ways to fix it:

*

*Use a font CDN my prefered choice to use Font-Awesome

*Deliver Font on Request

Use a font CDN
As this method is more suitable, as you are not trying to include a random font, but you want to use a font to display Icons. I suggest you to use FontAwesome. It only provides many more fun and free icons to use.
Just include it as descriped in their start page:
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">

To use the Hamburger Icon, just do it like this:

Menu

ABCD

The  Part includes the Icon. The fa-bars class is used to reference the specific FontAwesome Icon. For example change it to fa-caret-down to see this icon.
Note that im not sure, if your hamburger css class is needed anymore, as you haven't shared its code yet. Just being said, that this solution will include the icon without any more css.
Deliver Font on Request
Just Upload your font to the wwwroot/font folder and link it in your css:
/*default version*/
@font-face {
    font-family: 'lovelyFont';
    src: url('fonts/lovely_font.eot');
    src:
        local('Lovely Font'),
        local('Lovely-Font'),
        url('fonts/lovely_font.otf')
        format('opentype');
}
/*bold version*/
@font-face {
    font-family: 'lovelyFont';
    src: url('fonts/lovely_font_bold.eot');
    src:
        local('Lovely Font Bold'),
        local('Lovely-Font-Bold'),
        url('fonts/lovely_font_bold.otf')
        format('opentype');
    font-weight: bold;
}
/*container element*/
div { font-family: 'lovelyFont', sans-serif; }
/*span elements inside the container div*/
span { font-weight: bold; }

be sure to check out the link for this one.
Summary
I'd clearly go with the CDN / FontAwesome Approach, as it provides much more usability. Browse for any Icon you'd like and just easily include it. On the other hand, it also adds a new dependency to your project, which is not alaways a desired choice.
If so use the approach to Deliver your own font. Make sure it contains the Icons you need and you're good to go. This solution would be best to use, if you really needed to provide your very own font. It could also be containing a simplified version of your companys logo or whatever.
I hope this clears things up for you. If you're interested in why your current solution doesn't work have a look at terence eden's Answer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android WebView: Is it possible to detect URL hash change? I need to detect URL hash changes in an Android WebView but can't find any way to do so.  shouldOverrideUrlLoading() fires on the initial page load, but does not fire for any subsequent hash changes once the page has loaded.
Is this even possible with the Android WebView?

A: It is possible.
You have to declare a Javascript Interface like this :
private class MyJSI {
         public void doStuff()
         {
         }
}

And link your webview with the Javascript Interface like this :
webView.addJavascriptInterface(new MyJSI(), "myjsi");

Then, you have to write some javascript code when the page is loaded, to call the function doStuff on hash change.
webview.setWebViewClient(new WebViewClient() {

         public void onPageFinished(WebView view, String url)
         {
                 view.loadUrl("javascript:window.onhashchange = function() { myjsi.doStuff(); };");
         }
});

I hope it helps. I have tested it, and it works.


text:
Q: Custom Accordion I have the accordion below which works but when an item is open if you click it again it re opens instead of closing.
I'm not sure of the best way to adapt the code below to achieve this?
Any help or advice would be great?
Thanks
$('.acc h2').click(function() {
    $('.acc h2.open').nextUntil('h2').stop(true, true).slideToggle();
    $('.acc h2.open').removeClass('open');
    $(this).nextUntil('h2').stop(true, true).slideToggle(900);
    $(this).toggleClass('open');
});

1. Title 1

text 1

2. Title 2

text 2

3.  Title 3

text 3

A: Solution :
$('.acc h2').next('div').hide();
$('.acc h2').click(function() {
if($(this).next('div').is(':visible'))
{
    $(this).next('div').slideUp();
}
else{
    $('.acc h2').next('div').slideUp();
    $(this).next('div').slideToggle();
}
});

Demos :
http://jsfiddle.net/5NAhV/1/
or
http://jsfiddle.net/5NAhV/2/

A: Problem with toggle is that when user clicks multiple times, the animation starts to queue which is a pain.
Here's an alternative:
http://jsfiddle.net/adaz/5NAhV/3/
edit:
http://jsfiddle.net/5NAhV/2/ yeah, is(":visible") does the job!


text:
Q: How To Fetch Date type attribute from core data in swift? In My Notes Application I Want to Add A Option Of Task Expiry Date or Target Date for That I Save Date From UIDatePicker in Coredata, But Now How I Fetch It?? I Want to fetch It And Store It In Label..... Please Give Me Answer

A: This is how you can read out values from CoreData:
// context is your NSManagedObjectContext
var fetchRequest = NSFetchRequest(entityName: "YourEntity")
myData = context!.executeFetchRequest(fetchRequest, error: nil) as [YourCoreDataClass]

So in myData there is an Array of Objects - if there is only 1 object stores, check out with:
if(myData.count > 0) {
   myLabel.text = myData.last!.property //(the property here for the last entry)
}

You could also you a predicate, to filter your Objects (like for a specific value)
let myPredicate = NSPredicate(format: "id = %@", anyValue)
fetchRequest.predicate = myPredicate

And read more here:
https://developer.apple.com/library/ios/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectContext_Class/index.html


text:
Q: AngularJS Javascript + $scope data So I've been trying to figure this out all day and maybe I'm just overlooking something really simple. Here's my problem: I have a nice Nodejs/AngularJS app setup that's using Jade for templating. I do some stuff on the server and eventually get some values back that are rendered in the Jade template by Angular. I have some javascript that needs to run in that view which requires those values that get passed in. However when I test it, that javascript is never run (and even if it did run I'm not sure if those values I passed in would be available to my inline javascript!)
Here's a little example of what I'm trying to do (the Jade partial):
script.
    //Passed in from server
    var thing = {{data.thing}};
    var anotherThing = {{data.anotherThing}};

    function doSomething(a, b) {};

    doSomething(thing, anotherThing);

A: Im not entirely sure but I think you should try the following:
script.
    //Passed in from server
    var thing = "#{data.thing}";
    var anotherThing = "#{data.anotherThing}";

    function doSomething(a, b) {};

    doSomething(thing, anotherThing);

This isn't getting clear on the new jade page. They had an old doku on their github page which was more specific (you can find it here on webarchive, although that is quite ugly).
Hope that helps!
EDIT: HERE is the old version on github. This one covers far more stuff.

A: So I think I can do what I want to do with AngularJS Directives.
However, the reason why the javascript wasn't executing was because AngularJS (based on jqlite) doesn't see the < script> tags as special - so the solution is to just include the full version of jQuery before AngularJS (source).


text:
Q: How to align the header and the column properly in prawn pdf? We are generating pdf for invoice with prawn in rails 3.1.4.
  header =[[  "Date", "#", "sample name", "model","lease item", "hours", "$/hour", "Total"]]
  items = @invoice.invoice_items.map do |item|
    [
                item.lease_usage_record.lease_usage_items.map do |li|
                [
                  li.lease_date.strftime("%Y-%m-%d"),
                  item.lease_usage_record_id,
                  li.sample_name,
                  li.sample_model_num,
                  li.lease_item.short_name,
                  li.total_hour,
                  li.charge_rate,
                  li.subtotal
                ]
                end
    ]
  end
items = header + items
pdf.table items, :header => true, :width => 480
t = pdf.make_table([ ["                                                       ", "Total:     ","    #{@invoice.total}"] ])
t.draw

It works with a problem. The problem is that all the data cells are squeezed into the first column which is "Date". Tried to add one one more [] to header and it generated error of "data is 2-dimensional array...". How to align each column properly under its header? Thanks so much.

A: The problem was solved by reducing the dimension of the data (items) to 2 dimension. The prawn can only take 2 dimensional data. The following line does the trick:
items = items.flatten(2)


text:
Q: Grunt, Less, and File Watching I'm trying to get grunt working to do something. My project looks like this:
/app
    /assets
        /components
        /stylesheets
            /less
                /file1.less
                /file2.less
                /file3.less
                /importAll.less
            /css

I want it so that when file1, file2, or file3 are saved the importAll.less file is compiled into css and put into /css/style.css. This is as far as I got.
less: {
    development: {
        options: {
            paths: ["./assets/stylesheets/less"],
            yuicompress: true
        },
        files: {
            "./assets/stylesheets/css/style.css": "./assets/stylesheets/less/importAll.less"
        }
    }
}

I'm not sure how to get the file watcher working.

A: I got it working with the following!
module.exports = function(grunt) {
    grunt.initConfig({
        less: {
            development: {
                options: {
                    paths: ["./assets/stylesheets/less"],
                    yuicompress: true
                },
                files: {
                    "./assets/stylesheets/css/style.css": "./assets/stylesheets/less/style.less"
                }
            }
        },
        watch: {
            files: "./assets/stylesheets/less/*",
            tasks: ["less"]
        }
    });
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-contrib-watch');
};


text:
Q: proper expand command line parameter in bash I want to display what I'm running, but when the commands contain space parameter, it failed.
#!/bin/bash
go() {
  echo "*** $*"
  $* || exit 1
}
go make NAME="Hi Here"

That will get wrong behavior like
make NAME=Hi Here

Is there any better method to improve the go() function?

A: Replace $* with "$@":
#!/bin/bash
go() {
  echo "*** $*"
  "$@" || exit 1
}
go make NAME="Hi Here"


text:
Q: Am I using SOAP if I have a web service? Say I create a simple web service that adds two numbers together.  I send the service two numbers, I get back an answer.  If you like better, I send an account, I get back personal information.
Either way, am I using soap and not knowing it?  I thought I was calling my web service with an http url and my service is returning xml or json.  Where is soap in this?
Thanks.

A: It could be SOAP - or it could be REST.
What technologies are you using on the server and the client??
Indicators for SOAP:

*

*Did you define your service using a WSDL (Web Service Description Language) ?

*Does your service have methods that are verb-noun style, e.g. AddNumber or GetInfo ?

Indicators for REST:

*

*you don't have a WSDL

*you don't have service methods - you just use a resource identifier (URI) to get your information and you use the standard HTTP verbs like GET, POST, PUT etc. for "doing things"

As for the "where is SOAP in this" - read the Wikipedia article, check out the What Is SOAP? page, or research other places to get a feel for what SOAP is and does... in a nutshell: SOAP takes your input parameter, translates everything into a (XML) message and send that to the server for processing - and does the same thing with the response (XML) message coming back from the server.


text:
Q: How to disable rainbow-delimiters for Spacemacs? I've added dotspacemacs-excluded-packages '(rainbow-delimiters) at my .spacemacs file. (This is the only instance of the rainbow-delimiters at the whole file.) I've restarted Spacemacs and nothing happened. I still have the delimiters in a different color, which depends on my cursor position.

A: You can disable rainbow-delimiters-mode with
SPC t C d


text:
Q: Opening my app from a Reminder on IOS using objective C I have created an app that creates a reminder, adds a alarm with a structured location, and sets the URL to be my app.  My intention is that when the user sees this reminder on their phone and they click on it, it should open my app.  But this doesn't seem to be working.
What is working is that my app does create the reminder, it is geofenced, it is just that when the user clicks on the reminder they are taken to the IOS calendar and not my app.
Here's the code that I used to set the reminder URL:
  NSString* url = [NSString stringWithFormat: @"HealthTracker://"];
  self.reminder.URL = [NSURL URLWithString: url];

I also updated the URL schemes in the pinfo.list to contain the name of the app.
Screenshot of pinfo.list
Is there something else I should be doing?
I am targeting IOS 9.1 and using my IPhone 6 to test this.

A: Unlike calendar entries, reminders don't support URLs. Run the Reminders app and there is no way to add a URL.
The EKReminder has a URL property (inherited from CKCalendarItem) but the Reminders app itself doesn't support a URL.
I ran into the same problem and ended generating a Calendar event so the user can open my app from the event.
I submitted an enhancement request to Apple asking for the Reminders app to support URLs. Maybe in iOS 10.


text:
Q: Question about an exercise in Revuz/Yor I'm solving exercise 2.28 in Revuz/Yor. I was able to prove 1). Unfortunately at 2) I got stuck. I have to show:

Let $B$ be a d-dimensional Brownian motion and $A\in \mathcal{A}:=\cap_t \mathcal{A}_t$, where $\mathcal{A}_t:=\sigma(B_s;s\ge t)$. For any fixed $t$, there is an event $B\in \mathcal{A}$ such that $\mathbf1_{A}=\mathbf1_B\circ \theta_t$, ($\theta$ is the shift operator), then
  $$P_x[A]=\int P_y(B)P_t(x,dy)$$
  and conclude that either $P_\cdot[A]=0$ or $P_\cdot[A]=1$.

I did the following:
By Proposition 1.7 (Markov Property) I get:
$$E_x[\mathbf1_B\circ \theta_t|\mathcal{F}_t^0] =E_{B_t}[\mathbf1_B]$$
Well integrating the LHS, we get:
$$E_x[E_x[\mathbf1_B\circ \theta_t|\mathcal{F}_t^0]]=E_x[\mathbf1_A]=P_x[A]$$
Therefore I'm done with the first part, if
$$E_x[E_{B_t}[\mathbf1_B]]=\int P_y(B)P_t(x,dy)$$
My problem is, I do not see why this is true. It would be very nice if someone could tell me, why this equation is true. I run always in trouble using regular conditional probability. Also some hints for the second statement would be appreciated.
I'm very thankful for your help.
cheers
math

A: Define the function
$\phi(y)=E_y[\mathbf 1_B]$, that is, $\phi(y)=P_y(B)$. Then $E_{B_t}[\mathbf 1_B]$ is the random variable $\phi(B_t)$. The expected value of this random variable can be expressed in terms of the distribution $\nu$ of $B_t$ via $$E(\phi(B_t))=\int \phi(y)\, \nu(dy).\tag1$$ Under $E_x$, the distribution of $B_t$ is $\nu(dy)=P_t(x,dy)$, so substituting back into (1) gives
$$ E_x(E_{B_t}[\mathbf 1_B])=E(\phi(B_t))=\int P_y(B)\, P_t(x,dy). $$

A: You are starting from $x$, not from $0$, so what you wrote about $E_x(\mathbf1(B)\circ \theta_t|\mathcal F^0_t)$ is a bit confusing.To clarify the expression, you'd better write it as $E(\mathbf1(B)\circ \theta_t|\mathcal F^x_t)$. And the equation can be established more clearly:Firstly,thanks to strong markov property, $$E(\mathbf1(B)\circ \theta_t|\mathcal F^x_t)=E(\mathbf1(B)\circ \theta_t| B^x_t) $$ which is the conditional probability of $B$ under the law of Brownian motion evaluated at time $t$ along with the starting point $x$.
And then you calculate the expectation of the above to achieve the probability, which is equal to
$$E(E(\mathbf1(B)\circ \theta_t| B^x_t))=\int P_y(B) P_t(x,dy)$$
The statement then holds.
This question want you to confirm zero-one-law under any starting point of Brownian motion.


text:
Q: Is there any solution for failing to load model in tensorflow2.3? I try to use tf.keras.models.load_model to load saved model in tensorflow 2.3.
However, I got the same error in
https://github.com/tensorflow/tensorflow/issues/41535
It seems an important function. But this issue is still not solved. Does anyone know if there is any alternative method to implement the same result?

A: I found an alternative method to load custom model in tensorflow 2.3. You need to do some following changes. I will explain by some code snapshots

*

*for __init__() of custom model. Before,
def __init__(self, mask_ratio=0.1, hyperparam=0.1, **kwargs):
    layers = []
    layer_configs = {}
    if 'layers' in kwargs.keys():
        layer_configs = kwargs['layers']
    for config in layer_configs:
        layer = tf.keras.layers.deserialize(config)
        layers.append(layer)
    super(custom_model, self).__init__(layers)  # custom_model is your custom model class
    self.mask_ratio = mask_ratio
    self.hyperparam = hyperparam
    ...

After,
def __init__(self, mask_ratio=0.1, hyperparam=0.1, **kwargs):
    super(custom_model, self).__init__()  # custom_model is your custom model class
    self.mask_ratio = mask_ratio
    self.hyperparam = hyperparam
    ...

*define two functions in your custom model class
def get_config(self):
    config = {
        'mask_ratio': self.mask_ratio,
        'hyperparam': self.hyperparam
    }
    base_config = super(custom_model, self).get_config()
    return dict(list(config.items()) + list(base_config.items()))
@classmethod
def from_config(cls, config):
    #config = cls().get_config()
    return cls(**config)

*After finishing training, save model using 'h5' format
model.save(file_path, save_format='h5')

*Finally, load model as following codes,
model = tf.keras.models.load_model(model_path, compile=False, custom_objects={'custom_model': custom_model})


text:
Q: Multiple labels per item on Kendo chart I'm trying to get multiple label per item on Kendo Column chart
Desired layout looks like this

I was able to get only this layout
import { Component } from '@angular/core';
import { groupBy, GroupResult } from '@progress/kendo-data-query';
import { ValueAxisLabels } from '@progress/kendo-angular-charts';

export type TrendItem = {
  clientName: string;
  periodName: string;
  income: number;
};

@Component({
  selector: 'my-app',
  template: `
        <kendo-chart>
          <kendo-chart-category-axis>
              <kendo-chart-category-axis-item [categories]="categories">
              </kendo-chart-category-axis-item>
          </kendo-chart-category-axis>

          <kendo-chart-value-axis>
              <kendo-chart-value-axis-item [labels]="valueAxisLabels">
              </kendo-chart-value-axis-item>
          </kendo-chart-value-axis>

          <kendo-chart-series>
            <kendo-chart-series-item *ngFor="let groupedResult of groupedTrendsByPeriod" [data]="groupedResult.items" field="income" type="column">
              <kendo-chart-series-item-labels [content]="labelVisual">
              </kendo-chart-series-item-labels>
           </kendo-chart-series-item>
          </kendo-chart-series>
        </kendo-chart>
    `,
})
export class AppComponent {
  public valueAxisLabels: ValueAxisLabels = {
    font: 'bold 16px Arial, sans-serif',
  };

  public trendItems: TrendItem[] = [
    {
      clientName: 'Client1',
      periodName: 'Q1 2020',
      income: 20,
    },
    {
      clientName: 'Client1',
      periodName: 'Q2 2020',
      income: 15,
    },
    {
      clientName: 'Client1',
      periodName: 'Q3 2020',
      income: 35,
    },
    {
      clientName: 'Client1',
      periodName: 'Q4 2020',
      income: 40,
    },
    {
      clientName: 'Client2',
      periodName: 'Q1 2020',
      income: 15,
    },
    {
      clientName: 'Client2',
      periodName: 'Q2 2020',
      income: 20,
    },
    {
      clientName: 'Client2',
      periodName: 'Q3 2020',
      income: 15,
    },
    {
      clientName: 'Client2',
      periodName: 'Q4 2020',
      income: 30,
    }
  ];

  public categories = (groupBy(this.trendItems, [{ field: 'clientName' }]) as GroupResult[])
    .map((e) => e.value);

  public groupedTrendsByPeriod = groupBy(this.trendItems, [{ field: 'periodName' }]) as GroupResult[];

  public labelVisual(e: { dataItem: TrendItem }) {
    return `$${e.dataItem.income}\r\n${e.dataItem.periodName}`;
  }
}

You can try this code here.
My current result look like this

So my question is how to display multiple labels per item like on the first picture?

My current obstacles.

*

*I didn't find a way to add multiple <kendo-chart-series-item-labels> elements. Only one will be rendered, rest will be ignored.

*I didn't find a way to position labels below column chart. For column chart it's only possible to use "center", "insideBase", "insideEnd", "outsideEnd" options (according to API Reference) but none of them gives me desired position.

A: You can use the notes feature of the KendoChartComponent.
You can see the implementation here.

*

*You add noteTextField="periodName" [notes]="notesOptions" to your kendo-chart-series-item element.

*You add [labels]="labelOptions" to your kendo-chart-category-axis-item element.

*You add the following to your component:
public notesOptions = {
    position: 'bottom',
    icon: {
        visible: false,
    },
    label: {
        color: 'black',
        content: (e) => e.dataItem.periodName,
        font: "12px Arial",
        margin: -30,
    },
    line: {
        width: 0,
    },
};

public labelOptions = {
    margin: {
        top: 10,
    },
};

*Change the labelVisual function return value to `$${e.dataItem.income}\`.
Note: Some changes can be performed and still give the desired design so if something isn't exactly right, it's probably fixable.
Here is an image of the resulting chart:

A: I don't think kendo provides any native solution for that but what I can suggest is to:

*

*Use legends to display each bar meaning. like the example here.

*Use some self generated labels and position them under the table which is risky for UI. I provided an example here.


text:
Q: C# restrict editing partial word paragraph
allow users to edit the yellow paragraph.
But I get this document:
wrong document
I use word restrict editing feature, my code is :
//写入段落
foreach (TaskChaptersModel chapter in listChapter)
{
    paragraph = doc.Content.Paragraphs.Add();
    paragraph.Range.Text = chapter.chapterNo + " " + chapter.chapterName;

    //标题1
    if (!chapter.chapterNo.Contains("."))
    {
        paragraph.Range.Font.Name = "宋体";//宋体
        paragraph.Range.Font.Bold = 2;//加粗
        paragraph.Range.Font.Size = 16;//三号
        paragraph.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
    }
    else if (chapter.chapterNo.Select(c => c == '.').Count() == 1)
    {
        paragraph.Range.Font.Name = "宋体";//宋体
        paragraph.Range.Font.Bold = 2;//加粗
        paragraph.Range.Font.Size = 16;//三号
        paragraph.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;//左对齐
        paragraph.Format.LineSpacingRule = Word.WdLineSpacing.wdLineSpace1pt5;
    }
    else
    {
        paragraph.Range.Font.Name = "宋体";//宋体
        paragraph.Range.Font.Size = 12;//三号
        paragraph.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;//左对齐
        paragraph.Format.LineSpacingRule = Word.WdLineSpacing.wdLineSpace1pt5;
    }
    paragraph.Range.InsertParagraphAfter();

    //-------------------------------------------------------------------
    //This paragraph alow edit
    paragraph = doc.Content.Paragraphs.Add();
    paragraph.Range.Text = "请您编辑,张三";
    paragraph.Range.Editors.Add(Word.WdEditorType.wdEditorEveryone);
    paragraph.Range.InsertParagraphAfter();
    //-------------------------------------------------------------------
}

doc.Protect(Word.WdProtectionType.wdAllowOnlyReading, false, "000", false, true);

My idea is to add editor at Specified paragraph.

A: Your idea is right to start with, however Word acts a little bit different than expected. I noticed, just like you, that however adding new paragraphs the new paragraps could be edited even though you didn't specifically added Editors to the new paragraph.
So, you need to turn it around, by adding everyone to the complete document and working the other way around by removing the editors from the parts that you want to protect.
To give you an idea I created a little piece of VBA code but I'm sure you can rewrite the parts you need in C#. Also note that I loop over the editors deleting them individually instead of using DeleteAll(). I found that using DeleteAll was throwing unexpected exceptions.
Sub TestRestrictDocument()

    If ActiveDocument.ProtectionType <> wdNoProtection Then
        ActiveDocument.Unprotect "000"
    End If

    ActiveDocument.Content.Editors.Add Word.WdEditorType.wdEditorEveryone

    Dim paragraph As paragraph

    For I = 1 To 5

        Set paragraph = ActiveDocument.Paragraphs(I)

        If I <> 4 Then
            paragraph.Range.Select

            Dim objEditor As Editor

            If Selection.Editors.Count > 0 Then
                For X = 1 To Selection.Editors.Count
                    Selection.Editors(X).Delete
                Next
            End If
        End If

    Next

    ActiveDocument.Protect Word.WdProtectionType.wdAllowOnlyReading, False, "000", False, True

End Sub

This example shows you that (I created a document with 5 paragraphs to test) all but the fourth paragraphs can be edited. Obviously you can dynamically create your document and remove the Editors on that.
Some side notes to keep in mind that I ran into that might help:

*

*always check if your document is already protected

*always test if the range has Editors to delete

*Avoid DeleteAll on Editor for some reason

A: Got it:
1、create the doc
2、loop all paragraphs add editor at the right paragraph
I found that I can't add editor when the doc is create.
//写入段落
foreach (TaskChaptersModel chapter in listChapter)
{
    if (chapter.chapterNo == null || chapter.chapterNo == "-1")
    {
        continue;
    }

    paragraph = doc.Content.Paragraphs.Add();
    paragraph.Range.Text = chapter.chapterNo + " " + chapter.chapterName;

    //标题1
    if (!chapter.chapterNo.Contains("."))
    {
        paragraph.Range.Font.Name = "宋体";//宋体
        paragraph.Range.Font.Bold = 2;//加粗
        paragraph.Range.Font.Size = 16;//三号
        paragraph.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
    }
    else if (chapter.chapterNo.Select(c => c == '.').Count() == 1)
    {
        paragraph.Range.Font.Name = "宋体";//宋体
        paragraph.Range.Font.Bold = 2;//加粗
        paragraph.Range.Font.Size = 16;//三号
        paragraph.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;//左对齐
        paragraph.Format.LineSpacingRule = Word.WdLineSpacing.wdLineSpace1pt5;
    }
    else
    {
        paragraph.Range.Font.Name = "宋体";//宋体
        paragraph.Range.Font.Size = 12;//三号
        paragraph.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;//左对齐
        paragraph.Format.LineSpacingRule = Word.WdLineSpacing.wdLineSpace1pt5;
    }

    paragraph.Range.InsertParagraphAfter();
    paragraph = doc.Content.Paragraphs.Add();
    //有编辑权限
    if (chapter.wordFlag == "E")
    {
        paragraph.Range.Text = "请您编辑," + userName;
    }
    else
    {
        paragraph.Range.HighlightColorIndex = Word.WdColorIndex.wdGray25;
    }
    paragraph.Range.InsertParagraphAfter();
}

foreach (Word.Paragraph p in doc.Paragraphs)
{
    if (p.Range.Text.Contains("请您编辑"))
    {
        p.Range.Select();
        p.Range.Editors.Add(Word.WdEditorType.wdEditorEveryone);
    }
}


text:
Q: Cálculo Digito de control código de barras Estoy realizando una pequeña aplicación que me permita calcular el dígito de control del código de barras, pero utilizando la librería Tkinter de python.
EL algoritmo que calcula el dígito es:
EAN = "123456789041"

def eanCheck(ean):
    checksum = 0
    for i, digit in enumerate(reversed(ean)):
        checksum += int(digit) * 3 if (i % 2 == 0) else int(digit)

    return (10 - (checksum % 10)) % 10

print "Digito de control: %d" %eanCheck(EAN)

Me gustaría que me indicaran cómo adaptarlo a una interfaz gráfica básica en Tkinter mediante la que se introduzcan números en una ventana y al pulsar un botón calcule el dígito automáticamente.

A: Aquí tienes una sencilla implementación. He comentado el código para que pueda servirte para aprender y para que lo extiendas como necesites.
from tkinter import Tk, Label, Button, Entry, StringVar, END, W, E

class EANCalculator:

    def __init__(self, master):
        self.master = master
        master.title("Barcode")

        # Variables con la entrada del usuario (ean) y la salida producida
        self.ean = ""
        self.digito_control = ""

        # La salida la mostraremos en una Label (cuyo valor podremos cambiar)
        self.texto_digito_control = StringVar()
        self.texto_digito_control.set("")
        self.digito_control_label = Label(master, textvariable=self.texto_digito_control)

        # Delante de la cual pondremos otra Label con texto prefijado
        self.label = Label(master, text="Digito de control:")

        # Registramos un validador de modo que cada vez que el usuario escriba un
        # nuevo dígito, el validador será ejecutado. Lo usaremos para permitir
        # que sólo pueda introducir dígitos y no otros símbolos
        vcmd = master.register(self.validate)
        self.entry = Entry(master, validate="key", validatecommand=(vcmd, '%P'))

        # Un par de botones. Uno para calcular y mostrar el dígito de control
        # el otro para borrar la caja de entrada de texto
        self.boton = Button(master, text="OK", command=self.update_digito_control)
        self.boton_borrar = Button(master, text="Borrar", command=self.borrar)

        # Los elementos anteriores no son visibles hasta que no los pongamos en un "layout"
        # En este caso uso como layout un grid con tres filas y 2 columnas
        self.label.grid(row=0, column=0, sticky=W)
        self.digito_control_label.grid(row=0, column=1, sticky=E)
        self.entry.grid(row=1, column=0, columnspan=2, sticky=W+E)  # La entrada ocupa 2 columnas
        self.boton_borrar.grid(row=2, column=0)
        self.boton.grid(row=2, column=1)

    def validate(self, new_text):
        # Esta función verifica que lo que el usuario va introduciendo es un entero válido
        # Es llamada cada que vez que se pulsa una nueva tecla en la caja de entrada, o cuando
        # la entrada es borrada
        if not new_text:   # Si no hay texto nuevo, es que se ha borrado
            self.ean = ""  # Reiniciar la variable interna y dar la entrada por buena
            return True
        try:
            int(new_text)  # Mirar si se puede interpretar como entero
        except:
            return False   # No admitirlo de no ser así
        # Admitirlo (guardarlo y retornar True)
        self.ean = new_text

        # Si descomentas la línea siguiente, el dígito de control se actualizará a medida
        # que el usuario va introduciendo el código de barras. En este caso el botón OK
        # sería supérfluo
        # self.update_digito_control()
        return True

    def borrar(self):
        # Borrar la entrada y las variables asociadas
        self.texto_digito_control.set("")
        self.ean = ""
        self.entry.delete(0, END)

    def update_digito_control(self):
        # Calcular un nuevo dígito de control y mostrarlo en el elemento adecuado del GUI
        self.texto_digito_control.set(str(self.eanCheck(self.ean)))

    def eanCheck(self, ean):
        # Esta es la función que dabas en la pregunta
        checksum = 0
        for i, digit in enumerate(reversed(ean)):
            checksum += int(digit) * 3 if (i % 2 == 0) else int(digit)
        return (10 - (checksum % 10)) % 10

# Arrancar el bucle principal de eventos
root = Tk()
my_gui = EANCalculator(root)
root.mainloop()

Ejemplo en ejecución:


text:
Q: How can I upload a video to a specific YouTube channel without using the OAuth URL? I have a problem that in theory should be easy, but I have been at this for days and just can't get it to work.
I have a Google account to which a few aliases are connected (The main gmail, a test thing I made a long time ago and a youtube channel). I render my videos on a cloud server and would like to then automatically upload them to this channel. I don't want to have to open the URL because this should work unattended. And by god, I can't figure it out. It's pretty baffling in how bad a state Google's official API docs are (or how dumb I am). I am using Python and Google's official client
So far, I've modified the python upload example from the python examples to incorporate service auth as described here. This alone took me way too long to figure out, I think Google's newer key format is bugged. If I run this as is, I get a "youtubeSignupRequired" error, because the main account doesn't have a youtube channel. After hours of research I found this link that pretty poorly describes the onBehalf parameters, but it seems these require a YouTube CMS account, which I don't have and I don't think I will get.
Am I missing something extremely obvious here? This seems like something that should not be hard to do at all.


text:
Q: What do the after battle bonuses do and how do I get them In Bravely Default if you meet certain conditions during battle, such as taking no damage, defeating all enemies in one turn, or defeating 2+ enemies with a single attack, you get bonuses after battle. If you do it in multiple battles in a row, you can get upgraded versions of these bonuses. What are the possible bonuses, and what benefit do they provide?

A: There are three combat bonus "types": 1-Turn Victor, Unscathed, and Sweeper. 1-Turn Victor boosts the amount of EXP you get from the battle, Unscathed increases the number of JP (Job Points) you get, and Sweeper boosts how much money you receive.
Each of these bonuses come in three gradations: normal, Ace, and Hero. These grades are earned after 1, 5, and 10 battles in a row respectively. The amount of extra points that each combat bonus gives depends on what monsters you are fighting as they are percent increases, rather than flat increases. Normal grants a 10% increase, Ace is 20%, and Hero earns you 50% more.


text:
Q: What are mobile and wear modules? The WearHttp library is a library for communicating with web content :
https://github.com/takahirom/WearHttp
To implement this it states :
In Mobile and Wear module build.gradle:
You must be implemented in both the Mobile and Wear

dependencies {
    ...
    compile 'com.kogitune:wear-http:0.0.5'
}

I have an application module and Wearable module.
Do these correspond to Mobile and Wear modules respectively ?


text:
Q: How to get the process id of adobe when it is running in my MFC project? I create a MFC project, this MFC project hosts an Adobe ActiveX control.
When I start my MFC project, the adobe active control will launched the Adobe process under it.

This is my task manager under windows 10, you can clearly see that Adobe process is launched by my project.
But how can I get the process id of the Adobe process which is launched by my project ?
I am using the adobe active x control sample code from this link :
https://www.codeproject.com/Articles/9537/Adobe-ActiveX-Control-with-MFC
class CAcroAXDocShim
The reason why I need to get the pid is that I need to capture the mouse event over the pdf when it is displayed in active x control.
If I use the following function:
LowLevelMouseProc callback function

I need to pass the process id of adobe into it. If I passed 0 as the id, then it will capture all mouse input event for whole system.


text:
Q: Ionic row has width of 0px I'm trying to use the example from this link (Most of the code is not very important but rather the minor change I added is all the difference):
http://codepen.io/psutherland/pen/seiwE

angular.module('ionic.example', ['ionic'])

    .controller('MapCtrl', function($scope, $ionicLoading, $compile) {
      function initialize() {
        var site = new google.maps.LatLng(55.9879314,-4.3042387);
        var hospital = new google.maps.LatLng(55.8934378,-4.2201905);

        var mapOptions = {
          streetViewControl:true,
          center: site,
          zoom: 18,
          mapTypeId: google.maps.MapTypeId.TERRAIN
        };
        var map = new google.maps.Map(document.getElementById("map"),
            mapOptions);

        //Marker + infowindow + angularjs compiled ng-click
        var contentString = "
Click me!
";
        var compiled = $compile(contentString)($scope);

        var infowindow = new google.maps.InfoWindow({
          content: compiled[0]
        });

        var marker = new google.maps.Marker({
          position: site,
          map: map,
          title: 'Strathblane (Job Location)'
        });

        var hospitalRoute = new google.maps.Marker({
          position: hospital,
          map: map,
          title: 'Hospital (Stobhill)'
        });

        var infowindow = new google.maps.InfoWindow({
             content:"Project Location"
        });

        infowindow.open(map,marker);

        var hospitalwindow = new google.maps.InfoWindow({
             content:"Nearest Hospital"
        });

        hospitalwindow.open(map,hospitalRoute);

        google.maps.event.addListener(marker, 'click', function() {
          infowindow.open(map,marker);
        });

        $scope.map = map;

        var directionsService = new google.maps.DirectionsService();
        var directionsDisplay = new google.maps.DirectionsRenderer();

        var request = {
            origin : site,
            destination : hospital,
            travelMode : google.maps.TravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            }
        });

        directionsDisplay.setMap(map);

      }

      google.maps.event.addDomListener(window, 'load', initialize);

      $scope.centerOnMe = function() {
        if(!$scope.map) {
          return;
        }

        $scope.loading = $ionicLoading.show({
          content: 'Getting current location...',
          showBackdrop: false
        });
        navigator.geolocation.getCurrentPosition(function(pos) {
          $scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
          $scope.loading.hide();
        }, function(error) {
          alert('Unable to get location: ' + error.message);
        });
      };

      $scope.clickTest = function() {
        alert('Example of infowindow with ng-click')
      };

    });
#map {
  width: 100%;
  height: 100%;
}

.scroll {
  height: 100%;
}

    <meta charset="utf-8">
    <title>Map</title>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">

    <link href="//code.ionicframework.com/1.0.0-beta.12/css/ionic.css" rel="stylesheet">

    <ion-header-bar class="bar-dark" >

Google Maps Example

    </ion-header-bar>
    <ion-content>

    </ion-content>
    <ion-footer-bar class="bar-dark">
      Find Me
    </ion-footer-bar>

But when I add
 around the div with the "map" id as follows:

The map becomes invisible and I see that the width is 0. I can't understand why the "row" class would have this affect.

A: The issue is not specifically about the class "row" (any other class would have the same effect). The cause seems to be, that the content of the div has position: absolute, and therefore the containing div does not stretch automatically with the content. To fix it, just add explicit width and height properties:
.row {
  width: 100%;
  height: 100%;
}

See http://codepen.io/ramtob/pen/jbwbjZ


text:
Q: How to make internal processing encoding change to UTF8 in PHP? Currently in my application the utf8 encoded data is spoiled by internal coding of PHP.
How to make it consistent with utf8?
EDIT:To show examples,please tell me how to output the current internal encoding in PHP?
In php.ini I found the following:
default_charset = "iso-8859-1"

Which means Latin1.
How to change it to utf8,say,what's the iso version of utf8?

A: Change it to:
default_charset = "utf-8"
There is no ISO version of UTF-8.
You'll need to be specific with the details since encoding can be mangled at many different areas in your PHP application.
The common problem areas are:
Saving and retrieving from DB:
The database encoding must the same as the strings sent to it from PHP, or you must convert the strings to the DB encoding.
PHP4's single byte string functions:
PHP's functions such as strlen(), str_replace() do not produce the correct results on multibyte encodings such as UTF-8, since they operate on single bytes.
Page encoding:
Make sure the browser knows you are sending it UTF-8.

A: You can change the character encoding in php file. To change encoding in php page use the following function.
$new_value = htmlentities('$old_value',ENT_COMPAT, "UTF-8");

and also you can add the following in the html head section
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

I hope this will help to solve your problem.


text:
Q: Adding facebook custom tabs using URL method, no longer working we can still add some of our custom apps to customers pages.
every now and then we get a content error when using the URL method as below
http://www.facebook.com/dialog/pagetab?app_id=xxxx&next=ScriptURLxxxx/exec?tabpage=TABNAME
This works 99% of the time, although a new onboarding we receive the error "Content is not available right now", I then tried this same method on another page and worked fine.
Below is a method I found on Facebook Dev page. Although for the life of me cannot get it to authenticate when running the Curl commands with correct variables.
Has anyone had this whilst adding Facebook Custom App Tabs
Thanks


text:
Q: How do I Update the only field that is being chosen by the user from Dropdown List in my stored Procedure? I have stored Procedure, that i am using in ADO.NET code. When the user selects some value from dropdown, it should update only that value and not pass null values in other columns. I am not able to implement this logic.
ALTER PROCEDURE [dbo].[sp_UpdateEmployeeField]
(
@id INTEGER,
@first_name VARCHAR(10),
@last_name VARCHAR(10),
@salary DECIMAL(10,2),
@city VARCHAR(20)
)
AS
    UPDATE [EMPLOYEE] SET [first_name] =COALESCE(first_name,@first_name),
                          [last_name] =COALESCE(last_name,@last_name),
                          [salary]=COALESCE(salary,@salary),
                          [city]=COALESCE(city,@city)
                          WHERE [id] =@id

Corresponding ADO.NET code:
using (SqlConnection con = new SqlConnection(CS))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand("sp_UpdateEmployeeField", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@id",TextBox7.Text);
                    if (DropDownList2.SelectedValue == "first_name")
                    {
                        cmd.Parameters.AddWithValue("@first_name", TextBox8.Text);
                    }

                    if (DropDownList2.SelectedValue == "last_name")
                    {
                        cmd.Parameters.AddWithValue("@last_name", TextBox8.Text);
                    }

                    if (DropDownList2.SelectedValue == "salary")
                    {
                        cmd.Parameters.AddWithValue("@salary", TextBox8.Text);
                    }

                    if (DropDownList2.SelectedValue == "city")
                    {
                        cmd.Parameters.AddWithValue("@city", TextBox8.Text);
                    }

                    con.Open();
                    int count = cmd.ExecuteNonQuery();
                    if (count != 0)
                        Label2.Text = "Information Updated";
                    else
                        Label2.Text = "Information not updated";
                    con.Close();
                    con.Dispose();
                }
                catch (SqlException exception)
                {
                    Console.WriteLine(exception);
                }
            }

A: I think your coalesce()s are backwards:
UPDATE [EMPLOYEE]
    SET [first_name] = COALESCE(@first_name, first_name),
        [last_name] = COALESCE(@last_name, last_name),
        [salary] = COALESCE(@salary, salary),
        [city] = COALESCE(@city, city)
    WHERE [id] = @id;

Your version only changes the column names when the column values are NULL.  This version changes the value to the new value when the new value is not NULL.


text:
Q: Retornando o valor de um ponteiro Preciso criar uma função que tenha o funcionamento idêntico à função strcat. A princípio me parecia uma tarefa bastante simples, porém quando printo o retorno da função ft_strcat() isto acontece:
Sendo pont = dest então por que retornam coisas diferentes?

*

*Definição da função:

char *ft_strcat(char *dest, char *src) {
    char *pont;

    pont = dest;

    for(; *dest; dest++){
    }
    for(; *src; ){
        *dest++ = *src++;
    }
    *dest = '\0';
    return dest; /* return pont */
}

*

*Resultado 1 (Retornando dest):

cd "/mnt/c/Users/ex02/" && gcc ft_strcat.c -o ft_strcat && "/mnt/c/Users/ex02/"ft_strcat

*

*Resultado 2, (Retornando pont):

*

*Resultado: cd "/mnt/c/Users/ex02/" && gcc ft_strcat.c -o ft_strcat && "/mnt/c/Users/ex02/"ft_strcat
hello world%

Código completo caso necessário:
#include<stdio.h>
#include<unistd.h>
char *ft_strcat(char *dest, char *src);

int main(void){
    char texto[20] = {"hello"};
    char fonte[20] = {" world"};

    printf("%s", ft_strcat(texto, fonte));

    return 0;
}

char *ft_strcat(char *dest, char *src) {
    char *pont;

    pont = dest;

    for(; *dest; dest++){
    }
    for(; *src; ){
        *dest++ = *src++;
    }
    *dest = '\0';
    return dest;
}

A: Quando você retorna dest... vc retorna pro terminal a ultima posição de dest(isso acontece porque vc incrementou ele ao longo da função); no seu caso a ultima posição dele é o '\0'. por isso não mostra nada.
pont retorna corretamente pq n usou ele pra andar posições na string, ele apenas recebeu tudo de dest.
Sua string no final seria "hello world\0" tendo 11 posições aí.
quando vc retorna dest ele retorna a posição 11 da string. pra resolver isso vc teria q retornar dest pro inicio da string..
char *ft_strcat(char *dest, char *src) {
char *pont;

pont = dest;

for(; *dest; dest++){
}
for(; *src; ){
    *dest++ = *src++;
}
*dest = '\0';
return (dest - (dest - pont)); // aqui seria dessa forma...  dest vale 11 e pont 0 logo no retorno ta acontecendo. 11 - (11 - 0) 11 - 11 da 0.. assim seu dest  volta pro inicio e o resultado mostra na tela

}
A imagem abaixo mostra uma representação visual


text:
Q: How to configure kubectl to connect to EKS using OIDC (Azure AD)? I have configured Azure AD application as OIDC provider, associated OIDC in config EKS. Now I want to access using kubectl but I am not able to do using the following config.
ERROR : Unable to connect to the server: No valid id-token, and cannot refresh without refresh-token
kubectl config set-credentials aman \
   --auth-provider=oidc \
   --auth-provider-arg=idp-issuer-url=<my azure one> \
   --auth-provider-arg=client-id=<my client id> \
   --auth-provider-arg=client-secret=<my secret id>

whereas I can connect using oidc plugins for kubectl with the same details.
What am I doing wrong ?
I don't understand why it is asking refresh tokens. Plus I don't have refresh tokens.
NOTE: I followed EKS official doc to configure https://docs.aws.amazon.com/eks/latest/userguide/authenticate-oidc-identity-provider.html and Kubernetes official doc to set kubectl https://kubernetes.io/docs/reference/access-authn-authz/authentication/#using-kubectl
Could anyone suggest anything where I don't need to use any oidc plugin with kubectl ?

A: So, I have been doing some research and I think I found the answer. I am posting my findings so that it can help if someone struggles with the same question.
The way Kubernetes is authenticating with kubectl is with bearer_token. Now a bearer_token consists of access_token and refresh_token. But we can only have id token and here the oidc plugin comes to play. According to the Kubernetes official doc i.e. https://kubernetes.io/docs/reference/access-authn-authz/authentication/
The first option is to use the kubectl oidc authenticator, which sets the id_token as a bearer token for all requests and refreshes the token once it expires.
In other words since EKS is providing only authentication with OIDC, it needs only id_token. Then we need the help of oidc plugin which can set our id_token as bearer_token. Hence we don't need to provide any refresh token with oidc authenticator plugins.
P.S.
Authorization is later taken care by RBAC features. In my case I mapped my AD groups to Kubernetes groups with roles and role bindings.


text:
Q: Measurement - get full unit name I'm not sure how to use measurement to get full name of the unit. For example "kilometers" instead of "km".
let measurement = Measurement(value: 50, unit: UnitLength.meters)
let convertedMeasurement = measurement.converted(to: UnitLength.kilometers)

let value = convertedMeasurement.value // 0.05
let unitSymbol = convertedMeasurement.unit.symbol // km
let unit = convertedMeasurement.unit.? // I expect the output to be "kilometers"

A: In order to get the full name of the unit you can use the MeasurementFormatter like so:
let formatter = MeasurementFormatter()
formatter.unitStyle = .long
let unit = formatter.string(from: convertedMeasurement.unit) //"kilometers"


text:
Q: Convert codepoint to utf-8 byte array in Java using shifting operations I have used this answer to "manually" convert from unicode to UTF-8 code units. The problem is that I need the resulting UTF-8 to be contained in a byte array. How can I do that by using shifting operations whenever possible to go from hexadecimal to uft-8?
The code I already have is the following:
 public static void main(String[] args)
   throws UnsupportedEncodingException, CharacterCodingException {

   String st = "ñ";

   for (int i = 0; i < st.length(); i++) {
      int unicode = st.charAt(i);
      codepointToUTF8(unicode);
   }
 }

 public static byte[] codepointToUTF8(int codepoint) {
    byte[] hb = codepointToHexa(codepoint);
    byte[] binaryUtf8 = null;

    if (codepoint <= 0x7F) {
      binaryUtf8 = parseRange(hb, 8);
    } else if (codepoint <= 0x7FF) {
      binaryUtf8 = parseRange(hb, 16);
    } else if (codepoint <= 0xFFFF) {
      binaryUtf8 = parseRange(hb, 24);
    } else if (codepoint <= 0x1FFFFF) {
      binaryUtf8 = parseRange(hb, 32);
    }

    byte[] utf8Codeunits = new byte[hexStr.length()];
    for (int i = 0; i < hexStr.length(); i++) {
      utf8Codeunits[i] = (byte) hexStr.charAt(i);
      System.out.println(utf8Codeunits[i]); // prints 99 51 98 49,
      // which is the same as c3b1, the UTF-8 for ñ
    }

    return binaryUtf8;
  }

  public static byte[] codepointToHexa(int codepoint) {
    int n = codepoint;
    int m;

    List<Byte> list = new ArrayList<>();
    while (n >= 16) {
      m = n % 16;
      n = n / 16;
      list.add((byte) m);
    }
    list.add((byte) n);
    byte[] bytes = new byte[list.size()];
    for (int i = list.size() - 1; i >= 0; i--) {
      bytes[list.size() - i - 1] = list.get(i);
    }

    return bytes;
  }

  private static byte[] parseRange(byte[] hb, int length) {

    byte[] binarybyte = new byte[length];
    boolean[] filled = new boolean[length];

    int index = 0;
    if (length == 8) {
      binarybyte[0] = 0;
      filled[0] = true;
    } else {
      int cont = 0;
      while (cont < length / 8) {
        filled[index] = true;
        binarybyte[index++] = 1;
        cont++;
      }
      binarybyte[index] = 0;
      filled[index] = true;
      index = 8;
      while (index < length) {
        filled[index] = true;
        binarybyte[index++] = 1;
        binarybyte[index] = 0;
        filled[index] = true;
        index += 7;
      }
    }

    byte[] hbbinary = convertHexaArrayToBinaryArray(hb);
    int hbindex = hbbinary.length - 1;

    for (int i = length - 1; i >= 0; i--) {
      if (!filled[i] && hbindex >= 0) {
        // we fill it and advance the iterator
        binarybyte[i] = hbbinary[hbindex];
        hbindex--;
        filled[i] = true;
      } else if (!filled[i]) {
        binarybyte[i] = 0;
        filled[i] = true;
      }
    }
    return binarybyte;
  }

 private static byte[] convertHexaArrayToBinaryArray(byte[] hb) {

    byte[] binaryArray = new byte[hb.length * 4];
    String aux = "";
    for (int i = 0; i < hb.length; i++) {

      aux = Integer.toBinaryString(hb[i]);
      int length = aux.length();
      // toBinaryString doesn't return a 4 bit string, so we fill it with 0s
      // if length is not a multiple of 4
      while (length % 4 != 0) {
        length++;
        aux = "0" + aux;
      }

      for (int j = 0; j < aux.length(); j++) {
        binaryArray[i * 4 + j] = (byte) (aux.charAt(j) - '0');
      }
    }

    return binaryArray;
  }

I don't know how to handle bytes properly, so I'm aware that the things I did are probably wrong.

A: UTF-8 fills Unicode code points as follows:
0xxxxxxx
110xxxxx 10xxxxxx
1110xxxx 10xxxxxx 10xxxxxx
11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
... (max 6 bytes)

Where the right most bit is the least significant one for the number.
static byte[] utf8(IntStream codePoints) {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final byte[] cpBytes = new byte[6]; // IndexOutOfBounds for too large code points
    codePoints.forEach((cp) -> {
        if (cp < 0) {
            throw new IllegalStateException("No negative code point allowed");
        } else if (cp < 0x80) {
            baos.write(cp);
        } else {
            int bi = 0;
            int lastPrefix = 0xC0;
            int lastMask = 0x1F;
            for (;;) {
                int b = 0x80 | (cp & 0x3F);
                cpBytes[bi] = (byte)b;
                ++bi;
                cp >>= 6;
                if ((cp & ~lastMask) == 0) {
                    cpBytes[bi] = (byte) (lastPrefix | cp);
                    ++bi;
                    break;
                }
                lastPrefix = 0x80 | (lastPrefix >> 1);
                lastMask >>= 1;
            }
            while (bi > 0) {
                --bi;
                baos.write(cpBytes[bi]);
            }
        }
    });
    return baos.toByteArray();
}

Except for the 7 bits ASCII the encoding can be done in a loop.


text:
Q: Access one to many relationship data I am learning to work with LINQ, EF etc. I have 2 auto generated edmx classes course and student. I have written a code to access the course id and course name. With the data I also want to fetch the data of the students names who have enrolled for the courses respectively. Following is my code.
testEntities1 t = new testEntities1();
                var u = (from g in t.courses
                         select new
                         {
                             g.C_Id,
                             g.C_Name,
                             dd = g.student.Select(r=>r.S_Name)

                         }).ToList();

Now how to use/get data from the property dd which i have selected which contains all the student names who have enrolled  for the course. I am able to put data to variable u. I just don't know how to proceed and get data out of dd. Please help. Following is the line for getting data of the course id and course name. How can I get the data of the student names.
List<course> ui = u.Select(d => new course() { C_Name = d.C_Name, C_Id = d.C_Id }).ToList();

A: First of all there is no need to fetch the data first into an anonymous type and then add it to your custom type course, you can do that directly as mentioned below. Now, since you have not mentioned the Type of course, I am considering following two possibilites:-
Case 1: If you have student names as public List<string> Students_Enrolled { get; set; } in course i.e. you want to fetch the list of students enrolled then:-
List<course> u = (from g in t.courses
                  select new course
                  {
                      C_ID = g.C_Id,
                      C_Name =  g.C_Name,
                      Students_Enrolled = g.student.Select(r => r.S_Name).ToList()
                  }).ToList();

Case 2: If you have student names as public string Students_Enrolled { get; set; } i.e. if you want to fetch comma separated student names then you can do this:-
List<course> u = (from g in t.courses
                  select new course
                  {
                      C_ID = g.C_Id,
                      C_Name =  g.C_Name,
                      Students_Enrolled = String.Join(",",g.student.Select(r => r.S_Name))
                  }).ToList();


text:
Q: Qt seems to leak memory everywhere I have big problems with memory leaks in Qt.
The problems is that when i run methods like:
qwidget->show();
qwidget->hide();
qwidget->setVisible(...);
qlabel->setText(...);
qwidget->setEnabled(...);

then it leaks memory.
I do not create any objects on the fly. I have created all widgets on startup and I just hiding and showing widgets and changing text on some labels all the time.
And when I remove those methods, then it doesn't leaks memory at all.
Is there someone who know why it is that way or if someone knows what happens under the hood? Or does Qt have memory problems?
I run windows 7 x64 with Qt 5.0.1 x64 in release mode.

Now i have added a test code:
#include "qtmemoryleaktest.h"
#include "Content_Logs.h"

QWidget* m_placeholder;
bool m_toggle;

QtMemoryLeakTest::QtMemoryLeakTest(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);

    m_placeholder = new Content_Logs(this);

    this->layout()->addWidget( m_placeholder );

    connect( ui.pushButton, &QPushButton::clicked, this, &QtMemoryLeakTest::toggleClick );
}

void QtMemoryLeakTest::toggleClick()
{
    if( m_toggle = !m_toggle )
    {
        m_placeholder->show();
    }
    else
    {
        m_placeholder->hide();
    }
}

Memory grows everytime a click on the button. from 8 mb to 47 mb in  20 minutes. But if a replace Content_Logs to a QWidget, no memory leaks. So i Think there is a bug in Qts self gererated ui-classes? In Content_Logs i have  labels, lineEdits, Spacers, TableWidgets, Checkboxes, DateTimeEdits, ComboBoxes and so on.
Code in Conte_Logs:
#include "Content_Logs.h"

Content_Logs::Content_Logs( QWidget* parent = 0 )
    : QWidget( parent )
{
    ui.setupUi( this );
}

Content_Logs::~Content_Logs()
{

}


text:
Q: SSRS 2008 R2 Querystring parameters Sharepoint Integrated Mode I'm trying to run a report via the following url:
http://portal/dashboards/hr/reports/_vti_bin/ReportServer?http://portal/dashboards/hr/reports/reports/Test.rdl

However, I get a 401 Unauthorised error.
The reason I am accessing the report this way is so that I can pass some parameters (which I have taken off for now). I want to pass via queyrstring some mdx values which will be used to run the report.
The URL looks like this with the queyrstring parameters.
http://portal/dashboards/hr/reports/_vti_bin/ReportServer?http://portal/dashboards/hr/reports/reports/Test.rdl&rp:CostCentreCostCentreHierarchy=%5BCost%20Centre%5D.%5BCost%20Centre%20Hierarchy%5D.%26%5B1002%5D&TimeFiscalYearQuarter=%5BTime%5D.%5BFiscal%20Year-Quarter-Month%5D.%5BF%20Quarter%5D.%26%5B20123%5D

Basically the parameters are MDX values.
I'm sure this worked for me at one point - but not any more.
I'm hoping it's a case of missing permissions somewhere?!
Could the issue be related to the _vti_bin folder. I used this as per the article: http://msdn.microsoft.com/en-us/library/ms155391.aspx
Opening the reports via Sharepoint from the respective lists, works fine - the reports run without any errors - its just when I use the _vti_bin url i get this issue. The querystring parameters do not work with the regaular report viewer url which is in the _layouts folder.
If there is a better way to do this then please advise also.
Any help appreciated.
Thanks,
KS

A: Solved - apparaently each parameter is required to have the rp: prefix.
The only character that needs to be encoded in the mdx value is the ampersand.
Thanks.


text:
Q: What is this error when I using Pipe in R df2$Neighborhood %>% length()
df2$category %>% length()
table(df2$Neigborhood) %>% [order()]

This is the code I write to learn how to use the pipe. I'm not familiar with how to use it yet. An error occurred and I don't know how to fix it.
    [1] 481376
    [1] 481376
     Unknown or uninitialised column: 'Neigborhood'.integer(0)

The first two lines are able to generate a result. But not the third one. It means the neighborhood column is available. However, there are some mistakes in it. My purpose was to sort the table using function d2[order(d2)]. How can I fix it?

A: The issue is that there is 'h' missing in 'Neigborhood'.  If we use the correct column name i.e. Neighborhood, it should work if we also specify the data i.e. . from the lhs of %>%
library(magrittr)
table(df2$Neighborhood) %>%
      .[order(.)]

It may be also better to wrap with {} if there are multiple things involved
table(df2$Neighborhood) %>%
             {.[order(.)]}

Here the . represents the data from the lhs of %>%


text:
Q: Create A Maximum-Gradient Vector Overlay QGIS I have generated several vector layers of different gradients and geographic areas (PUMAs, ZCTAs & Census Tracts).
Is there a way I can overlay all these layers with the aim of identifying the ultimate hotspots?
Data merge won't do the trick.


text:
Q: excel - count if multiple words are in a cell I have values
 AA,BB,CC
 AA,CC
 AA
 AA,BB
 BB
 BB,CC
 CC
 CC,AA
 CC,BB
 BB,CC,DD

find all cells that have. how do I search for each values.
 AA,BB = 2
 BB,CC = 4

Example
COUNTIFS($A:$A,"*AA*",$A:$A,"*BB*") doesn't seem to work.

A: You could try this using wildcards * with TEXTBEFORE() & TEXTAFTER()

• Formula used in cell D2
=COUNTIFS(A1:A10,"*"&TEXTBEFORE(C2,",")&"*",A1:A10,"*"&TEXTAFTER(C2,",")&"*")

EDIT
As suggested by Tom Sharpe Sir,

• Formula used in cell D2
=LET(x,TEXTSPLIT(C2,","),y,COUNTA(x),
SUM(--(MMULT(N(ISNUMBER(SEARCH(x,$A$1:$A$10))),SEQUENCE(y,,1,0))=y)))

A: You could try:

Formula in D2:
=MAP(C2:C5,LAMBDA(z,SUM(MAP(A1:A11,LAMBDA(x,LET(y,TEXTSPLIT(z,,","),N(SUM(N(TEXTSPLIT(x,",")=y))=ROWS(y))))))))

Note: My answer assumes no duplicates in the values in column A:A. e.g.: AA,AA.

A: How about:
=LET(searchvalues,  C2,
     data,          $A$1:$A$10,
     split,         TEXTSPLIT(searchvalues,","),
     count,         COLUMNS(split),
SUM(
    --(MMULT(
             --ISNUMBER(SEARCH(split,data)),
             SEQUENCE(count,,1,0))
       =count)))

It splits the values you want to search (stored in C2 in my example) into individual values: split
Than split is searched within each row of your data.
This returns TRUE or FALSE wrapped in -- changes TRUE to 1 and FALSE to 0.
This is used within MMULT and this returns the sum of the occurrences of each individual split value. Finally the MMULT result needs to equal the number of splitted search values.
The sum of this being true is the end result.

A: The following approach considers a variable number of words to search, not just 2 words as in the input sample:
=LET(lk, B1, A, $A$1:$A$11, lks, TEXTSPLIT(lk,, ","),
  byr, BYROW(A, LAMBDA(x,SUM(COUNTIF(x,"*"&lks&"*")))), SUM(N(byr=ROWS(lks))))

It has a caveat that if the word is repeated more than one time per row in the first column, it is counted as 1, as you can see in the following output. This is because of how COUNTIF (or COUNTIFS) works with wildcards (other answers provided using SEARCH produce the same result). If that assumption is ok, then it works. The rest is just to drag the formula down (formula1).
UPDATE: Considering @JvdV's comment, to avoid false positive when the word to search could be a substring of the column A on a given row. Like for example, searching the word AA, in the string: AAA will produce a false positive. The following version avoids it:
=LET(lk, B1, A, $A$1:$A$11, lks, TEXTSPLIT(lk,, ","),
 byr, BYROW(A, LAMBDA(x, SUM(N(TEXTSPLIT(x,",") = lks)))), SUM(N(byr=ROWS(lks))))

Here is the output:

I added intentionally the highlighted cases to test additional situations. Row 11 repeats the word: AA, and BB, but it is counted as 1 in the final result.
The following approach tries to identify the total number of counts considering repetitions of the word in column A (formula2):
=LET(lk, B1, A, $A$1:$A$11, lks, TEXTSPLIT(lk,, ","),
 byr, BYROW(A, LAMBDA(x, LET(match, IFERROR(TOCOL(XMATCH(TEXTSPLIT(x, ","),
 lks),2),0), ux, UNIQUE(match), IF(ROWS(ux) < ROWS(lks), 0,
   MIN(MMULT(TRANSPOSE(N(match = TOROW(ux))), SEQUENCE(ROWS(match),,1,0))))))),
 SUM(byr))

Now we get the following result:

Now we get an additional count for the case of AA, BB.
In formula2, match has the index position as a result of the XMATCH call, we use TOCOL to remove non-found values #N/A. In case no words were found, we use IFERROR to assign the zero value. The IF condition:
IF(ROWS(ux) < ROWS(lks)

Ensures to calculate non-zero counts only if all words were found. We use MMULT to calculate per row the number of repetitions of the lookup words. We take the minimum, to ensure we only consider the scenarios where all the words are present. There could be a situation, where one of the lookup words has more counts than another one, which is why we take the minimum. Therefore we are counting the entire set of lookup words found regardless of the order,

A: Answer was
COUNTIFS($A:$A,"*"&$C$2&"*",$A:$A,"*"&$C$3&"*")

C2 = AA
C3 = BB


text:
Q: Google finance wpf graph/chart alike control? Does anyone know a WPF control/app that functions like the google Finance graph/chart?
Thank you.

A: Check this article on CodeProject. It is exactly about what you are asking. Author makes standard Chart control to look and behave like Google chart.

A: Take a look at amCharts Stock Chart for WPF & Silverlight.


text:
Q: Alert on failed links for inbound port for a specific process on a VM Let's say I have an Azure VM and there's a process called ABC.exe and it listens on port 34952. I want to monitor this port and perform some sort of health probe check for it. If it goes down, I want to be alerted.
I looked into using Log Analytics Workspace, as you can create an Alert rule for it. Something like this:
VMConnection
| where Direction == "inbound"
| where ProcessName == "ABC.exe"
| where DestinationPort in (34952)
| where LinksFailed > 0

The problem is, the "LinksFailed" metric is only available for Outbound connections, not Inbound. This is documented here - https://learn.microsoft.com/en-us/azure/azure-monitor/reference/tables/vmconnection
Otherwise, the above works well for identifying any failed links for specific ports and their processes.
Is there another option I can use? I'm trying not to implement any solutions at the VM guest level. Ideally, if this can be done at the PaaS level, that would be great.


text:
Q: How to express the following design in UML? I have the following diagram:

I want to model in it that the list of the StatusCommandManager has to be the same instance as the one in the StatusViewModel but I don't know how to model that with UML class diagrams.
Thanks.
EDIT:
For each instance of the StatusViewModel there will be an instance of the StatusCommandManager and both of them have to share the same list instance.

A: So, would this model describe your situation (I prefer to show attributes of non-trivial types using associations)?

A couple of notes:

*

*I added an association between StatusViewModel and StatusCommanderManager, based on your comment ("for each instance of the StatusViewModel there will be an instance of the StatusCommandManager"). Please let me know if "1 to 1" is ok, of you have "1 to n" instead

*as instances of Lists are shared, you cannot use the composition (like in your example), but rather aggregation

If this understanding is correct, you have (at least) two options to add your restriction:

*

*Add somehow the restriction to the model, stating that the attribute StatusParameterViewModels of StatusViewModel must be equal to the same attribute of the linked StatusCommanderManager instance. There are several ways to include this statement in specification:
A less formal way is just to add a note on the diagram and type it textually.
A formal way would be to use OCL (please let me know if you need more info on this)

*Change slightly the model, as one of the aggregarions is reduntant in the first place. StatusViewModel and StatusCommanderManager are linked between each other and therefore it is enough that only one of them has a List. Another one can get it directly "asking" the first one.

The second option is definitelly recommended if there is no some strong reason (unknown from your description) not to apply it. The model would be simpler and clearer, no redundancy, the List is maintained centrally, whole logic is in the model (no external restrictions), etc.


text:
Q: Running Julia scripts from the terminal in a virtual environment I'm curious whether Julia supports the same workflow as Python + virtual environments.
In Python I can do the following from the terminal:
$ python -m venv venv
$ source venv/bin/activate
(venv) $ pip install myFavPackage
(venv) $ python src/myFavScript.py

Julia can use virtual environments through its REPL like so:
(@v1.5) pkg> activate .
(myFavProject) pkg> add myFavPackage
julia> include("src/myFavScript.jl")

But if I run the first two lines (which adds all dependencies to the Project.toml and Manifest.toml files) and then jump out to the terminal and run
$ julia src/myFavScript.jl

Then it doesn't recognise the package I installed:
ERROR: LoadError: ArgumentError: Package myFavPackage not found in current path:
- Run `import Pkg; Pkg.add("myFavPackage")` to install the myFavPackage package.

Does this mean that I have to install my packages globally to run Julia scripts from the terminal? And if not, how can I force the terminal to use the local dependencies?

A: You can use the --project flag, i.e.
$ julia --project=path/to/project src/myFavScript.jl

If you are in the correct folder you can just omit the path, i.e.
$ julia --project src/myFavScript.jl

Finally, if you want this behavor by default, you can set the the JULIA_PROJECT environment variable to @., which is equivalent to always starting Julia with --project.


text:
Q: Adding functionality to a form in a React functional component I have a form component that when submitted uploads a photo to my server using multer and then to an S3 bucket on AWS in a single upload route. I want to add an extra line of functionality that stores the photo key from S3 in state on the front end which I will then store with the user object in the database so the photo is always associated with the user (profile picture).
The form sends properly as currently set up using the action parameter, but I'm not sure how to implement the submitHandler function into the form properly. If I remove the action parameter from the form it breaks, if I use onSubmit it also seems to break. I'm sure this is a really easy one but I can't figure it out. Any help much appreciated.
import React from 'react';
import axios from 'axios';

//setProfilePhoto is the set method for state from props

const UploadForm = ({setProfilePhoto}) => {

    const submitHandler = async (e) => {
        e.preventDefault();
        const result = await axios.post('http://localhost:8000/api/upload');
        console.log(result.key)
        setProfilePhoto(result.key)
    }

    return(
        <form action="http://localhost:8000/api/upload" encType='multipart/form-data' method='POST'>
        <input type='file' name='photo' />
        <input type='submit' value="submit" />
        </form>
    )

}

export default UploadForm;

A: try to take this line and delete it.  <input type='submit' value="submit" />
Replace it with a button.
Then add the onSubmit handler to the form tag, not the button.


text:
Q: SQLite not connecting on newly created pages I am dumbfounded. In both xcode 3 and 4 I am able to connect to my sqlite DB on pages I did a month ago. With any new view / class I create i get a null value returned. Even if I copy word for word a page that is working and returning my data.
Has anyone else had this happen to them? Have there been any fixes you might have tried.

A: I am unaware of any changes that would cause this problem. My older code still works fine and I seen no similar reports.
The wording of your question suggest that you are thinking of Core Data in SQL terms which is dangerous. Core Data is an object graph management system with persistence options. It's a lot more than just a database. It is very common for people to get confused into errors by trying to treat Core Data as just an object wrapper around SQL.


text:
Q: identify multiple gaps and islands for n columns In this previous question, I asked for a way of identifying some gaps and islands. with a table t below;
+---------------------+------------+---------------+
| ts                  | EngOilP_sd | CompOilLVL_sd |
+---------------------+------------+---------------+
| 2015-06-24 20:28:07 |          0 |             0 |
| 2015-06-24 20:30:20 |          1 |             0 |
| 2015-06-24 20:36:47 |          1 |             0 |
| 2015-06-24 20:41:11 |          1 |             0 |
| 2015-06-24 20:43:29 |          1 |             0 |
| 2015-06-24 20:45:42 |          0 |             0 |
| 2015-06-24 20:47:51 |          0 |             0 |
| 2015-06-24 20:49:59 |          0 |             1 |
| 2015-06-24 20:52:01 |          0 |             1 |
| 2015-06-24 20:54:17 |          0 |             0 |
+---------------------+------------+---------------+

The following view will give me the islands of data where values are successively true;
create view t_pivot as
    select 'EngOilP_sd' as sd, ts, EngOilP_sd as val from t
    union all
    select 'CompOilLVL_sd', ts, CompOilLVL_sd from t;

# explain
select sd, timediff(stop, start) as duration, start, stop
from (
    select x.sd, x.start, min(case y.val when 0 then y.ts end) as stop
    from (
        select sd, min(case val when 1 then ts end) as start
        from t_pivot
        group by sd
    ) as x
    join t_pivot as y
        on x.sd = y.sd
       and y.ts > x.start
    group by x.sd, x.start
) as z
order by sd desc;

Gives
+---------------+----------+---------------------+---------------------+
| sd            | duration | start               | stop                |
+---------------+----------+---------------------+---------------------+
| EngOilP_sd    | 00:15:22 | 2015-06-24 20:30:20 | 2015-06-24 20:45:42 |
| CompOilLVL_sd | 00:04:18 | 2015-06-24 20:49:59 | 2015-06-24 20:54:17 |
+---------------+----------+---------------------+---------------------+
2 rows in set (0.00 sec)

Now, I am stumped as how to look at the following table for n gaps
+---------------------+------------+---------------+---------------+
| ts                  | EngOilP_sd | CompOilLVL_sd | Brake_sd      |
+---------------------+------------+---------------+---------------+
| 2015-06-24 20:28:07 |          0 |             0 |             0 |
| 2015-06-24 20:30:20 |          1 |             0 |             0 |
| 2015-06-24 20:36:47 |          1 |             1 |             0 |
| 2015-06-24 20:41:11 |          1 |             1 |             1 |
| 2015-06-24 20:43:29 |          1 |             1 |             1 |
| 2015-06-24 20:45:42 |          1 |             0 |             1 |
| 2015-06-24 20:47:51 |          0 |             0 |             1 |
| 2015-06-24 20:49:59 |          0 |             1 |             0 |
| 2015-06-24 20:52:01 |          1 |             1 |             0 |
| 2015-06-24 20:53:01 |          1 |             1 |             0 |
| 2015-06-24 20:54:01 |          1 |             1 |             1 |
| 2015-06-24 20:56:01 |          1 |             1 |             1 |
| 2015-06-24 20:57:01 |          1 |             1 |             1 |
| 2015-06-24 20:58:01 |          1 |             1 |             1 |
| 2015-06-24 21:02:01 |          1 |             1 |             1 |
| 2015-06-24 21:32:01 |          0 |             1 |             1 |
| 2015-06-24 21:52:01 |          0 |             0 |             1 |
| 2015-06-24 22:12:01 |          0 |             0 |             0 |
| 2015-06-24 22:20:01 |          0 |             0 |             0 |
| 2015-06-24 22:49:01 |          0 |             1 |             1 |
| 2015-06-24 23:52:01 |          0 |             1 |             1 |
| 2015-06-24 23:54:17 |          0 |             0 |             0 |
+---------------------+------------+---------------+---------------+

The result set I am looking for here would be as below
+---------------+----------+---------------------+---------------------+
| sd            | duration | start               | stop                |
+---------------+----------+---------------------+---------------------+
| EngOilP_sd    | 00:15:22 | 2015-06-24 20:30:20 | 2015-06-24 20:45:42 |
| EngOilP_sd    | 00:10:00 | 2015-06-24 20:52:20 | 2015-06-24 21:02:42 |
| CompOilLVL_sd | 00:06:42 | 2015-06-24 20:36:47 | 2015-06-24 20:43:29 |
| CompOilLVL_sd | 00:42:02 | 2015-06-24 20:49:59 | 2015-06-24 21:32:01 |
| CompOilLVL_sd | 00:03:00 | 2015-06-24 20:49:59 | 2015-06-24 20:54:17 |
| Brake_sd      | 00:06:40 | 2015-06-24 20:41:11 | 2015-06-24 20:47:51 |
| Brake_sd      | 00:58:01 | 2015-06-24 20:54:01 | 2015-06-24 21:52:01 |
| Brake_sd      | 01:02:00 | 2015-06-24 22:49:01 | 2015-06-24 23:52:01 |
+---------------+----------+---------------------+---------------------+
8 rows in set (0.00 sec)

EDIT Initially, I did not have the column Brake_sd in the question. User @tombom's answer correctly describes the case where the Brake_sd column is not present, although that is the only difference

A: Sample data:
CREATE TABLE t
    (`ts` varchar(19), `EngOilP_sd` int, `CompOilLVL_sd` int)
;

INSERT INTO t
    (`ts`, `EngOilP_sd`, `CompOilLVL_sd`)
VALUES
    ('2015-06-24 20:28:07', 0, 0),
    ('2015-06-24 20:30:20', 1, 0),
    ('2015-06-24 20:36:47', 1, 1),
    ('2015-06-24 20:41:11', 1, 1),
    ('2015-06-24 20:43:29', 1, 1),
    ('2015-06-24 20:45:42', 1, 0),
    ('2015-06-24 20:47:51', 0, 0),
    ('2015-06-24 20:49:59', 0, 1),
    ('2015-06-24 20:52:01', 1, 1),
    ('2015-06-24 20:53:01', 1, 1),
    ('2015-06-24 20:54:01', 1, 1),
    ('2015-06-24 20:56:01', 1, 1),
    ('2015-06-24 20:57:01', 1, 1),
    ('2015-06-24 20:58:01', 1, 1),
    ('2015-06-24 21:02:01', 1, 1),
    ('2015-06-24 21:32:01', 0, 1),
    ('2015-06-24 21:52:01', 0, 0),
    ('2015-06-24 22:12:01', 0, 0),
    ('2015-06-24 22:20:01', 0, 0),
    ('2015-06-24 22:49:01', 0, 1),
    ('2015-06-24 23:52:01', 0, 1),
    ('2015-06-24 23:54:17', 0, 0)
;

create view t_pivot as
    select 'EngOilP_sd' as sd, ts, EngOilP_sd as val from t
    union all
    select 'CompOilLVL_sd', ts, CompOilLVL_sd from t;

Query:
SELECT sd, TIMEDIFF(MAX(ts), MIN(ts)) AS duration, MIN(ts) AS startime, MAX(ts) AS endtime
FROM (
    SELECT
    tp.*
    , @val_change := IF(@prev_val != tp.val, @val_change + 1, @val_change) AS vc
    , @prev_val := tp.val
    FROM
    t_pivot tp
    , (SELECT @prev_val := NULL, @val_change := 0) var_init_subquery
    ORDER BY sd, ts
) sq
WHERE val = 1
GROUP BY sd, vc;

Result:
|            sd |                  duration |            startime |             endtime |
|---------------|---------------------------|---------------------|---------------------|
| CompOilLVL_sd | January, 01 1970 00:06:42 | 2015-06-24 20:36:47 | 2015-06-24 20:43:29 |
| CompOilLVL_sd | January, 01 1970 00:42:02 | 2015-06-24 20:49:59 | 2015-06-24 21:32:01 |
| CompOilLVL_sd | January, 01 1970 01:03:00 | 2015-06-24 22:49:01 | 2015-06-24 23:52:01 |
|    EngOilP_sd | January, 01 1970 00:15:22 | 2015-06-24 20:30:20 | 2015-06-24 20:45:42 |
|    EngOilP_sd | January, 01 1970 00:10:00 | 2015-06-24 20:52:01 | 2015-06-24 21:02:01 |

*

*See it working live in an sqlfiddle
Explanation:
With the subquery in the FROM clause we are initializing our variables. The ORDER BY is very important! Here's why: In the SELECT clause each line is processed. The order in the SELECT clause is also important. Here
, @val_change := IF(@prev_val != tp.val, @val_change + 1, @val_change) AS vc

we increment our variable @val_change if the value in the column val differs from the "previous" row (that's why ORDER BY is so important). The "previous row" is in the variable @prev_val. The value of the current row is assigned to it in this line
, @prev_val := tp.val

Since MySQL processes each line in the SELECT clause in the order the SELECT clause is written, the @prev_val variable holds the value of the previous row (or NULL when no row has been processed yet) in the previous line of the SELECT clause.
Now all we have to do is GROUP BY sd and this @val_change variable in the outer query.

*

*Read more about how to use user-defined variables in the manual here.

CAVEAT:
This will result in a full table scan.
sorry for bad english, hope it's understandable
UPDATED QUESTION:
The query still is the same. You just have to adjust the view t_pivot
create view t_pivot as
    select 'EngOilP_sd' as sd, ts, EngOilP_sd as val from t
    union all
    select 'CompOilLVL_sd', ts, CompOilLVL_sd from t
    union all
    select 'Brake_sd', ts, Brake_sd from t;

to include Brake_sd.

*

*See it working live in an sqlfiddle


text:
Q: DataGridView auto re-sort I'm making a program in C# that receive sms and display to the user, and I'm having a problem with the sort of the data.
For example, if the user sort the table by ids, from the higher id to the lower so when a new sms arrives it gets on the top of the table, the new sms will get to the bottom of the table anyway.
Here is a screenshot

As you can see, the id 125 is under the 0 instead of being on the top of the table...
Is there any code or event that I should use?
There is where I want to start that event:
public void readSms()
{
    try
    {
        comm = AppData.getInstance().getComm();

        DecodedShortMessage[] messages = comm.ReadMessages(PhoneMessageStatus.All, "SM");
        foreach (DecodedShortMessage message in messages)
        {
            if (AppData.getInstance().mensagens.Count != 0)
            {
                Message msg = new Message(
                    AppData.getInstance().messages.Last.Value.getId() + 1,
                    ((SmsDeliverPdu)(message.Data)).OriginatingAddress,
                    message.Data.UserDataText,
                    ((SmsDeliverPdu)(message.Data)).SCTimestamp.ToDateTime(),
                    false);
                    AppData.getInstance().setMensagem(msg);
            }
            else
            {
                Message msg = new Message(
                   0,
                   ((SmsDeliverPdu(message.Data)).OriginatingAddress,
                   message.Data.UserDataText,
                   ((SmsDeliverPdu)(message.Data)).SCTimestamp.ToDateTime(),
                    false);
                AppData.getInstance().setMensagem(msg);
            }
        }

        // I need to put the event of sorting here in case any message was been added
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Thank you once more Edper for your help!
There is when I add the message in the program:
public void preencherTabela(int lastIndex)
{
    LinkedList<Message> messages = AppData.getInstance().getMessagessList();
    {
        addTable(
            messages.ElementAt(i).getId(),
            messages.ElementAt(i).getChecked(),
            messages.ElementAt(i).getMsg(),
            messages.ElementAt(i).getNum(),
            messages.ElementAt(i).getDate());
     }
}

And the AddTable method:
private void addTable(int p, bool p_2, string p_3, string p_4, DateTime dateTime)
{
    this.dataGridView1.Invoke(
        new MethodInvoker(() =>
        {
            this.dataGridView1.Rows.Add(p, p_2, p_3, p_4, dateTime);
        }));
}

If you want to now also the point of it, this is a program for show Messages in a screen, for example, in a disco, the users send messages from the mobile to a number connected by a model to a PC and the messages will show on it, actually I'm testing it in a friends disco.
Thank you again for the help!
Edit: Added a bounty of 50 reputation for who can help me fix the table.

A: You can use RowsAdded event of datagridview. Inside that method you can write code to sort the datagridview.
private void dataGridView1_RowsAdded(object sender,
       DataGridViewRowsAddedEventArgs e)
{
   datagridview1.Sort();
}

A: Finally got it work!
There is what I did:
DataGridViewColumn column = dataGridView1.SortedColumn;
ListSortDirection order;

if (dataGridView1.SortOrder.Equals(SortOrder.Ascending))
   {
       order = ListSortDirection.Ascending;
   }
else
   {
       order = ListSortDirection.Descending;
   }

dataGridView1.Sort(column, order);

So, I got the sorted column and I check in a if what is the order that the datagridview is sorted, then I sort again the column that used sorted for the same order...
Notice that this code is fresh so it isn't "bulletproof" I'm not checking if the values of column and the order are null or not!
If you need this code and use it, take that in mind!
It's almost like the answer of Jayesh.
Thank you all for the help!

A: If your DataGridView is bound, you could use:
 dataGridView1.Columns[0].ValueType = typeof(System.Int32);
 dataGridView1.Columns[0].CellTemplate.ValueType = typeof(System.Int32);

If your DataGridView is not bound, you could use SortCompare handler in sorting values, like:
 public Form1()
   {
        InitializeComponent();
        dataGridView1.SortCompare += new DataGridViewSortCompareEventHandler(dataGridView1_SortCompare);
   }

Then do this:
void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
    {
        if (e.Column.Index == 0)
        {
            if ( int.Parse(e.CellValue1.ToString()) > int.Parse(e.CellValue2.ToString()))
            {
                e.SortResult = 1;
            }
            else if (int.Parse(e.CellValue1.ToString()) < int.Parse(e.CellValue2.ToString()))
            {
                e.SortResult = -1;
            }
            else
            {
                e.SortResult = 0;
            }
            e.Handled = true;
        }
    }

A: The other thing could be that if the datagrid is bound by a stored procedure within that you could add an ORDER BY clause that would sort the data however you want in the first place...


text:
Q: Get left and right of member in sorted set I need to be able to get the members to the left and right of a given member in a sorted set.
For example:
["red", "green", "blue", "yellow", "black"]

If I asked for the members to the left and right of "blue" I would need to get back "green" and "yellow".
One way I could do that is use zrank to get the index of the member (let's call it x) of blue (2) and then use zrange with a start of x-1 and stop of x+1.
The problem: it's not atomic. If a member with an index <= x is removed in between the two steps (zrank and zrange) the indexes would not match and the wrong members would be returned.
Is there an atomic way to do this?

A: Use LUA scripting. Something like:
local rank = redis.call('zrank', KEYS[1], ARGV[1]);
if rank == nil then
    return nil
end

if rank == 0 then
    return redis.call('zrange', KEYS[1], rank, rank + 1);
end

return redis.call('zrange', KEYS[1], rank - 1, rank + 1);

There 1st arg is your sorted set key and 2nd arg is memeber in sorted set.


text:
Q: Find nlargest of two columns (for tweets in python) I have a .csv of tweets and want to find the top tweets, which I am defining for my purposes as the tweets with the most RTs AND Favs. I know I can use nlargest to do this as follows:
toptweets = tweets.nlargest(10, ['retweet_count' , 'favorite_count'])
However, I know I get slightly different results if I change the order of the columns in the brackets because the above code orders by the largest values in retweet_count AND THEN favorite_count (source: http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.nlargest.html).
What I'm looking for, though, is a way to order the tweets that doesn't prioritize one column over the other and gives me the tweets that have the highest values in both columns. Any ideas?


text:
Q: onResume() called twice in a row after onCreate() > onPause() I've run into a weird occurrence with regards to my child activity's life-cycle methods. If I launch and close the activity enough times, there eventually comes a point where for some reason, upon launching, onPause gets called immediately after onCreate (skipping onResume), which is then followed by onResume being called twice in a row. This ends up causing a RuntimeException in my onResume.
Here's the code that starts my activity:
Intent intent = new Intent(MainActivity.this, RecorderActivity.class);
startActivityForResult(intent, AV_CAPTURE);

My onPause:
protected void onPause() {
    camera.stopPreview();
    camera.setPreviewCallback(null);
    camera.release();
    camera = null;
    super.onPause();
};

I'm not really sure what else I can provide here, it's all pretty straightforward. finish() is called to close the activity, etc.
I should also probably mention that the activity is being triggered from a Javascript Interface attached to a WebView. Another interesting thing to mention is that setting a breakpoint anywhere in the first code block above seems to prevent the issue from happening.

A: While I do not have an answer for the resume being called twice, I do have a link to the Android docs stating that you should always check for exceptions while attempting to open the camera.  See here:
http://developer.android.com/guide/topics/media/camera.html#access-camera
In your onPause, make sure that you set your Camera object to null.  Then in onResume, only attempt to call getCameraInstance() if your camera is not null.


text:
Q: Nhibernate hql left join Is it possible to do a left join like this in Nhibernate:
SELECT T.title_id, T.title, S.qty
FROM titles T
LEFT JOIN sales S on
    T.title_id = S.title_id
    AND S.stor_id = '7131'
ORDER BY T.title

The important part to note is the extra clause (AND S.stor_id = '7131') in the LEFT JOIN expression.
Can I do this in Nhibernate hql or is there another way?

A: The answer is the with keyword, for example:
Select q FROM GeneralQuestion
q Left Join q.QuestionResponses as qr with
qr.ContactUid = :contactuid WHERE q.ParentUid = :audituid


text:
Q: Populating controlled inputs in React I'm currently building a form with React, and I'm wondering what the best practices are for pre-filling fields from an object.
import React, { Component } from 'react'

class EditResourceForm extends Component {
  constructor (props) {
    super(props)

    this.state = {
      resource: props.resource
    }
  }

  handleFieldChanged (e) {
    // update state
  }

  render () {
    return (
      <input
        type="text"
        value={this.state.resource.email}
        onChange={::this.handleFieldChanged} />
    )
  }
}

I'm encountering a problem when this.state.resource.email is null or undefined, because React does not want me providing those as values to controlled components:
Warning: `value` prop on `input` should not be null. Consider using the
empty string to clear the component or `undefined` for uncontrolled
components.

Where is the proper place to provide an empty string as a fallback for a null value? Should this be done in the parent component's constructor method? Is there a way to avoid having to do this explicitly for every attribute that might have a null value?

A: Simplest way I can think of:
constructor (props) {
    super(props)

    this.state = {
      resource: props.resource || {}
    }
  }

As far as I know there is no way to automatically set this values so they are not null, but if there was, I would not recommend it, good code is self explanatory.
EDIT 1
If this is still not enough, then the other option is using uncontrolled components, however, straight from the documentation of react:

Since an uncontrolled component keeps the source of truth in the DOM,
  it is sometimes easier to integrate React and non-React code when
  using uncontrolled components. It can also be slightly less code if
  you want to be quick and dirty. Otherwise, you should usually use
  controlled components.

EDIT 2
The code provided on the documentation seems a little convoluted, so here is a snippet of how I would do it:
<input type="text" onChange={(e, val) => {this.setState({email: val})}} />

A: You can use the defaultValue prop to set an initial value.
<input
  type="text"
  defaultValue={this.state.resource.email ? this.state.resource.email : ""}
  onChange={this.handleFieldChanged} />

Check out this great documentation about controlled vs uncontrolled components: https://facebook.github.io/react/docs/uncontrolled-components.html