text:
Q: ffmpeg определить качество видео Пишу сайт, с возможностью загрузки видео и дальнейшего конвертирования его для выбора качества.
Сам вопрос: можно ли при загрузке определить исходное качество видео?
Например: я не могу из 360р сделать 720р, но как узнать, что видео именно 360р, чтобы не тратить время на дополнительное бессмысленное конвертирование.

A: Думаю, вам поможет ffprobe.

ffprobe gathers information from multimedia streams and prints it in
  human- and machine-readable fashion.

Вам нужна секция streem.
Пример вывода:
$ ffprobe 123.mp4
ffprobe version N-79139-gde1a0d4 Copyright (c) 2007-2016 the FFmpeg developers
  built with gcc 4.8 (Ubuntu 4.8.4-2ubuntu1~14.04.1)
  configuration: --extra-libs=-ldl --prefix=/opt/ffmpeg --mandir=/usr/share/man --enable-avresample --disable-debug --enable-nonfree --enable-gpl --enable-version3 --enable-libopencore-amrnb --enable-libopencore-amrwb --disable-decoder=amrnb --disable-decoder=amrwb --enable-libpulse --enable-libfreetype --enable-gnutls --enable-libx264 --enable-libx265 --enable-libfdk-aac --enable-libvorbis --enable-libmp3lame --enable-libopus --enable-libvpx --enable-libspeex --enable-libass --enable-avisynth --enable-libsoxr --enable-libxvid --enable-libvidstab
  libavutil      55. 19.100 / 55. 19.100
  libavcodec     57. 30.100 / 57. 30.100
  libavformat    57. 29.101 / 57. 29.101
  libavdevice    57.  0.101 / 57.  0.101
  libavfilter     6. 40.102 /  6. 40.102
  libavresample   3.  0.  0 /  3.  0.  0
  libswscale      4.  0.100 /  4.  0.100
  libswresample   2.  0.101 /  2.  0.101
  libpostproc    54.  0.100 / 54.  0.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '123.mp4':
  Metadata:
    major_brand     : mp42
    minor_version   : 0
    compatible_brands: isommp42
    creation_time   : 2016-03-29 14:00:43
    artist          :
    description     :
    title           :
  Duration: 00:00:08.40, start: 0.000000, bitrate: 181 kb/s
    Stream #0:0(eng): Video: h264 (Baseline) (avc1 / 0x31637661), yuv420p(tv), 480x320 [SAR 1:1 DAR 3:2], 177 kb/s, 30 fps, 30 tbr, 30k tbn, 60 tbc (default)
    Metadata:
      creation_time   : 2016-03-29 14:00:49
      handler_name    : Mainconcept MP4 Video Media Handler
      encoder         : AVC Coding


text:
Q: How do you remove trailing objects from a list with linq? I have a collection of objects with properties and I want to remove all the trailing objects with (say) a value of 0 in LINQ.
public class Object
{
    public Object(){}

    public int Property {get; set;}
}

and if I have a list of objects:
new Object(){ Property = 1};
new Object(){ Property = 0};
new Object(){ Property = 9};
new Object(){ Property = 7};
new Object(){ Property = 0}; // "trailing zero"
new Object(){ Property = 0}; // "trailing zero"
new Object(){ Property = 0}; // "trailing zero"

How would I go about removing the "trailing zeros" in this list? I don't want to remove all properties with a zero, but I want to remove any objects from the list with a property value of zero if it it is not later followed by a property value of something greater.

A: Standard solution for sequences of finite size - reverse, remove from start, reverse:
   var withoutTail = sequence
       .Reverse()
       .SkipWhile( x => x == 0) // whatever condition you need
       .Reverse();

This is very non-optimal, so if you actually have real collection (i.e. List) it would be better to just remove items starting from last index.

A: Write an extension method:
static class Extensions
{
    public static IEnumerable<T> TrimTrailing<T>(this IEnumerable<T> items,
                                                 Predicate<T> test)
    {

        if (items == null) throw new ArgumentNullException(nameof(items));
        if (test == null) throw new ArgumentNullException(nameof(test));

        var buf = new List<T>();
        foreach (T item in items)
        {
            if (test(item))
            {
                buf.Add(item);
            }
            else
            {
                foreach (T bufferedItem in buf)
                {
                    yield return bufferedItem;
                }
                buf.Clear();
                yield return item;
            }
        }
    }
}

Then, if you have an IEnumerable<Object> called l, you would call TrimTrailing using
var trimmed = l.TrimTrailing(o => o.Property == 0);

Be careful with this, though: in the worst case, it buffers all the items from items and then throws away the buffer.

A: Just iterate your list backwards removing any 0 entries and stop either at the beginning of the list or the Property != 0.
for (int i = list.Count - 1; i >= 0; i--)
{
    var item = list[i];
    if (item.Property == 0)
    {
        list.RemoveAt(i);
    }
    else
    {
        break;
    }
}

This will allow for a single pass through your list.

A: You can use FindLastIndex to find the last non-0 index, and Take the elements up to that.
var result = list.Take(list.FindLastIndex(x => x.Property != 0) + 1);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Let a metadata table automatically match all columnnames from original table in MariaDB In my database I have large table with a lot of columns in which each row represents a dataset. ("Table1")
I have created a second table ("Table2") which functions as a metadata-table for Table1. All the columns are identical except for an added primary key.
The main difference is that each row in this table is representing a view which has metadata for all columns of Table1
Small example:
Table1
Column1  Column2  Column3
      1     True    "Foo"
      2    False    "Bar"
      3    False    "Baz"

Table2
View_name  Column1  Column2  Column3
  "admin"   "show"   "show"   "show"
  "sales"   "show"   "hide"     null
"default"   "hide"   "show"   "hide"

I am now looking for a way to automatically update Table2 whenever Table1 changes. So:

*

*If Table1 adds a Column4, add Column4 to Table2 (values for the views can be null).

*If Table1 removes Column3, remove Column3 from Table2.

*If Table1 alters Column2's name to Col2, alter Column2s name to Col2 in Table2

And of course, while not overwriting any existing values in the Table2 for all these actions.
I am hoping to write some sort of TRIGGER function, but as an alternative I wouldn't mind running a query that does this every now and then. I just don't want to manage these changes manually.
Is there any way to do this?

A: It can't be automated using the way you've stored the data in columns.
Perhaps this is a clue that you should store the data in a different way.
Another clue is that the changes occur so frequently that you need adding and dropping of the columns to be automated!
Here's an example:
Table1
 dataset attribute value
      1    col2    True
      1    col3    'Foo'
      2    col2    False
      2    col3    'Bar'
      3    col2    False
      3    col3    'Baz'

This is also called an Entity-Attribute-Value table. It has plenty of drawbacks too, but its advantage is that you can add or drop attributes just by inserting or deleting rows.
But you also need a table to record the canonical set of attributes that you allow.
Metadata
 attribute type    default
   col2     bool    False
   col3     string  ''

In this table too, adding a new attribute is just an insert. You can make the attribute in the first table a cascading foreign key, so if you delete a row from the Metadata table it automatically deletes matching rows that reference it.
You also need a table to annotate which attributes are to be included in each view:
Viewership
 view    attribute  show
 'admin'     col1   True
 'admin'     col2   True
 'admin'     col3   True
 'sales'     col1   True
 'sales'     col1   False
 'sales'     col1   False
'default'    col1   False
'default'    col2   True
'default'    col3   False

You are still required to manually insert rows to this table if you add a new attribute. But that's easier than adding columns.
You might be able to automate this a bit with triggers so when you insert a new row to the Metadata table, it adds a row for each view to this table. But in my experience, it's not worth the effort to use triggers. Just code it that way in your application.
(You should also assume a default that if an attribute fails to be added to the view table, it is hidden by default.)


text:
Q: PHP string encoding is not recognized by strpos()? I have a binary Word .doc that looks something like this in string format:
þÿÿÿÿÿÿÿppp"±¶g œÙ Text in word doc here I'm interested in  [|`ñÿ|Standard1$S_HmHnHsHtHOJPJQJCJEH567>

When I echo that string, I can see all the text I'm interested in finding in between unrecognized characters (but those I'm not worried about them since I only want the text). The issue is that PHP does not seem to recognize it as a string and so I cannot search it with strpos(), strpos(), strchr(), mb_strpos() all return nothing. No -1, no error in the PHP error log, just nothing.
However, when I call gettype() I get string. I suspect this is an encoding issue, but mb_detect_encoding returns UTF-8. I have tried converting it to multiple different encoding types, without avail.
How can I get PHP to search this string? I understand that parsing a Word .doc is more complex of an issue, but for my purposes the plaintext I'm interested in are in the binary data. Does anyone have any experience with this?
Thank you :)

A: Since you string seems binary encoded and you are only interested in text a quick  solution would be to use filter_var to clean the string from non ascii-printable characters.Try using this before searching:
$clean_string = filter_var($str,FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH);

A: Notice the part "Standard1$". php is taking $ as the operator instead of a character.
check here.
<?php

$s = "þÿÿÿÿÿÿÿppp"±¶g œÙ Text in word doc here I'm interested in  [|`ñÿ|Standard1$S_HmHnHsHtHOJPJQJCJEH567>";

$s2 = strpos($s, "interested");
echo $s2;
?>

you might want to put a backslash before that $ sign.


text:
Q: Zoom and reset contollers do not work when placed in UiOutput in shiny app I have the shiny app below in which I use js to add controls to zoom and reset on a svg file. It was working until the moment I put the output inside another UiOutput.
library(shiny)
library(shinyWidgets)
library(DiagrammeR)
library(magrittr)

js <- '
$(document).ready(function(){
var element = document.getElementById("grr");
var instance = panzoom(element);
var z = 1;
$("#zoomout").on("click", function(){
instance.smoothZoom(0, 0, 0.9);
z *= 0.9;
});
$("#zoomin").on("click", function(){
instance.smoothZoom(0, 0, 1.1);
z *= 1.1;
});
$("#reset").on("click", function(){
instance.smoothZoom(0, 0, 1/z);
z = 1;
});
$("#zoomout").on("dblclick", function(){
return false;
});
$("#zoomin").on("dblclick", function(){
return false;
});
});
'

ui <- fluidPage(
  tags$head(
    tags$script(src = "https://unpkg.com/panzoom@9.4.0/dist/panzoom.min.js"),
    tags$script(HTML(js))
  ),

  uiOutput("main")
  #grVizOutput("grr", width = "100%", height = "90vh"),

)

server <- function(input, output) {

  output$main <- renderUI({
    div(
      grVizOutput("grr", width = "100%", height = "90vh"),

      actionGroupButtons(
        inputIds = c("zoomout", "zoomin", "reset"),
        labels = list(icon("minus"), icon("plus"), "Reset"),
        status = "primary"
      )
    )

  })
  output$grr <- renderGrViz(render_graph(
    create_graph() %>%
      add_n_nodes(n = 2) %>%
      add_edge(
        from = 1,
        to = 2,
        edge_data = edge_data(
          value = 4.3
        )
      )
  ))

}

shinyApp(ui, server)

A: That's because the elements defined in the renderUI are not ready yet when the document is ready. A possible technique is to use an interval which will "screen" the document every 100ms, until it finds the element.
library(shiny)
library(shinyWidgets)
library(DiagrammeR)
library(magrittr)

js <- '
$(document).ready(function(){
  var instance;
  var myinterval = setInterval(function(){
    var element = document.getElementById("grr");
    if(element !== null){
      clearInterval(myinterval);
      instance = panzoom(element);
    }
  }, 100);
  var z = 1;
  $("body").on("click", "#zoomout", function(){
    instance.smoothZoom(0, 0, 0.9);
    z *= 0.9;
  });
  $("body").on("click", "#zoomin", function(){
    instance.smoothZoom(0, 0, 1.1);
    z *= 1.1;
  });
  $("body").on("click", "#reset", function(){
    instance.smoothZoom(0, 0, 1/z);
    z = 1;
  });
  $("body").on("dblclick", "#zoomout", function(){
    return false;
  });
  $("body").on("dblclick", "#zoomin", function(){
    return false;
  });
});
'

ui <- fluidPage(
  tags$head(
    tags$script(src = "https://unpkg.com/panzoom@9.4.0/dist/panzoom.min.js"),
    tags$script(HTML(js))
  ),

  uiOutput("main")
  #grVizOutput("grr", width = "100%", height = "90vh"),

)

server <- function(input, output) {

  output$main <- renderUI({
    div(
      grVizOutput("grr", width = "100%", height = "90vh"),

      actionGroupButtons(
        inputIds = c("zoomout", "zoomin", "reset"),
        labels = list(icon("minus"), icon("plus"), "Reset"),
        status = "primary"
      )
    )

  })
  output$grr <- renderGrViz(render_graph(
    create_graph() %>%
      add_n_nodes(n = 2) %>%
      add_edge(
        from = 1,
        to = 2,
        edge_data = edge_data(
          value = 4.3
        )
      )
  ))

}

shinyApp(ui, server)


text:
Q: applying stock chart style in highchart i've so far created an high chart which into my page. However i want to apply different colors if they are below or above 0. I've plotted a line on 0, but cant seem to change the colors so it looks like following:

Here is my code

$(function() {
  $('#chart-container').highcharts({
    title: {
      text: '',
      x: -20 //center
    },
    subtitle: {
      text: '',
      x: -20
    },
    exporting: {
      enabled: false
    },
    xAxis: {
      categories: ['Januar', 'Februar', 'Marts', 'April', 'Maj', 'Juni', 'Juli', 'Aug', 'Septemper', 'Oktober', 'November', 'December'],

      labels: {
        enabled: false
      },
    },
    yAxis: {
      gridLineWidth: 0,
      minorGridLineWidth: 0,
      title: {
        text: ''
      },
      labels: {
        enabled: false
      },
      plotLines: [{
        color: 'orange',
        width: 2,
        value: 0,
      }]
    },
    tooltip: {
      valueSuffix: 'Kr.'
    },
    legend: {
      layout: 'vertical',
      align: 'right',
      verticalAlign: 'middle',
      borderWidth: 0
    },
    credits: {
      enabled: false
    },
    series: [{
      showInLegend: false,
      name: 'Tokyo',
      data: [0.0, 6.9, 9.5, -14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
    }]
  });
});

A: You are looking for the negativeColor and negativeFillColor options.
Here's a link to the official example.
And your code updated:

$(function() {
  $('#chart-container').highcharts({
    title: {
      text: '',
      x: -20 //center
    },
    subtitle: {
      text: '',
      x: -20
    },
    exporting: {
      enabled: false
    },
    xAxis: {
      categories: ['Januar', 'Februar', 'Marts', 'April', 'Maj', 'Juni', 'Juli', 'Aug', 'Septemper', 'Oktober', 'November', 'December'],

      labels: {
        enabled: false
      },
    },
    yAxis: {
      gridLineWidth: 0,
      minorGridLineWidth: 0,
      title: {
        text: ''
      },
      labels: {
        enabled: false
      },
      plotLines: [{
        color: 'orange',
        width: 2,
        value: 0,
      }]
    },
    tooltip: {
      valueSuffix: 'Kr.'
    },
    legend: {
      layout: 'vertical',
      align: 'right',
      verticalAlign: 'middle',
      borderWidth: 0
    },
    credits: {
      enabled: false
    },
    series: [{
      showInLegend: false,
      name: 'Tokyo',
      data: [0.0, 6.9, 9.5, -14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6],
      color: 'purple',
      negativeColor: 'red'
    }]
  });
});


text:
Q: Why my code fails to replace a string with empty string in RDLC column expression? I just want to replace a particular text with blank space in RDLC column.
I want to replace .aspx with "" in every string.
I tried writing
=Replace(Fields!AuditsUserActivity.Value, ".aspx", "")

it works this kinda lines

Page Applicants.aspx viewed

but not for these kinda lines:

Data added in Inspectors.aspx

i.e. it removed '.aspx' from those lines in which .aspx appears in in-between but not for those in which '.aspx' appears at the end of string. Does someone know why?
Update:
I used this but not working
=Replace(Fields!AuditsUserActivity.Value, "@"+".aspx", string.Empty)


text:
Q: The email body is missing when I send mails with attachements using ActionMailer The content in the view is not being displayed. Only the attachment is being sent. Help would be appreciated!
def send
 @subject = "Status of PIS App"
 @recipients = "ssg@gmail.com"
 @from = APP_CONFIG[:email]
 @sent_on = Time.now
 #@content_type = "text/html"
 content_type = "multipart/alternative"

 attachment :filename => "Report.html",:content_type => "text/html",
  :body => File.read("/home/shreyas/repos/mysorepoc/app/models/new1.html")
end

A: When using attachments, you need to specify the text part separately:
def send
  @subject = "Status of PIS App"
  @recipients = "ssg@gmail.com"
  @from = APP_CONFIG[:email]
  @sent_on = Time.now
  #@content_type = "text/html"
  content_type = "multipart/mixed"

  part :content_type => "text/plain", :body => "contents of body"

  attachment :filename => "Report.html",:content_type => "text/html", :body => File.read("/home/shreyas/repos/mysorepoc/app/models/new1.html")
end

And you probably want to send the mail as a multipart/mixed, not as multipart/alternative (unless the attachment really is an alternative representation of the text part).


text:
Q: SELECT some_value FROM php_array WHERE other_values (not mysql !) In MySQL I can SELECT a value from one column of a row WHERE one or more columns have a specified value:
SELECT name FROM table WHERE birthyear = '1965' AND birthplace = 'Vancouver'

Now I have a multidimensional PHP_array (not a mySQL database), and I would like to extract the name from the row for a given birthyear and birthplace in a similar manner. This is the array:
$example = Array
(
    [0] => Array
            (
            [0] => 1965
            [1] => Bob
            [2] => Vancouver

        )

    [1] => Array
        (
            [0] => 1973
            [1] => John
            [2] => Vancouver

        )

    [2] => Array
        (
            [0] => 1965
            [1] => Paul
            [2] => Houston

        )

)

It seems to me that for each WHERE-condition I would need one loop in PHP. If you assume that I need to match several columns (birthday, birthplace, sex, occupation etc.), you'll understand how this slows down the execution over an array with thousands of entries.
How can I do this with the least number of loops?

A: array_filter($example,function($v) { return $v[0] == 1982; });

A: This function will do what you are looking for:
function getNameByYear($year, array $array) {
    $name = false;
    foreach ($array as $a) {
        if ($a[0] == $year) {
            $name = $a[1];
            break;
        }
    }
    return $name;
}

Usage:
$example; // your array
$n = getNameByYear(1965, $array); // Bob
$n = getNameByYear(1973, $array); // John
$n = getNameByYear(1982, $array); // Paul
$n = getNameByYear('1965', $array); // Bob
$n = getNameByYear('1973', $array); // John
$n = getNameByYear('1982', $array); // Paul
$n = getNameByYear('wrong', $array); // false
$n = getNameByYear(2035, $array); // false


text:
Q: Show difference between values in r-plotly I would like to add to the hover information about the difference between the values in the chart. It would be best if it looks like the graphics below.

My example:
library(plotly)
trace_1 <- sample(1:20)
main <- sample(1:20)
diff <-main - trace_1
x <- c(1:20)

data <- data.frame(x, trace_1, diff)

fig <- plot_ly(data, x = ~x, y = ~trace_1, name = 'trace 1', type = 'scatter', mode = 'lines')
fig <- fig %>% add_trace(y = ~main, name = 'main', type = 'scatter', mode = 'lines')
fig <- fig %>%
  layout(hovermode = "x unified")
fig

A: You could add another line that is calculated as the difference andd set the line color to transparent.
library(plotly)

df = mtcars %>%
  tibble::rownames_to_column("cars") %>%
  mutate(diff = mpg - wt)

plot_ly(df) %>%
  add_lines(x = ~cars,y = ~mpg,name="mpg") %>%
  add_lines(x = ~cars,y = ~wt,name="weight") %>%
  add_lines(x = ~cars,y = ~diff,name="diff",line = list(color = "rgba(0,0,0,0)"))


text:
Q: Express routing param seen as endpoint I am trying to get a user by id in a nodeJS, mongodb, and express app(a tutorial). What I receive in postman is that it looks for the endpoint 'user/885427r8448734', when id is equal to 885427r8448734, and it simply doesn't work. I put below 3 pics to better explain
Postman request
general route for the user
specific problematic route


text:
Q: Error on calling showAt method of Ext.menu.Menu Hi I am trying to display context menu on right click of a dataview item. I handled itemcontextmenu event in which I instantiated Ext.menu.Menu and called its showAt method, but
it is giving me error as TypeError: me.el.translatePoints is not a function in Component.js
I observed the el is undefined, what value should be assigned to it so that the translatePoints function works? or there can be other work around?
Please find my code below:
    {
        xtype: 'dataview',
        store: 'SearchedGraphics',
        tpl: [
            '<tpl for=".">',
                '
',
                '

',
                '{shortName:htmlEncode}',
                '
',
            '</tpl>',
            '

'
        ],
        multiSelect: true,
        height: 310,
        trackOver: true,
        overItemCls: 'x-item-over',
        itemSelector: 'div.thumb-wrap',
        emptyText: ORT.Utility.GridEmptyText,

        prepareData: function(data) {
            Ext.apply(data, {
                shortName: Ext.util.Format.ellipsis(data.name, 15),
                sizeString: Ext.util.Format.fileSize(data.size),
                dateString: Ext.util.Format.date(data.lastmod, "m/d/Y g:i a")
            });
            return data;
        },
        listeners: {
            selectionchange: function(dv, nodes ){
                if(false) {
                    var l = nodes.length,
                    s = l !== 1 ? 's' : '';
                    this.up('panel').setTitle('Simple DataView (' + l + ' item' + s + ' selected)');
                }
            },
            itemcontextmenu: function(dataview, record, item, index, event, eOpts){

                var menu = Ext.create('Ext.menu.Menu', {
                    width: 100,
                    el:'p',
                    margin: '0 0 10 0',
                    floating: false,
                    items: [{
                        text: 'regular item 1'
                    },{
                        text: 'regular item 2'
                    },{
                        text: 'regular item 3'
                    }]
                }).showAt(event.getXY());

            }
        }
    }

A: 1) Not sure why you set floating to false. It's a menu, so it should float.
2) You shouldn't be setting the el config at all.


text:
Q: How do I cause objects in my canvas to be attracted to other objects I have plotted some words on a canvas. They have random positions. I want them to slowly gravitate towards one another according to a set of rules.
The rules are that some words have to be above, to the left of, to the right of other words.
var rules = {
    "id": {
      leftOf: ["title"],
    },
    "title": {
      above: ["userId"],
    },
    "completed": {
      "rightOf": ["title"]
    }
  }

How do I add independent gravitational attractions between multiple objects mathematically?
In my codepen, I have just rigged the x and y to the positions rule.
Full code:
<canvas id="canvas" width="1000" height="300"></canvas>

<script type="text/javascript">
// vector code from https://gist.github.com/winduptoy/a1aa09c3499e09edbd33
function Vector(x, y) {
    this.x = x || 0;
    this.y = y || 0;
}

/* INSTANCE METHODS */

Vector.prototype = {
    negative: function() {
        this.x = -this.x;
        this.y = -this.y;
        return this;
    },
    add: function(v) {
        if (v instanceof Vector) {
            this.x += v.x;
            this.y += v.y;
        } else {
            this.x += v;
            this.y += v;
        }
        return this;
    },
    subtract: function(v) {
        if (v instanceof Vector) {
            this.x -= v.x;
            this.y -= v.y;
        } else {
            this.x -= v;
            this.y -= v;
        }
        return this;
    },
    multiply: function(v) {
        if (v instanceof Vector) {
            this.x *= v.x;
            this.y *= v.y;
        } else {
            this.x *= v;
            this.y *= v;
        }
        return this;
    },
    divide: function(v) {
        if (v instanceof Vector) {
            if(v.x != 0) this.x /= v.x;
            if(v.y != 0) this.y /= v.y;
        } else {
            if(v != 0) {
                this.x /= v;
                this.y /= v;
            }
        }
        return this;
    },
    equals: function(v) {
        return this.x == v.x && this.y == v.y;
    },
    dot: function(v) {
        return this.x * v.x + this.y * v.y;
    },
    cross: function(v) {
        return this.x * v.y - this.y * v.x
    },
    length: function() {
        return Math.sqrt(this.dot(this));
    },
    normalize: function() {
        return this.divide(this.length());
    },
    min: function() {
        return Math.min(this.x, this.y);
    },
    max: function() {
        return Math.max(this.x, this.y);
    },
    toAngles: function() {
        return -Math.atan2(-this.y, this.x);
    },
    angleTo: function(a) {
        return Math.acos(this.dot(a) / (this.length() * a.length()));
    },
    toArray: function(n) {
        return [this.x, this.y].slice(0, n || 2);
    },
    clone: function() {
        return new Vector(this.x, this.y);
    },
    set: function(x, y) {
        this.x = x; this.y = y;
        return this;
    }
};

/* STATIC METHODS */
Vector.negative = function(v) {
    return new Vector(-v.x, -v.y);
};
Vector.add = function(a, b) {
    if (b instanceof Vector) return new Vector(a.x + b.x, a.y + b.y);
    else return new Vector(a.x + b, a.y + b);
};
Vector.subtract = function(a, b) {
    if (b instanceof Vector) return new Vector(a.x - b.x, a.y - b.y);
    else return new Vector(a.x - b, a.y - b);
};
Vector.multiply = function(a, b) {
    if (b instanceof Vector) return new Vector(a.x * b.x, a.y * b.y);
    else return new Vector(a.x * b, a.y * b);
};
Vector.divide = function(a, b) {
    if (b instanceof Vector) return new Vector(a.x / b.x, a.y / b.y);
    else return new Vector(a.x / b, a.y / b);
};
Vector.equals = function(a, b) {
    return a.x == b.x && a.y == b.y;
};
Vector.dot = function(a, b) {
    return a.x * b.x + a.y * b.y;
};
Vector.cross = function(a, b) {
    return a.x * b.y - a.y * b.x;
};

var texts = ["userId", "id", "title", "completed"];

var rules = {
    "id": {
      leftOf: ["title"],
    },
    "title": {
      above: ["userId"],
    },
    "completed": {
      "rightOf": ["title"]
    }
  }

var vectors = [];
function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

function Thing(text, x, y) {
  this.text = text;
  this.pos = new Vector(x, y);
  this.velocity = new Vector(getRandomArbitrary(-1, 1), getRandomArbitrary(-1, 1));
  this.thrust = 0.1;
}
var things = texts.map(function (item) {
  return new Thing(item, getRandomArbitrary(0, 900), getRandomArbitrary(0, 300));
}
);

var lookup = {};
for (var i=0; i<texts.length; i++) {
    lookup[texts[i]] = things[i];
}

var ctx = document.getElementById('canvas').getContext('2d');
  ctx.font = '18px serif';

function tick() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

 for (var i=0; i < things.length; i ++) {

   var thing = things[i];
   thing.velocity.add(thing.thrust);

   for (var j=0; j < things.length; j++) {
     if (things[j].text == thing.text) { continue }
     if (!rules.hasOwnProperty(thing.text)) { continue }
     var rule = rules[thing.text];

     if (rule.hasOwnProperty( "leftOf")) {
        console.log(thing.text, "must be left of", rule["leftOf"]);
         for (var k=0; k < rule["leftOf"].length; k++ ) {
            if (rule["leftOf"] == things[j].text) {
              console.log("Changing velocity of", thing.text, "to cause it to be left of", things[j].text);
              thing.pos.x = things[j].pos.x - 20;
              thing.pos.y = things[j].pos.y;
            }
         }
     }

        if (rule.hasOwnProperty( "above")) {
        console.log(thing.text, "must be above", rule["above"]);
         for (var k=0; k < rule["above"].length; k++ ) {
            if (rule["above"] == things[j].text) {
              console.log("Changing velocity of", thing.text, "to cause it to be above", things[j].text);
              thing.pos.x = things[j].pos.x;
              thing.pos.y = things[j].pos.y - 30;
            }
         }
        }

        if (rule.hasOwnProperty( "rightOf")) {
        console.log(thing.text, "must be right of", rule["rightOf"]);
         for (var k=0; k < rule["rightOf"].length; k++ ) {
            if (rule["rightOf"] == things[j].text) {
              console.log("Changing velocity of", thing.text, "to cause it to be right of", things[j].text);
              thing.pos.x = things[j].pos.x + 60;
              thing.pos.y = things[j].pos.y;
            }

        }

     }

   }

     thing.pos.add(thing.velocity);
    ctx.fillText(thing.text, thing.pos.x, thing.pos.y);

 }
}
setInterval(tick, 1000);
</script>


text:
Q: Add user to group automatically after registration in Wordpress I installed Groups plugin in Wordpress and I want to add user to group automatically after registration in Wordpress.
Does anyone know how to do it?

A: You can add in your functions.php
   add_action( 'user_register', 'myplugin_registration_save', 10, 1 );
    function myplugin_registration_save( $user_id ) {
    if ( isset( $_POST['first_name'] ) )
            do_shortcode('[groups_join group="Knitting"]');
        }


text:
Q: OnNmeaMessageListener not working for samsung j7, android 6.0.1 When testing an app that uses the OnNmeaMessageListener on a Samsung J7 the app breaks with this error

And I really don't get what is the problem, I've tested on other devices and the app works.
Code that I'm testing:
 LM.addNmeaListener(new OnNmeaMessageListener() {
                @Override
                public void onNmeaMessage(String nmea, long timestamp) {
                 // do stuff
                }
    });

A: Ok I found a possible solution for SDK versions below 24
             if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.N) {
                GpsStatus.NmeaListener nmeaListenerDeprecated = new GpsStatus.NmeaListener() {
                    @Override
                    public void onNmeaReceived(long timestamp, String nmea) {
                        processNmeaData(nmea, timestamp);
                    }
                };
                try {
                    //noinspection JavaReflectionMemberAccess
                    Method addNmeaListener =
                            LocationManager.class.getMethod("addNmeaListener", GpsStatus.NmeaListener.class);
                    addNmeaListener.invoke(LM, nmeaListenerDeprecated);
                } catch (Exception exception) {
                    // TODO
                }
            } else {
                LM.addNmeaListener(new OnNmeaMessageListener() {
                    @Override
                    public void onNmeaMessage(String nmea, long timestamp) {
                        processNmeaData(nmea, timestamp);
                    }
                });
            }

with that solution I manged to get NMEA working for new and older devices.


text:
Q: how to convert a given string into Integer in JS I tried this but i always get wrong value on the last index of given string.
let n= '9875987598759875';
let g= Math.floor(Number(d));
console.log(g);
I am getting this in the output = 9875987598759876
I notice this always happens whenever the last index of my string got any odd value, any ideas ?


text:
Q: Couldn't read TokensRegexNER Stanford NLP Hello everyone and thanks for your help in advance.  I am brand new to trying to use Stanford NLP and am trying to follow the C# example at https://sergey-tihon.github.io/Stanford.NLP.NET/samples/CoreNLP.Pipeline.html.  I am recweiving an error:
An unhandled exception of type 'edu.stanford.nlp.io.RuntimeIOException' occurred in stanford-corenlp-3.9.1.dll
Additional information: Couldn't read TokensRegexNER from edu/stanford/nlp/models/kbp/regexner_caseless.tab
The error is being thrown at the line:
var pipeline = new StanfordCoreNLP(props);

I've been searching this error buthaven't found a resolution yet.  Since I've never worked with NLP and have never worked with jar files, I'm wondering if I simply have my folders and paths incorrectly set up but don't inow how to proceed.  Any help would be appreciated.


text:
Q: Which probability is correct There are three indentical balls marked $A, B$ and $C$ randomly shuffled in a bag.  Consider the experiment that balls are drawn out from the bag until the ball marked '$C$' is drawn. We have to find the probability that the first ball drawn will be marked '$C$'.
I tried doing the problem in $2$ ways-
1) The possible outcomes of the experiment are $C, AC, BC, ABC, BAC$ out of which only the first is favourable. Hence probability $=1/5$.
2) There are $3!=6$ ways of drawing the $3$ balls out of which $2$ ways ($CAB$ and $CBA$) are favourable. Hence probability $=1/3$.
The first method seems more true to the experiment while the second one seems more correct intuitively to me. Which one is correct?
Also, if the experiment was performed with three cards marked $A, B$ and $C$ instead, what would be the correct probability? In this case, the second method seems much more logical to me as, unlike in the first experiment wherein the balls are randomly drawn, in this case once the cards are shuffled, their order becomes fixed.

A: You have the correct possible outcomes, and to me, that seems like the easier approach.
$$C, AC, BC, ABC, BAC$$
The probability of these, respectively, are
$$\frac{1}{3}, \frac{1}{6}, \frac{1}{6}, \frac{1}{6},\frac{1}{6}$$
$$P(C\text{ is first ball chosen})=\frac{\frac{1}{3}}{\frac{1}{3}+ \frac{1}{6}+ \frac{1}{6}+ \frac{1}{6}+\frac{1}{6}} = \frac{1}{3}$$
This is the same as the probability of selecting $C$ first, without the constraint that we select balls until we draw $C$.


text:
Q: Expressibility of Peano arithmetic and the Arithmetical Hierarchy First-order Peano arithmetic has no non-logical symbols other than S, +, *, < and variables. One allows finite quantification over predicates such as: $\forall k<n: \phi(k)$ where $\phi(k)$ is a logical formula containing some non-logical symbol such as Ak. This is because it is understood as a shorthand for $\phi(1)\land \phi(2)...\land \phi(n)$. That way the Ak-s are nothing but n different variables. For example:
$(A_0=1) \land \forall k<3: (A_{k+1} = A_k*(k+1))$
is actually:
$(A_0=1) \land (A_1 = A_0*1)\land (A_2 = A_1*2)$.
This way we can deal with primitive recursive functions.
However, situation is different when moving up in the arithmetical hierarchy. For example, in $\Sigma_1^0$ it is no longer possible to make the above substitution, because the number of variables will now depend on a non-fixed variable on which we quantify in a non-bounded way. Taking the above example, we now have:
$\exists n: (A_0=1) \land \forall k<n: (A_{k+1} = A_k*(k+1))$
which we obviously cannot turn into a formula with no new non-logical symbols.
So my question is: Do we actually allow other non-logical symbols in first-order Peano arithmetic in certain conditions? or do the arithmetical hierarchy formulas actually not belong to first-order Peano arithmetic? or am I missing something?

A: You are misinterpreting bounded quantifiers.
"$\forall x<y(\varphi)$" is shorhand for "$\forall x(x<y\rightarrow \varphi).$"
Similarly, "$\exists x<y(\varphi)$" is shorthand for "$\exists x(x<y\wedge\varphi)$."
This can be generalized greatly: in any language, for any definable binary relation $R$, we write "$\forall x Ry(\varphi)$" as shorthand for "$\forall x(xRy\rightarrow \varphi)$," etc. For example, expressions of the form "$\forall x\in y$" are common in set theory, and there's a corresponding version of the arithmetical hierarchy in which such expressions are "for free" (similarly to bounded quantification in arithmetic).

Note that the "substitution" interpretation you give breaks down immediately if the model under study is something other than the classical $\mathbb{N}$. Suppose $M$ is a nonstandard model of $PA$, and $c\in M$ is an infinite element. Then how would you interpret "$\forall x<c(\varphi(x))$"?

A: It turns out that https://en.wikipedia.org/wiki/Course-of-values_recursion is the way to make this possible.
More elaborately, for any quantifier-free formula $\varphi$ one has to create the Goedel number of the formula:
$a_0 = C \land \forall n: a_{n+1} = \varphi(n, a_n)$
where C is some constant (e.g. C could be 1).
Then it can be shown that there is a number and some (other) first-order formula $\psi$ such that:
$\psi(G, 0, C)$
and:
$\psi(G,n,m)$ if and only if, in first order arithmetic to which we add the predicate $a_n$, the recursion formula defined by $\varphi$ implies: $a_n = m$. Thus in proper first order arithmetic (without addition of new predicates) the recursion can be "recreated" by G and $\psi$.
One way to do that is with Goedel's beta function: https://en.wikipedia.org/wiki/G%C3%B6del%27s_%CE%B2_function.


text:
Q: How to access swift class in objective-c file I have a swift project and i import a singleton, objective-c coded class in the project.
I tried to import the productname_swift.h file but no luck.
How can i access swift class in that singleton class?

A: Project made in Swift : To use Swift class in Objective C
To use Swift class in Objective C , follow given steps :

*

*Create one Objective C class named User.

*A popup display with  "Would You like to configure an Objective-C bridging Header". Choose Create Bridging Header.

User.h
#import <Foundation/Foundation.h>

@interface User : NSObject

+(id) sharedUser ;

@end

User.m
#import "User.h"
#import "SwiftInObjectiveC-swift.h"

@implementation User

//Singleton of User

+(id)sharedUser{

    static User *sharedUser = nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        sharedUser = [[self alloc] init];

        //Class Method of ViewController.swift
        [ViewController mySwiftClassFunction];

        //Instance Method of ViewController.swift
        ViewController *vc = [[ViewController alloc] init];
        [vc mySwiftFunction];

    });
    return sharedUser;
}

-(void) myObjcectivecMethod {

    ViewController *vc = [[ViewController alloc] init];
    [vc mySwiftFunction];

}

*Add @objc in your .swift class in front of Class name.
 import UIKit

 @objc class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func mySwiftFunction() {

    print("Swift Function")
}

class func mySwiftClassFunction (){

    print("Swift Class Function")

}

}

*Go to Build Settings.

*Set Product Module Name : ProjectName

*Set Defines Module : YES

*Set Embedded Content Contains Swift : YES

*Set Install Objective-C Compatibility Header : YES

*Set Objective-C Bridging Header : SwiftInObjectiveC/SwiftInObjectiveC-Bridging-Header.h

*Import Auto generated header "ProjectName-swift.h" in your *.m file.

*Clean and Run your Project.

*It will work!!!

Follow Apple link for Mix and Match for detailed information.

A: It is very simple use Swift classes in Objective-C. Just follow steps given below

*

*Open your Objective-C project.

*Add a new swift file to the project.

*One default dialogue will open to create a bridging header (If it
does not open by default, add a bridging header file).

*Go to build settings type Swift Compiler and you will see Your
ProjectName-Swift.h in Swift Compiler- General like below

*Import you desired swift classes build and run.

A: Adding multiple Swift files to an Objective-C project.
Let's say you want to add Class1.swift, Class2.swift, and Class3.swift file to the SwiftToObjC project

*

*Add Class1.swift file to the project.

*XCode will ask "Would You like to configure an Objective-C bridging Header"? You choose "Create Bridging Header". So the SwiftToObjC-Bridging-Header.h file as well as the SwiftToObjC-Swift.h file are generated.

*In the SwiftToObjC-Bridging-Header.h file you add this line

@class Class1;

*When you add Class2.swift and Class3.swift to the project, you also add these two classes to the SwiftToObjC-Bridging-Header.h file as follows.

@class Class1;
@class Class2;
@class Class3;

5. In the target SwiftToObjC, under Build Settings, Swift-Compiler General you should see these two settings:

Objective-C Bridging Header -> SwiftToObjC-Bridging-Header.h
Objective-C Generated Interface Header Name -> SwiftToObjC-Swift.h

6. In the target SwiftToObjC, under Build Settings, Define Module is set to YES.

*If you want to access Class1 in say MyViewController, then in MyViewController.m, you should import.

#import "SwiftToObjC-Bridging-Header.h"

*In your Class1.swift file, declare your class as "@objc public" as follows. The same @objc public is used for Class2 and Class3.

@objc public class Class1: UITableViewController

Note that: UITableViewController is only an example for demonstration purpose.
That's all.


text:
Q: Salesforce send push notification calls APNS or Android? We are currently working on integrating sales force mobile push sdk in our android app. We have the salesforce sdk returning the device token and also we are able to trigger the push notification. But we are interested in knowing about how does the sales force's send push notification rest api call (with the device token in the request) internally talks to the appropriate vendor(Google/Apple) to trigger push notification to the device? Do you call the GCM/APNS push notification apis from sales force along with the device token to trigger push notification? Also please let us know the complete push notification flow after the send push notification api request reaches Salesforce?

A: Salesforce's push servers use the device's token with GCM or APNS to deliver push messages.
You're going to have to be more specific about your 2nd question.


text:
Q: what exactly are built-in types in Python? I keep hearing "everything is an object" in both Ruby and Python world. Well, what are built-in functions then? Can someone explain that in layperson English?
For example:
file=open(abc.txt)

open is a built-in function. Is it an object? Is it a method? Of what class?
How did we even end-up with functions in Python if everything is an object? I mean, shouldn't we be having class, objects, methods and attributes, instead of functions? I thought we had functions in languages like C. Python, Ruby and Java had classes, objects, attributes, methods.
In Ruby (irb), you could do something like 1.class and this will give you Fixnumit will show you which class it belongs to. I don't seem to be able to do this in Python shell. Is there an equivalent?
FYI:

*

*I am using Python 2.7

*relatively new to programming so please use layperson English. For instance, I read in one of the answers "But everything is an object in the sense that it can be assigned to a variable or passed as an argument to a function" --- no idea what that means.

A: They are all listed here: http://docs.python.org/library/functions.html
The function open is an object (all functions are objects) and belongs to the __builtin__ module. They are simply built-in, and available to all objects, since they are automatically imported (something like from __builtin__ import *).
>>> print repr(open)
<built-in function open>

>>> print open.__module__
__builtin__

>>> import __builtin__
>>> print __builtin__.open
<built-in function open>

Update
You mentioned in your edit that you don't know what assigning a function means.
>>> o = open
>>> print repr(open)
<built-in function open>
>>> print repr(o)
<built-in function open>
>>> o('file.txt')
<open file 'file.txt', mode 'r' at 0x107fe49c0>

A: Everything is an object, but not every object is an instance of a useful class in the classic sense. Some things you're better off treating as plain objects, as far as I can tell (functions are a good example that's already been given).
Note that you can use type(obj) or inspect obj.__class__ to replicate Ruby's .class method somewhat (see delnan's comment about the caveat for integers, though). You can also see the 'order' of the full inheritance sequence by issuing type.mro(type(obj)).
In [7]: type.mro(type(open))
Out[7]: [<type 'builtin_function_or_method'>, <type 'object'>]

In [4]: import datetime
In [5]: d = datetime.datetime(2009,11,11)
In [6]: type.mro(type(d))
Out[6]: [<type 'datetime.datetime'>, <type 'datetime.date'>, <type 'object'>]


text:
Q: ReleaseArrayElements not actually releasing memory from the heap during JNI call? I am developing an Android application that interfaces with some Native C++ code (JNI). On the Java side, I pass a look up table (double array) and two Open-CV matrices over to the JNI (by reference) to then process the matrices with C++. While the JNI function call works for the first 15~20 times, the application crashes and restarts soon after. I am 99% sure this is an issue with me not properly freeing up memory on the heap.
I have looked at the Profiler to check what is going on with the memory and I see a consistent increase in memory usage with each JNI function call. Most of the memory allocation seems to be in the Native portion, and you can see this increase in the image below (increase coincides with the calls to the JNI function).

extern "C" JNIEXPORT void JNICALL
Java_com_mygroup_productName_ImgProcUtils_interpVals(
        JNIEnv *env,
        jobject /* this */,
        jlong addrKSqrd,
        jint nRows,
        jint nCols,
        jdoubleArray yTaucVal,
        jlong addrTauc) {
    cv::Mat& kSqrd = *(cv::Mat*)addrKSqrd;
    cv::Mat& Tauc = *(cv::Mat*)addrTauc;
    jboolean isCopy;
    jdouble *elem = env->GetDoubleArrayElements(yTaucVal, &isCopy);
    float pixel;
    for (int i = 0; i < nRows; i++) {
        for (int j = 0; j < nCols; j++) {
            pixel = kSqrd.at<float>(i, j);
            int value = (int)round(pixel * 65535);
            if (value < 0) {
                value = 0;
            } else if (value > 65535) {
                value = 65535;
            }
            Tauc.at<float>(i,j) = (jfloat)elem[value];
        }
    }
    env->ReleaseDoubleArrayElements(yTaucVal, elem, JNI_ABORT);
}

As you can see, I am releasing the double array I "get" before the for loops, but it seems like we still have memory that is not being released. Do I have to do anything else to properly release the memory? Is there any additional data that I need to release?

A: I doubt it's releasing issue.
If I have super simple Java code like this
package recipeNo026;

public class PassArray {

  public static native void passDoubleArray(double[] array);
  static { System.loadLibrary("PassArray"); }

  public static void main(String[] args) throws Exception {
    for(int i=0; i<100; i++) {
      double[] doubleArray = new double[1_000_000_000];
      passDoubleArray(doubleArray);
      Thread.sleep(1000);
    }
  }
}

and the native code has no other calls than calls to JNI stuff
JNIEXPORT void JNICALL Java_recipeNo026_PassArray_passDoubleArray
  (JNIEnv * env, jclass obj, jdoubleArray array) {

  printf ("Double array\n");
  jboolean isCopy;
  jdouble *doubleBody = (*env)->GetDoubleArrayElements(env, array, &isCopy);
  (*env)->ReleaseDoubleArrayElements(env, array, doubleBody, JNI_ABORT);
}

memory consumptions seems to be pretty stable in both: Java heap and native code. And you can see how native memory is being allocated and released while code proceeds.

I'd definitely start looking for the leak in parts of the code that are called from your JNI wrapper.
Also, be aware of the fact, that native memory can grow even though you don't call native code at all (e.g. JNI). After all, Java have to make allocations using malloc for it's own heap at some point. Take a look here:
public static void main(String[] args) throws Exception {

    int size = 10;

    double [][] array = new double[100][1];

    for(int i=0; i<100; i++) {
      array[i] = new double[size];
      size = size * 2;
      System.out.println("Allocating: " + size);
      Thread.sleep(1000);
    }

  }

there is no JNI call anymore. Now, let's run the app.
> java -Xmx4G -Xms512m -Djava.library.path=:./lib -cp target recipeNo026.PassArray
library: :./lib
Allocating: 20
Allocating: 40
Allocating: 80
Allocating: 160
Allocating: 320
Allocating: 640
Allocating: 1280
Allocating: 2560
Allocating: 5120
Allocating: 10240
Allocating: 20480
Allocating: 40960
Allocating: 81920
Allocating: 163840
Allocating: 327680
Allocating: 655360
Allocating: 1310720
Allocating: 2621440
Allocating: 5242880
Allocating: 10485760
Allocating: 20971520
Allocating: 41943040
Allocating: 83886080
Allocating: 167772160
Allocating: 335544320
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at recipeNo026.PassArray.main(PassArray.java:25)

and let's take a look at native memory consumption (over time) of Java process.


text:
Q: How to substitute type by child type in function definition in TypeScript? interface Parent {
    name: string;
}

interface Child extends Parent {
    name: string;
    text: string;
}

function myFunction(text: string, target: Child): Child {
    target.text = text;
    console.log(target);
    return target;
}

const testChild: Child = {
    name: 'test',
    text: 'sample',
};

declare type FunctionType = (text: string, target: Parent) => Parent;

const func: FunctionType = myFunction;

func('newText', testChild);

This code leads to an error, because FunctionType awaits a function that has Parent (instead of Child) as one of arguments and result. Is there a way to make it works with direct descendants of Parent (like Child is)?
When it might be useful?
Let's imagine we have Angular component that accepts simple slim items (like our Parent) and handler function, but we want to give a Child item and corresponding handler function (myFunction in our case) to this component. All component's internal functions touch only Parent-related fields.
I know that it is possible to create a subclass for parent component's class in Angular and override properties. But this will be a pain to create a new component or class for each new 'Child' type.
It's only for example.
My general question is how to define function type that will accept not only Parent interface, but also all child interfaces (without listing children)?
Actually I am trying to implement basic substitution principle: What works for parent should work for children.

A: I suppose you can make generic to make it work, which seems to be the way to go in your case:
declare type FunctionType<T extends Parent = Parent> = (text: string, target: T) => T;

const func: FunctionType<Child> = myFunction;

playground
example to show it only works with descendants of Parent, because of T extends Parent:
playground


text:
Q: Netgear WNR1000v4 Keeps Disconnecting I've updated the firmware, still problems. I've tried hard reseting it, still problems. I've tried wired connection instead of wireless, still problems. The only way I get good internet is to stop using router and just plug into wire coming into building so it's definitely the router. I've checked user log, I'm only one using it. I have 150Mb/s download, 150Mb/s upload; using router I get 20 Mb/s download and maybe 8Mb/s upload but upload drops to 0 for a couple seconds every ~5 minutes. Router is rated for 150Mb/s so really performing sub par. Any ideas?

A: There's no alternative firmware for this model - Get yourself a TL-WR841N then install openwrt. Cheapest and most reliable router out at the moment.

A: I have the same model and though it worked great for a couple years, now having horrible packet loss.  We live in a crowded area and I assume this is interference.  I have just switched the channel from '3' to '11' on the 'Wireless' screen in the admin page, and for the moment, things are much better.


text:
Q: using getline(cin, string) on a loop not working properly I am using a for loop to input data in a structure array, I am not able to get a string variable to have white spaces, such that the stored name is two or more words as opposed to one. Can anyone help me properly use getline in a loop?
It works when I do not use a loop, not sure what is causing the error in this program though.
Below is the sample that is giving me trouble:
void Data_Input(int numberOfStudents, int numberOfTests, classroom* &student){
    for (int count = 0; count < numberOfStudents; count++){
        cout << "For student number " << count + 1 <<
                ", please input the following data:";
        cout << "Student Name: ";
        //cin >> student[count].Name; (this option does not allow white spaces)
        getline(cin, student[count].Name); // <-- this line
    }
}

A: I've modified your program slightly so that I could test your function and I couldn't find any problems with what I expect the behavior to be, could you elaborate one what you're trying to accomplish?
The way your code is currently formatted, I expect that student[count].Name is an std::string.
#include <iostream>

void Data_Input(int numberOfStudents, int numberOfTests){

    for (int count = 0; count < numberOfStudents; count++){
        std::cout << "For student number " << count + 1 << ", please input the following data:";
        std::cout << "Student Name: ";
        //cin >> student[count].Name; (this option does not allow white spaces)
        std::string student;
        getline(std::cin, student);

        std::cout << student << std::endl;
    }
}

int main() {

    Data_Input(5, 0);

}

runtime:
For student number 1, please input the following data:Student Name: John Smith
John Smith
For student number 2, please input the following data:Student Name: Anne Smith
Anne Smith
...


text:
Q: Quickly package/submitubuntu fails because of debhelper dependency When running the submitubuntu or package command, I get this fatal error:
quickly.templatetools.CantUpdateFile: Build-Depends: debhelper (>= 8), was not found in the file myproject/debian/control.
ERROR: submitubuntu command failed

The debhelper dependency in control is set by quickly itself, if I change it, it is changed back before packaging.

A: Solved by upgrading, it was indeed this bug:
https://bugs.launchpad.net/ubuntu/+source/quickly/+bug/1022514


text:
Q: How do I access imported local settings without a circular import? At the end of my settings.py file, I have:
try:
    from local_settings import *
except ImportError:
    pass

I then have a local_settings.py file where I have some db settings, etc. In this file I would also like to do the following (in order to use django_debug_toolbar):
INTERNAL_IPS = ('127.0.0.1',)
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS += ('debug_toolbar',)

I want to put these settings here so that they don't show up in the production environment, which uses the main settings.py file, but of course this file can't access the original settings because it doesn't know about settings.py. How can I avoid a potentially circular import to achieve what I'm trying to do?

A: You can't do this. The imported module is executed in it's own scope and has no way of knowing where (and if) it is has been imported in any way. An alternative way would be something like this:
In your local_settings:
INTERNAL_IPS = ('127.0.0.1',)
MIDDLEWARE_CLASSES = ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS = ('debug_toolbar',)

And in the main settings.py
try:
    import local_settings as local
    has_local = True
except ImportError:
    has_local = False

# ...
if has_local:
    MIDDLEWARE_CLASSES += local.MIDDLEWARE_CLASSES

A: I use an approach in which my settings is actually a package and not a module
settings/
  init.py
  base.py
  local.py #this one is on .gitignore
init.py:
from setings import *
try:
    from local.py import *
except ImportError:
    pass

base.py:
import os
DEBUG = False
TEMPLATE_DEBUG = DEBUG

SITE_ROOT = os.path.join( os.path.dirname( os.path.realpath(__file__) ) ,'..' )

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
    }

etc...

local.py:
from settings import settings as PROJECT_DEFAULT

PREPEND_WWW = False
DEBUG = True
TEMPLATE_DEBUG = DEBUG

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_pyscopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'somesecretname',                      # Or path to database file if using sqlite3.
        'USER': 'somesecretuser',                      # Not used with sqlite3.
        'PASSWORD': 'somesecretpassword',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

INSTALLED_APPS += PROJECT_DEFAULT.INSTALLED_APPS + ('debug_toolbar',)

You can see an example of this in here


text:
Q: Trace minimization subject to diagonal constraints Problem Revisited - Edited for conciseness:
We are given two set of data points X [$p \times n$] and Y [$q \times n$].
Let us assume $X = \hat{X} + \tilde{X}$ and $Y = \hat{Y} + \tilde{Y}$
I am trying to minimize the following objective function for $\hat{X}$ and $\hat{Y}$:
\begin{equation*}
\begin{aligned}
& \underset{\hat{X}, \hat{Y}}{\text{minimize }}
& &
  \|\hat{X}'\hat{X} - \hat{Y}'\hat{Y}\|_F^2 \\
&&  =& Tr((\hat{X}'\hat{X})^2) - 2Tr(\hat{X}'\hat{X}\hat{Y}'\hat{Y}) + Tr((\hat{Y}'\hat{Y})^2)
  \end{aligned}
\end{equation*}
subject to the constraints that under the constraints that $X\tilde{X}'=0$ and $Y\tilde{Y}'=0$, and both $\Phi = \tilde{X}\tilde{X}'$ and $\Theta = \tilde{Y}\tilde{Y}'$ are PSD and diagonal.
After expansion of the above equation and application of cauchy-schwarz inequality, the original problem is reduced to the following objective function, subject to the constraint that $\Phi$ [$p \times p$] and $\Theta$ [$q \times q$] are both diagonal matrices and PSD.
$$
\begin{aligned}
& \underset{\Phi, \Theta}{\text{minimize }}
& & f\\
&
& \leq & 2 Tr(XX'\Phi) + Tr(\Phi^2) + 2Tr(YY'\Theta)+ Tr(\Theta^2) \\
&&+& 2Tr(XX')Tr(\Theta) + 2 tr(YY')Tr(\Phi) + 2Tr(\Theta)Tr(\Phi) \\
& \text{subject to}
& & \Phi \text{ and } \Theta \text{ are diagonal and PSD}\\
\end{aligned}
$$
1) Does this equation have a unique solution? If so, how can I find the solution? If not, what are the solution concepts, say w.r.t. minimization of different norms?
2) When I try to encode the problem in terms of the sum of the diagonal elements of $\Phi$ and $\Theta$, the problem is reduced to a convex quadratic program. But what does knowing about the sum of diagonal elements tell about the actual matrix itself, even if we have some extra information about say, the rank of matrices.

A: This is what I'm thinking. Ignore your attempt to use Cauchy Schwarz. Your problem looks like this:
\begin{array}{ll}
\text{minimize}   & \left\| (X^TX-\Phi) - (Y^TY-\Theta) \right\|_F \\
\text{subject to} & 0 \preceq \Phi \preceq X^T X \\
                  & 0 \preceq \Theta \preceq Y^T Y \\
                  & \Phi,\Theta~\text{diagonal}
\end{array}
where $\preceq$ is the generalized inequality on the semidefinite cone; for instance, $\Phi\preceq X^TX$ means that $X^TX-\Phi$ is positive semidefinite.
This is convex, and in fact a semidefinite program, and is therefore amenable to solution by any semidefinite programming solver.
EDIT: I just realized it can be simplified. Since the variables only concern the diagonal, there's no point in looking at the Frobenius norm of the entire matrix, just look at the diagonal.
\begin{array}{ll}
\text{minimize}   & \left\| \mathop{\textrm{diag}}(X^TX-Y^TY)-\phi+\theta \right\|_2 \\
\text{subject to} & \phi,~\theta_i \geq 0, ~ i=1,2,\dots, n \\
                  & X^T X - {\mathop{\textrm{diag}}}^{-1}(\phi) \succeq 0 \\
                  & Y^T Y - {\mathop{\textrm{diag}}}^{-1}(\theta) \succeq 0
\end{array}
Not a huge savings, but why not. Now $\phi$ and $\theta$ are just vectors.


text:
Q: "IndexError: list index out of range" when performing string checking Ideally, I'd like to be able to prompt users for "Small" or "S", "Medium" or "M" and "Large" or "L" when determining prices for drinks. This is all case insensitive, so "s" or "smaLL" is good, etc. If i input just an 'M', I get an error for an index code out of range, and it computes as a small. A large gives me a medium. Help?
print("Ie. 'S', 'M', 'L', 'Small', 'Medium, 'Large'" +
      " or any variations in their letter case sensitivity will work.")
beverageSize = str(input("Input your desired size: "))
print("")

if len(beverageSize) > 1 and len(beverageSize) < 5:
  exit(print("Error with choice of beverage input."))

elif beverageSize.startswith("S") or beverageSize.startswith("s") and\
            beverageSize is beverageSize.isalpha() and len(beverageSize) == 0 or len(beverageSize) == 4 or\
            beverageSize[0] == "S" or beverageSize[0] == "s" and\
            beverageSize[1] == "M" or beverageSize[1] == "m" or beverageSize[1] == "" and\
            beverageSize[2] == "A" or beverageSize[2] == "a" or beverageSize[2] == "" and\
            beverageSize[3] == "L" or beverageSize[3] == "l" or beverageSize[3] == "" and\
            beverageSize[4] == "L" or beverageSize[4] == "l" or beverageSize[4] == "" and\
           len(beverageSize) != 5:

        beverageSize = SMALL_SIZE
        print("SMALl")

elif beverageSize.startswith("M") or beverageSize.startswith("m") and\
            beverageSize is beverageSize.isalpha() and\     len(beverageSize) == 0 or len(beverageSize) == 5 or \
            beverageSize[0] == "M" or beverageSize[0] == "m" and\
            beverageSize[1] == "E" or beverageSize[1] == "e" or beverageSize[1] == "" and\
            beverageSize[2] == "D" or beverageSize[3] == "d" or beverageSize[3] == "" and\
            beverageSize[3] == "I" or beverageSize[3] == "i" or beverageSize[3] == "" and\
            beverageSize[4] == "U" or beverageSize[4] == "u" or beverageSize[4] == "" and\
            beverageSize[5] == "M" or beverageSize[5] == "m" or beverageSize[5] == "":

        beverageSize = MEDIUM_SIZE
        print("MEDIUM")

A: There are smarter ways for testing the value of variables in python. One method using if-else conditions has already been suggested in the comments. Here's another short, concise method using a dict:
size_dict = {'s' : SMALL_SIZE, 'small' : SMALL_SIZE,
             'm' : MEDIUM_SIZE,'medium' : MEDIUM_SIZE,
             'l' : LARGE_SIZE, 'large' : LARGE_SIZE}
beverageSize = size_dict.get(beverageSize.lower(), 'Invalid Size')

This uses dict.get to extract values associated with your input. If the user entered a word that does not exist as a key in the dictionary, then beverageSize is assigned the value Invalid Size.

A: Firs of all, your program won't work because this will always be true for allowed values:
if len(beverageSize) > 1 and len(beverageSize) < 5:
  exit(print("Error with choice of beverage input."))

Then, give yourself a break and avoid all lower/uppercase checks by just using this before comparing stuff:
bevarageSize = bevarageSize.lower()

Now start comparing:
if (beverageSize == 's' or bevarageSize == 'small'):
  print 'small'
elif (beverageSize == 'm' or bevarageSize == 'medium'):
  print 'medium'
elif (beverageSize == 'l' or bevarageSize == 'large'):
  print 'large'

Or even better, using real Python style:
if (beverageSize in ('s', 'small')):
  print 'small'
elif (beverageSize in ('m', 'medium')):
  print 'medium'
elif (beverageSize in ('l', 'large')):
  print 'large'


text:
Q: How to validate form fields before moving to next slide I'm building a form that is broken up into slides. I want to make it so that when a user clicks the arrow to move to the next slide, the form first validates whether the information he/she put in is valid for the input field. If so, it moves on and if not it alerts the use with some visual effect.
Here is the code
    $('.next').click(function() {
    if(indexBG === 3){
        indexBG = 3;
        $('#RF'+indexBG).css('display', 'block');
        $('#RF'+indexBG).fadeOut(500);
        $('#RF'+indexBG).fadeIn(500);
     }
     else {
           validateIt();
     }
     function validateIt() {
           if(!isValidEmailAddress($('#email-reg-input').val())) {
                $('#email-reg-input').css("border","red solid thin");
            }
            else {
                  $('#RG1').css('background-color','green');
                  $('#RG1').html('33% Complete!');
            }
            if($('#name-reg-input').val() == ''){
                  $('#name-reg-input').css("border","red solid thin");
             }
             else {
                  $('#name-reg-input').css("border","green solid thin");
             }
     };
     });

A: Form validation can get pretty tricky. Especially when you consider all of the different use cases and variations of junk users can enter. So, since you're already using jQuery, you might want to check out the jQuery Validation Plugin.


text:
Q: Autowiring of exchange, queue and binding with Spring AMQP + RabbitMQ (Spring Boot) In the Spring docs for Messaging with RabbitMQ, rabbitTemplate, queue, exchange and binding are all set up by Spring Boot. What I don't understand is how rabbitTemplate.convertAndSend(...) sends it to the created exchange, since the method call does not specify an exchange and it includes only the routing key (via the queue name) and the message itself - which I thought implicitly sends the message to the default exchange and not the created exchange. The message will reach the intended queue since the routing key matches the name of the queue.
If I wanted to specify the exchange and routing key, using this API method:
// Convert a Java object to an Amqp Message and send it to
// a specific exchange with a specific routing key.
convertAndSend(String exchange, String routingKey, Object object);

... how do I get a reference to the created exchange?
Thanks.

A: Boot's RabbitAutoConfiguration only registers the connection factory, a RabbitAdmin a RabbitTemplate and a RabbitMessagingTemplate.
That guide declares its own exchange, queue, and binding.
You can simply @Autowire the exchange as normal and call getName().


text:
Q: Java Why does the constructor for a DatagramPacket need the length of the byte array? According to the javadocs very constructor in the DatagramPacket class requires an array of bytes and an integer less than or equal to the length of that array.
e.g:

DatagramPacket(byte[] buf, int length)

All the examples i have seen simply pass the length attribute of the byte array like this:
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

For this (common) use case it would have been simpler to access the length attribute of the passed byte array inside the constructor. Why is the length parameter explicitly required for all constructors?

A: The precise answer to the question 'why' is simply 'because'. The spec says so, and note that DatagramPacket has been part of java since the very very beginning (well, after oak, I guess): The javadoc is tagged with @since 1.0.
All we can do is guess at what the original developer of this API was thinking.
So I'll try to do just that:

*

*This API predates the convention to offer both (dataStore) as well as (dataStore, offset, length) variants (and no other variants). In, say, the new String(byteArray, offset, length, charset) constructor, and just about everywhere else this kind of concept shows up, you have to pick between either passing the entire datastore, OR passing both offset and length; you can never pass solely length and have offset default to 0. But you can here; that's because this convention wasn't a thing yet.

*The reason that the notion 'pass an offset and a length' exists at all, not just here but with string's byte-array based constructor, with OutputStream's write method which comes in both write(byte[] data) as well as write(byte[] data, int offset, int length) variants, and many, many other places in the java core libraries, is because often you have a larger buffer than the amount of data you have. If you don't yet know how much data you want to send in your datagram packet, you could generate all the data into a self-growing structure, like a ByteArrayOutputStream or perhaps a StringBuilder or an ArrayList<Byte>, write out all the data, then extract a properly sized byte[] array from it. Or, and this is VASTLY more efficient, you make a byte array that is definitely large enough to store whatever you're going to make, optionally reuse this using ThreadLocal if you must, and once you're done, only NOW do you know how large it actually had to be. Instead of making another byte array that is properly sized and copying all bytes in, just.. send the first X bytes of the 'buffer array', save yourself the memory and the copy operation. There are also reasons for not wanting to start at 0 in the same vein. Which is why DatagramPacket also has a (byte[] buf, int offset, int length) constructor, and this also explains why the parameter name of the byte array is in fact buf (short for buffer, and note how it isn't the more obvious name data).

*ByteBuffer is a concept that is specifically designed to do this well. I'm not sure why there still isn't a constructor in DatagramPacket to work with these, but datagrampacket itself predates bytebuffers by a decade or more. Had bytebuffers been part of the language from 1.0, this would probably have been done with bytebuffers, which fully represent this notion of having a fixed size buffer and being very efficient with having code that works with potentially unknown lengths of data to write/read into it at precisely the right position and no further than some limit in order to avoid having to make byte arrays all over the place.


text:
Q: Use Typescript to describe a class with dynamically added properties I'm trying to add Typescript definitions to an existing codebase which happens to use the Knockout library. The code contains a very common pattern which looks like this:
interface SomeProperties {
    // A bunch of properties
}

class ViewModel {
    // Some properties of my own...

    constructor(data: SomeProperties) {
        AddAllPropertiesToThis(data);
    }
}

Where AddAllPropertiesToThis takes the data object and dynamically adds all of its properties to this.
I can't figure out how to express this pattern in Typescript. It makes sense to say something like
class ViewModel implements SomeProperties

but this requires manually copying all of the properties from the interface definition into the class.
Is there any way to accomplish what I need to do here without having to type out redundant properties?

A: You could introduce a member variable data: SomeProperties in ViewModel.
interface SomeProperties {
    // A bunch of properties
}

class ViewModel {
    data: SomeProperties;

    constructor(data: SomeProperties) {
        // deep copy the data
        this.data = { ...data };
    }
}

To me it makes more sense to do it by way of composition as the code above rather than inheritance. The ViewModel contains (has) SomeProperties. It is not an extension of SomeProperties ("is a" relationship).


text:
Q: System.ListException: List index out of bounds: 3  String  dateSplit = '2015/05/05'
 List<String> arr = new List<String>();
 arr = dateSplit.split('/');

 String tempDate = '';
 for(Integer i=arr.Size();i>=0;i--){
    if(tempDate == ''){
        tempDate = arr[i];
    }
    else{
        tempDate = tempDate + '/' + arr[i];
    }
 }
 Date depDate = Date.parse(tempDate);

A: akash,
is this code just for your learning ? why do you use hard coded dates and convert the format and parse it ?
Date.parse usually parses the string into date using user's locale date format.
so no point in changing the format to pass it to parse method.
now to the error you are getting,

*

*its becos you are starting the loop from arr.size() which is always 1
plus index of the last element stored in the array (since arrays starts
storing element from 0 index)

*so start your looping from arr.size()-1 and you should be good


text:
Q: Get rows from a jtable sorted with RowSorter Actually i am able to export as excel but it export the entire JTable not the sorted data with Rowsorter, i tried something like but nothing changed :
DefaultTableModel tableModel;
try {
    RowSorter<? extends TableModel> rowSorter = model.getjTable1().getRowSorter();
    TableModel tableModel = rowSorter.getModel();
} catch (NullPointerException ne) {
    tableModel = (DefaultTableModel) model.getjTable1().getModel();

}

A second important thing about my jtable, actually i can select only 1 row and i wont be able to change that.
My question, is, how can i only get the sorted rows from RowSorter ?
Do i need to sort programmatically ? Can i get the visible rows from my jtable ?

A:
but it export the entire JTable not the sorted data

The data in the TableModel does NOT change.
Only the data displayed in the JTable (the view) changes.
If you only want the data in the table then you only use methods of the JTable to access the data.
Something like:
for (int row = 0; row < table.getRowCount(); row++)
    for (int column = 0; column < tagle.getColumnCount(); column++)
        System.out.println( table.getValueAt(row, column);


text:
Q: VisualForce: Conditionally render HTML elements like
* I have a Force.com site portal written completely with custom Visualforce, HTML and CSS.
I have a component which is used to display the navigation links at the top of the page.
This navigation is built using  and
* tags which is pretty common.

Billing

Deposits

Checks

Now I want to be able to render these
* links based on the user's security as each of these links display information from different custom objects.
I know we can check a user's access to a record using something like:
{!$ObjectType.objectname.accessible}

So how can I achieve something like not displaying the
* link for deposits if the user has no access to the deposit custom object.

A: This is a bit off the cuff, but I think you can wrap it in a panel:
<apex:outputPanel rendered="{!$ObjectType.objectname.accessible}" layout="none"> </apex:outputPanel>

Would that work in your case?

A: One option would be to compose them server side, then display with <apex:dataList> or <apex:repeat>. Useful especially if the list will grow in future?
To do that build some wrapper apex class  (or even something as simple as Map<String, String>) that would hold the URL and display name. Anything you can do in VF with {!$ObjectType.Account.accessible} you can check with Account.sObjectType.getDescribe().isAccessible()

A: Off the cuff, I believe you can overload the use of the <apex:variable> tag along with its rendered attribute to show/hide individual elements.
<apex:variable var="foo" rendered="{!$ObjectType.objectname.accessible} >

 bar ...

</apex:variable>

A: If the VF level or Controller level is not an option (the two first things I would try) - then you could also potentially control it via jQuery.  Give the LI's you want to hide a specific class, and then tie it back to a function which checks if the user has the permission, and then shows the LI (instead of the other way around).


text:
Q: How to use GM_addStyle in Tampermonkey on #shadow-root (open)? There are extensions that make small on-page popups that in Inspection in Chrome show as #shadow-root(open).
I want to customise its styles with Tampermonkey, but using GM_addStyle(".class_name{zoom: 166%;}"); doesn't work. On native elements it works.

A: GM_addStyle() appends the <style> element it creates to the <head>, therefore it can't modify the styling of Shadow DOM elements. You need to use GM_addElement().
// ==UserScript==
// @name         Shadow DOM styling
// @version      0.1
// @author       double-beep
// @match        http*://example.com
// @grant        GM_addElement
// ==/UserScript==

(function() {
    'use strict';

    const shadowRoot = document.querySelector('element');
    const styles = `div { color: red; }`;

    GM_addElement(shadowRoot, 'style', { textContent: styles });
})();

If the styles aren't applied, you can create a <script> element instead in a similar way:
GM_addElement(shadowRoot, 'script', {
    textContent: 'shadowRootElement.shadowRoot.querySelector("...").style.color = "red";'
});

A: You need to insert the style tag into the shadow root.
(pinching some code from this answer)
function addStyleToShadowRoot(shadowRoot,css) {
    const style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = css;
    shadowRoot.appendChild(style);
}

Call it like this:
addStyleToShadowRoot(customElement.shadowRoot, myCss);


text:
Q: BibTeX error LaTeX Warning: There were undefined references I am using TexPad as editor and I do the latex, bibtex, latex, latex compilation. The weird thing is that I have two citations that show up and two that come as question marks, I am really puzzled about what the problem is and would appreciate help very much.
This is my tex code:
\documentclass{article}
\usepackage{plain}
\begin{document}

xx\cite{Yu}
\cite{doiX}
\cite{labinger}
\cite{ab}
\bibliography{references}
\bibliographystyle{plain}
\end{document}

and my .bib file:
@article{doiX,
   author = "He Hao and Ling-Yan Chen and Wai-Yeung  Wong and
             Wing-Hong  Chan and Albert W. M.  Lee",
   title  = "Practical Synthetic Approach to Chiral Sulfonimides (CSIs)
             Brnsted Acids for Organocatalysis",
}

@book{Yu,
   series = {Topics in current chemistry},
   volume = {292},
   publisher = {Springer},
   isbn = {978-3-642-12355-9},
   year = {2010},
   title = {C-H Activation},
   language = {eng},
   address = {Heidelberg},
   author = {Yu, Jin-Quan and Ackermann, xL},
   keywords = {ORGANISCHE SYNTHESE (CHEMIE): 547.057{,
}

@article{labinger,
   title  = {Understanding and exploiting C-H bond activation},
   author = {hallo},
   journal= {Nature},
   volume = {417},
   number = {6888},
   pages  = {507},
   year   = {2002},
   publisher={Nature Publishing Group}
}

@article{ab,
   author = "He Haond Ling-Yan Chen and Wai-Yeung  Wong and
             Wing-Hong  Chan and Albert W. M.  Lee",
   title  = "Practical Synthetic Approach to Chiral Sulfonimides
             (CSIs)  Brnsted Acids for Organocatalysis",
}

and this is what the output looks like:

The error in the log says:
LaTeX Warning: Citation `ab' on page 1 undefined on input line 8.

(./BiBTexTest.bbl) [1{/usr/local/texlive/2017/texmf-var/fonts/map/pdftex/updmap
/pdftex.map}] (./BiBTexTest.aux)

LaTeX Warning: There were undefined references.

A: When you ran BibTeX on the above bibliographic entries, you must have gotten a fatal-error message about the entry with key Yu, because that entry contains the following faulty keywords field:
keywords = {ORGANISCHE SYNTHESE (CHEMIE): 547.057{,

The second instance of { must surely be }. Once you make the called-for correction, the four entries can be compiled.
By the way, "can be compiled" does not imply that the contents of the bibliographic entries are correct. For instance, the entries with keys ab and doiX are missing the required journal and year fields. Moreover, the ab entry has the following, rather dubious, author field:
author = "He Haond Ling-Yan Chen and Wai-Yeung Wong ..."

This must surely be
author = "He, Hao and Ling-Yan Chen and Wai-Yeung Wong ..."

With Chinese names, be extra careful to identify what are the first or given name components and what are the last or family name components.
Next, Brnsted is incorrect; please change both instances of Brnsted to Br{\o}nsted. Incidentally, the author "hallo" [!!] in the labinger entry has got to be wrong.
And, I doubt that the Ackermann item in the author field of the Yu entry is correct. I think you should replace
author = {Yu, Jin-Quan and Ackermann, xL},

with
editor = {Yu, Jin-Quan and Shi, Zhangjie},

That book contains 12 chapters authored by various contributors. (One of the chapters, in fact, was co-authored by L. Ackermann and R. Vicente!) Are you really citing the entire book? Or did you mean to cite a specific chapter from that book? If so, you should be using an entry of type @incollection, so that you can provide information about the authors, the title of the chapter, and possibly the number of the chapter and the page range in addition to the editor and booktitle fields.
Finally, don't forget to encase certain uppercase-letter strings, such as CSIs, C-H and (yes!) Br{\o}nsted, in curly braces so that BibTeX doesn't convert them to all-lowercase.


text:
Q: В ubuntu глючит мышь xubuntu 11.10 voyager при прокрутке колесика на беспроводной мыши она отключается и перестает отвечать на какие-либо действия. Есть предложения - в каком направлении смотреть?p.s. На мышь не грешить, т.к. в семерке работает безупречно.На проводной нет возможности проверить - сломано колесо.
A: Мышь A4Tech ?С ними известные проблемы, попробуйте другую мышь.Если нет возможности, то напишите модель мыши сюда, я постараюсь вам помочь.

добавлено из комментариев
Попробуйте установить пакет xserver-xorg-input-evdev:
$ sudo apt-get install xserver-xorg-input-evdev

и перезапустить x-сервер (например, завершив x-сеанс).

A: Заменить драйвер мыши.
Обновление
К сожалению, не силен в УБУНТУ (чем-то он мне не понравился когда еще только линуксятничать начинал, давно это было и не помню чем именно), но думаю, что управление этим процессом должно быть где-то в управлении оборудованием, в частности, в openSUSE (которым пользуюсь я и очень этим доволен) это находится в центре управления YAST - Оборудование. Там можно выбрать тип используемой мыши (ну или подобрать более нормально работающий).

A: У меня был похожий глюк и оказалась проблема в драйверах для видеокарты. Пришлось поставить версию чуть по-старее и проблема решилась!


text:
Q: How to reduce numbers of AND used in this MySQL query? This is the query I am working on and somehow it takes to much time and eventually times out, which makes me think if I can reduce the number of AND in the WHERE Clause. I am new to this Huge Queries.
SELECT sfog.entity_id,
(
CASE
    WHEN sfog.status = 'delivered' THEN 'Order'
    WHEN sfog.status IN ('return','rtndelivered','closed') THEN 'Return Order'
    WHEN sfog.status = 'CanceledBS' THEN 'CanceledBS Order'
END) AS Type,

CONCAT(cev1.value,' ', cev2.value) AS 'Vendor Name',
sfog.status AS Status,
sfog.increment_id AS OrderNo ,
sfosh.created_at AS 'Invoice Date',
mo.tracking_number AS 'Tracking Number',
CONCAT(sfoa.firstname,' ', sfoa.lastname) AS 'Customer Name',
CONCAT(sfoa.street,' ',sfoa.city,' ',sfoa.region,' ',sfoa.postcode) AS 'Address',
sfoa.email AS 'Email',
group_concat( DISTINCT sfoi.sku SEPARATOR ', ') AS `Product Name`,
sfo.total_qty_ordered AS 'Qty',
SUM(ms.totalamountut) AS 'Order Value'
FROM sales_flat_order_grid sfog,
  sales_flat_order_status_history sfosh,
  customer_entity_varchar cev1,
  customer_entity_varchar cev2,
  marketplace_orders mo,
  sales_flat_order_address sfoa,
  sales_flat_order_item sfoi,
  sales_flat_order sfo,
  marketplace_saleslist ms
WHERE sfog.status IN ('delivered','return','rtndelivered','closed','CanceledBS')
 and sfosh.parent_id = sfog.entity_id
 and cev1.attribute_id = '5'
 and cev2.attribute_id = '7'
 and mo.seller_id = cev1.entity_id
 and mo.seller_id = cev2.entity_id
 and mo.order_id = sfog.entity_id
 and sfoa.parent_id = sfog.entity_id
 and sfoi.order_id = sfog.entity_id
 and sfo.entity_id = sfog.entity_id
 and ms.mageorderid = sfog.entity_id
GROUP BY sfog.entity_id;

A: Reducing the number of "and"s in the query has got very little to do with the query performance. If you had looked at some of the many questions posted here on improving query performance you would have noticed that those which are upvoted and answered include many featires missing from your post, like schemas and explain plans.
This is going to be a very heavy query to run - the only problem we can see is the number of tables. With 9 tables you will need at least 8 joining predicates. And that is what we see in your query mixed up with three filter predicates using literals. Its quite possible that some of those tables are redundant in this query, but we cannot determine that.
"Huge queries" are no different in their composition nor optimization than short, simple ones.

A: Join like this:
 FROM sales_flat_order_grid sfog
 JOIN sales_flat_order_status_history sfosh
   ON sfosh.parent_id = sfog.entity_id
 JOIN marketplace_orders mo
   ON mo.order_id = sfog.entity_id
 JOIN customer_entity_varchar cev1
   ON mo.seller_id = cev1.entity_id
 JOIN customer_entity_varchar cev2
   ON mo.seller_id = cev2.entity_id
 JOIN sales_flat_order_address sfoa
   ON sfoa.parent_id = sfog.entity_id
 JOIN sales_flat_order_item sfoi
   ON sfoi.order_id = sfog.entity_id
 JOIN sales_flat_order sfo
   ON sfo.entity_id = sfog.entity_id
 JOIN marketplace_saleslist ms
   ON ms.mageorderid = sfog.entity_id
WHERE sfog.status IN ('delivered','return','rtndelivered','closed','CanceledBS')
  AND cev1.attribute_id = '5'
  AND cev2.attribute_id = '7'
GROUP BY sfog.entity_id;

It makes your code way easier to read through


text:
Q: using IIS self signed cert, but form data is still plain text I'm pretty newbie in https and my project is MVC web application and i've created a self-signed certificate in IIS and set the website's binding to use that certificate and ssl settings to 'require SSL' and I can browse the website over https (although it's not verified and has red x on it).
The part that I don't understand is when I send a request to server (post request), I can still check the network console and see what was the parameter passed.

A:
I can still check the network console

I assume that you mean the information about the send and received data within the browser with "network console". Since the browser is creating and encrypting the data the browser has access to the clear text before encryption and after decryption and thus can show these information.


text:
Q: Combining two text views in single line I want to align text view as mentioned below in my android application
totally two lines
in first line one text view layout weight 2
in second line one text view layout weight 2
the third text view combining both lines and the layout weight 1 and text alignment center
anyone please help me to get fixed this in my android application
the xml layout
   <LinearLayout
        android:id="@+id/imageview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginStart="5dp"
        android:layout_marginEnd="5dp"
        android:layout_marginBottom="5dp"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:layout_marginStart="5dp"
            android:layout_marginEnd="5dp"
            android:orientation="vertical">

            <TextView
                android:id="@+id/itemName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:editable="false"
                android:importantForAutofill="no"
                android:padding="15dp"
                android:fontFamily="@font/bold"
                android:textSize="20sp"
                android:textColor="@color/black"
                android:textAlignment="center"
                tools:ignore="Deprecated,TouchTargetSizeCheck,DuplicateSpeakableTextCheck"
            />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginStart="5dp"
            android:layout_marginEnd="5dp"
            android:layout_marginBottom="5dp"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/eancode"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="2"
                android:textAlignment="center"
                tools:ignore="ContentDescription" />

            <TextView
                android:id="@+id/rate"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:importantForAutofill="no"
                android:selectAllOnFocus="true"
                android:padding="25dp"
                android:fontFamily="@font/bold"
                android:textSize="40sp"
                android:textAlignment="center"
                android:textColor="@color/black"
                tools:ignore="Deprecated,TouchTargetSizeCheck,SpeakableTextPresentCheck" />
        </LinearLayout>
        </LinearLayout>

thank you


text:
Q: Data Extract vs Query Activity Can I ask what's the difference between a Data Extract Activity vs Query Activity?
I've created some Queries and realized that some information (like OS and Platform) was not available in Query Activity.
Edit: I am trying to extract ALL jobs sent with MC and currently I am getting the data from Data Extract Activity with the Click and SendJobs file.
I would like to customise the column of the output file and join them together into 1 file instead of having to download both the Click and SendJobs.
Hence I was exploring the Query function.
Thanks.

A: A Query Activity is for selecting rows from a Data Extension or System Data View and writing them to another Data Extension.
A Data Extract Activity is for extracting data out of the Marketing Cloud.
The syntax for SFMC Query Activities is closely related to Microsoft's Transact-SQL (aka T-SQL).


text:
Q: Verb-ing (present participle) + noun Can verb-ing + noun mean something which is done?
For example, "drinking water."
"Drinking water" means water which is drunk, not water which drinks something.

A: Yes, this is possible.
The "verb+ing" forms a participle, which modifies the noun.  The interpretation of that participle is determined by idiom.  In the case of water, the participle describes the function or purpose of the water: it to be drunk.
This is not always the case!  A "washing machine" is not to be washed, it is for washing clothes.
How do you know the difference?  Idiom, experience and common sense.  "Water" cannot drink, so "drinking water" can't be "water that drinks something". A machine can be washed, but that is not a use of a machine, so "washing machine must mean a machine that does washing.
As these are idioms they have to be learnt.  You can try making your own, but you can't be sure that they will be idiomatic.


text:
Q: local php code works wrong in php based theme in wordpress I'm super new with php/wordpress (first day today) and I trying to deploy application on my local machine (Windows 7/ 64bit's if that's matter). SO I get the sources - which is like a theme, deploy wordpress locally with xampp, and put my source folder to wp-content/themes
So now it works, but work's wrong. Some element's like header menu do not render, some text missed. And when I trying to do some navigation like localsite/register it realod the same page, but make page title "page not found", but register.php in the folder. This is work the same for any other pages except login. When hit localsite/login it redirect's me to wp-login.php
I do not need to change it somehow, just make local version looks and works the same as live. Does anyone have an idea why could that be and what should I do to fix it?

A: Probably your pages do not executes because you do not create it like pages in CMS. That's also the reason why local version could looks different from the server one.
So you need to login to remote server admin panel and replicate all stuff from live server with the same way on your local server. I mean add pages, articles, configure menus, widgets, etc. And then your local version will be look and feel the same.


text:
Q: Issue while generating Signed APK Facing AAPT2 error: check logs for details issue while generating Signed APK. Normally when taking build it give successful apk, while generating Signed APk it blocks.

And the error file is placed below for further information

A: Since the logs are not posted. I believe one of the reasons for the build failure is due to some PNG files are corrupted and were not parsed. Sometimes the images have an extension but are not real PNG.
You can check if the images in your project are real PNGs with the below command :
find . -type f -name "*.png" | xargs -L 1 -I{} file  -I {} | grep -v 'image/png; charset=binary$'

After getting the list I used this site to convert them to PNG. I was then able to generate a signed apk.


text:
Q: Is the md5 function safe to use for merging datasets? We are about to promote a piece of code which uses the SAS md5() hash function to efficiently track changes in a large dataset.
format md5 $hex32.;
md5=md5(cats(of _all_));

As per the documentation:

The MD5 function converts a string, based on the MD5 algorithm, into a 128-bit hash value. This hash value is referred to as a message digest (digital signature), which is nearly unique for each string that is passed to the function.

At approximately what stage does 'nearly unique' begin to pose a data integrity risk (if at all)?

A: I have seen an example where the md5 comparison goes wrong.
If you have the values "AB" and "CD" in the (two columns of the) first row and "ABC" and "D" in the second row, they got the same md5 value. See this example:
data md5;
  attrib a b length=$3 informat=$3.;
  infile datalines;
  input a b;
  format md5 $hex32.;
  md5=md5(cats(of _all_));
datalines;
AB CD
A BCD
;run;

This is, of course, because the CATS(of _all_) will concatinate and strip the variables (converting numbers to string using the "best" format), without a delimiter. If you use CAT instead , this will not happen because the leading and trailing blanks are not removed. This error is not very far fetched. If you have missing values, then this could occur more often. If, for example, you have a lot of binary values in text variables, some of which are missing, it could occur very often.
One could do this manually, adding a delimiter in between the values. Of course, you would still have the case when you have ("AB!" and "CD") and ("AB" and "!CD") and you use "!" as delimiter...

A: MD5 has 2^128 distinct values, and from what I've read at 2^64 different values (that's 10^20 or so) you begin to have a high likelihood of finding a collision.
However, as a result of how MD5 is generated, you have some risks of collisions from very similar preimages which only differ in as little as two bytes.  As such, it's hard to say how risky this would be for your particular process.  It's certainly possible for a collision to occur on as few as two messages.  It's not likely.  Does saving [some] computing time benefit you enough to outweigh a small risk?