text:
Q: How does one transfer JSON to/from an iOS app, securely? Is there a standard protocol that is commonly followed? Or is this an area that varies greatly? How do most good iOS apps already do this in a way that prevents unintended uses or hacking?

A: To prevent someone from using your web service you must have some sort of password scheme, or the party on the other end must have "credentials" (ie, a fancy password) that you recognize.

A: Use a high level API (NSURLConnection API) connecting to a SSL driven web server for which you ensure the secure urls that return JSON require authentication and authorization.


text:
Q: What is the difference between onclick(function(){}) and on('click',function(){}) function in jquery I am trying to load pages in one div using ajax :
this is my HTML code :

Tab1

Tab2

Tab3

When i am calling the pages in one div that is 'home' div like this :
$(document).ready(function(){

     $("#m_blink").onclick(function() {
        $("#home").load("tab1.php",{},function(){});
     });

     $("#d_blink").onclick(function() {
        $("#home").load("tab2.php",{},function(){});
     });

     $("#k_blink").onclick(function() {
        $("#home").load("tab3.php",{},function(){});
     });
});

In chrome and Firefox when i inspect element the error is :
In chrome :
'Uncaught TypeError: undefined is not a function'
and in firefox :
[12:15:46.575] TypeError: $(...).onclick is not a function
and when i changed my jquery code to like this
$(document).ready(function(){

     $("#m_blink").on('click', function() {
        $("#home").load("tab1.php",{},function(){});
     });

     $("#d_blink").on('click',function() {
        $("#home").load("tab2.php",{},function(){});
     });

     $("#k_blink").on('click',function() {
        $("#home").load("tab3.php",{},function(){});
     });
});

When i execute this code this is working , what is the difference between the onclick functions in jquery.

A: There is no onclick function in jquery. So the error is correct and self-explanatory.
TypeError: $(...).onclick is not a function

You should use .click(), which is a shortcut for .on("click", handler)
$(selector).click(function() {
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sort an array with numerical values: the good way First, let me give some context: I teach a first course in numerics for students who major in biology and mathematics. In this course, I try to give the students good habits for manipulating array of numbers, such as using the ndarray data structure of NumPy.
I am aware of the fact that no for loop should be used over a ndarray. I want to illustrate this statement with a standard sorting algorithm. Of course I know how to code this naively, and this is not what I want to do here.
I don't know how to do it with all the machinery of NumPy, but I thought I could search by myself. I found the reference page for the sort function in NumPy, which has the following signature
numpy.sort(a, axis=-1, kind='quicksort', order=None)

This page links to the source code of the function, which is useful. But then I'm lost! I don't understand where the magic happens in the following lines:
if axis is None:
    a = asanyarray(a).flatten()
    axis = 0
else:
    a = asanyarray(a).copy(order="K")
a.sort(axis=axis, kind=kind, order=order)
return a

So my question is: what does this piece of code do?


text:
Q: C# Не вставляются данные в Excel файл при запуске oledbcommand.ExecuteNonQuery() Столкнулся с проблемой, которую не получается самостоятельно решить (или найти решение в интернете).
Задача: выгрузить данные из Oracle таблицы в Excel.
Для решения проблемы написал код, который успешно выгружал данные из Oracle процедуры, возвращающей курсор.
Но при попытке увеличить возвращаемый курсором объем данных (порядка 20 колонок и 90 000 строк), данные перестали выгружаться. Пробовал выгружать по 10 000 строк и сохранять данные, но после приблизительно 30 000 данные не грузятся.
При этом, процесс не останавливается, счетчик внутри цикла бежит, и ExecuteNonQuery() регулярно возвращает 10 000 вставленных строк, но при открытии Excel файла, в нем оказывается только, как правило, порядка 30 000 строк.
В текстовый файл в блоке catch не заносятся ошибки. Может быть, подскажете, как можно попытаться отловить ошибки?
Cтроки соединения не привожу, они заданы корректно, так как скрипт отрабатывает на небольших объемах данных.
Возможно, кто-либо сталкивался с такой проблемой? У меня найти похожие статьи не получилось. Буду рад любой помощи!
public static void Main()
{
    string datetime = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");
    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
    try
    {
        OleDbConnection Excel_OLE_Con = new OleDbConnection();
        OleDbCommand Excel_OLE_Cmd = new OleDbCommand();

        string qwe_constr = "connection string";
        OracleConnection myADONETConnection = new OracleConnection(qwe_constr);

        string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + "E:\\qaz\\15.07.2016\\qwe" +
                            ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";

        File.Delete("E:\\qaz\\15.07.2016\\qwe.xlsx");

        //fill datatable with data for insert
        myADONETConnection.Open();
        OracleCommand cmd_proc = new OracleCommand();
        cmd_proc.Connection = myADONETConnection;
        cmd_proc.CommandType = System.Data.CommandType.StoredProcedure;
        cmd_proc.CommandText = "procedure_name";
        cmd_proc.Parameters.Add("p_show_del", OracleDbType.Int16).Value = 0;
        cmd_proc.Parameters.Add("p_type", OracleDbType.Varchar2, 3).Value = "INV";
        cmd_proc.Parameters.Add("p_errno", OracleDbType.Int16).Value = 157;
        cmd_proc.Parameters.Add("outcur", OracleDbType.RefCursor).Direction = ParameterDirection.Output;

        DataTable dt_with_data = new DataTable();
        dt_with_data.Load(cmd_proc.ExecuteReader());
        myADONETConnection.Close();

        //string with column headers
        string TableColumns = "";
        foreach (DataColumn column in dt_with_data.Columns)
        {
            TableColumns += column + "],[";
        }

        // Replace most right comma from Columnlist
        TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
        TableColumns = TableColumns.Remove(TableColumns.Length - 2);

        //Use OLE DB Connection and Create Excel Sheet
        Excel_OLE_Con.ConnectionString = connstring;
        Excel_OLE_Con.Open();
        Excel_OLE_Cmd.Connection = Excel_OLE_Con;
        Excel_OLE_Cmd.CommandText = "Create table [sheet1] (" + TableColumns + ")";
        Excel_OLE_Cmd.ExecuteNonQuery();
        Excel_OLE_Con.Close();

        //Write Data to Excel Sheet from DataTable dynamically
        //string with command
        Excel_OLE_Con.Open();
        String sqlCommandInsert = "";
        String sqlCommandValue = "";
        foreach (DataColumn dataColumn in dt_with_data.Columns)
        {
            sqlCommandValue += dataColumn + "],[";
        }

        sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
        sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
        sqlCommandInsert = "INSERT into [sheet1] (" + sqlCommandValue + ") VALUES(";

        int columnCount = dt_with_data.Columns.Count;

        int i_qaz = 0;
        foreach (DataRow row in dt_with_data.Rows)
        {
            i_qaz++;
            Console.WriteLine(i_qaz.ToString());
            string columnvalues = "";
            for (int i = 0; i < columnCount; i++)
            {
                int index = dt_with_data.Rows.IndexOf(row);
                columnvalues += "'" + dt_with_data.Rows[index].ItemArray[i].ToString().Replace("'", "''") + "',";
            }
            columnvalues = columnvalues.TrimEnd(',');
            var command = sqlCommandInsert + columnvalues + ")";
            Excel_OLE_Cmd.CommandText = command;
            Excel_OLE_Cmd.ExecuteNonQuery();
        }
    }
    catch (Exception exception)
    {
        // Create Log File for Errors
        using (StreamWriter sw = File.CreateText("E:\\qaz\\15.07.2016\\qwe_" + datetime + ".log"))
        {
            sw.WriteLine(exception.ToString());
        }

    }
}

PS: Этот вопрос по-английски.

A: А попробуй использовать либу из даной темы:
Как просто работать с / открыть / изменить / сохранить Excel / CSV файлы
Проверял даный код на очень больших файлах: 16 х 64000 ячеек. Проблем замечено не было.


text:
Q: What is a CA21A cable? What does CA stand for?
Why is it numbered 21?
Who standardized it?
The abbreviation is used by Cisco for a cable called RJ-21X/CA21A that is used to connect an RJ-21 port on a voice gateway to a patch panel for analog phones. Since there are many other cables such as CA2DA, CA2EA, CA2FA, CA2GA, CA2HA, CA26A, CA27A, I assume that there's a standard.

A: CA stands for Console and Auxiliary
21 is for Registered Jack 21 (RJ21)
From Wikipedia:

Registration interfaces were created by the Bell System under a 1976
  Federal Communications Commission order for the standard
  interconnection between telephone company equipment and customer
  premises equipment. These interfaces used newly standardized jacks and
  plugs, primarily based on miniature modular connectors.

A: There is no RJ21X/CA21A cable.
But there are cables that have a CA21A connector. CA21A is a name used for RJ21X in Canada. There is a set of designations that correspond to Registered Jacks. For example, CA45A corresponds to RJ45S, CA11A corresponds to RJ11C.
Who standardized it? I cannot tell who originally standardized it. However, there is a list of the Certification and Engineering Bureau in Canada at ic.gc.ca and here's a backup at web.archive.org.
What is it used for? The CA21A (RJ-21X) end of a cable terminates multiple two-wire copper lines for analog telephony or DSL over POTS.


text:
Q: Facebook Open Authentication using Node JS and Angular JS I am new to node and angular programming. I am trying out open authentication using node and angular js. The browser console throws the following error -
XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?response_type=code&redirect_uri=http%…%3A3000%2Fauth%2Ffacebook%2Fcallback&scope=email&client_id=. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
I have used passport-facebook and passport module for open authentication.
Below is the code:
server.js
var auth = require('./app/routes/auth');

passport.serializeUser(function(user, done) {
    done(null, user.id);
});

// used to deserialize the user
passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
        done(err, user);
    });
});
app.use('/auth', auth);

app/routes/auth.js
var express = require('express'),
  passport = require('passport'),
  router = express.Router(),
  mongoDB = require('mongoDB').MongoClient,
  GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

require('../configs/passport')(passport, mongoDB);

router.post('/login',
  passport.authenticate('local', {
    successRedirect: '/profile',
    failureRedirect: '/user/loginFailure'
  })
);

router.get('/facebook', passport.authenticate('facebook', { scope : 'email' }));

    // handle the callback after facebook has authenticated the user
router.get('/facebook/callback',
    passport.authenticate('facebook',
    {
        successRedirect : '/profile',
        failureRedirect : '/'
      }
));

router.get('/loginFailure', function(req, res){
  res.send("Login Failed..");
});

module.exports = router;

var FacebookStrategy = require('passport-facebook').Strategy;
var fbConfig = require("./facebook.json");

module.exports = function(passport){

   passport.use(new FacebookStrategy({
        clientID        : fbConfig.appID,
        clientSecret    : fbConfig.appSecret,
        callbackURL     : fbConfig.callbackURL

    },
    function(token, refreshToken, profile, done) {
        process.nextTick(function() {
                    var newUser = {};
                    newUser.facebook.id    = profile.id;
                    newUser.facebook.token = token;
                    newUser.facebook.name  = profile.name.givenName + ' ' + profile.name.familyName;
                    newUser.facebook.email = profile.emails[0].value;
                        return done(null, newUser);

            });
    }));
};

angular controller. handles click event for Facebook login button.
app.controller("authCtrl",["$scope", '$resource', function($scope, $resource){
    $scope.userid = "";
    $scope.password = "";

    $scope.authenticate = function(type){
        if(type === 'local'){
            var login = $resource('http://localhost:3000/auth/login');
            login.save({username: $scope.userid, password: $scope.password });
        }
        else if(type === 'facebook'){
            var login = $resource('http://localhost:3000/auth/facebook');
            login.get();
        }
    }
}])

Please help in fixing this error.

A: The Facebook auth strategy requires that the user be signed into Facebook and has allowed your "app" permission to access your Facebook account information. This cannot be done with an XHR because how would the user enter their Facebook credentials to log into Facebook if the user wasn't already signed in? How would the user approve the permissions your Facebook "app" is requesting if the request is sent via XHR?
This applies to all of the Passport strategies that utilize OAuth or OpenID. The user's browser has to go directly to the auth provider's site so that they can either A) login to the auth provider or B) approve the permissions you're requesting in your application. Once the user has done that the auth provider (in your case Facebook) will then redirect the user's browser back to your application's endpoint with some kind of token which your application will then use to request information from the auth provider (such as email address, full name, etc.)

A: Did you register your application with Facebook as a valid client? If so please make sure your redirect uri is registered as a valid redirect uri with FB.


text:
Q: Wordpress woocommerce - hide other shipping method when flat rate available It's easy to find how to hide other shipping methods when free shipping is available. But I would like to hide other shipping methods when flat rate is available (I have custom other methods).
Can you help please ?
regards

A: The code below is modified from this article :
add_filter('woocommerce_package_rates', 'xa_hide_shipping_rates_when_flat_rate_is_available', 10, 2);
function xa_hide_shipping_rates_when_flat_rate_is_available($rates, $package) {
    global $woocommerce;
    $version = "2.6";
    if (version_compare($woocommerce->version, $version, ">=")) {
        foreach($rates as $key => $value) {
            $key_part = explode(":", $key);
            $method_title = $key_part[0];
            if ('flat_rate' == $method_title) {
                $flat_rate_shipping = $rates[$key];
                // Unset all rates.
                $rates = array();
                // Restore flat rate shipping rate.
                $rates[$key] = $flat_rate_shipping;
                return $rates;
            }
        }
    }
    else {
        if (isset($rates['flat_rate'])) {
            // Below code is for unsetting single shipping method/option.
            $flat_rate = $rates['flat_rate'];
            // Unset all rates.
            $rates = array();
            // Restore flat rate shipping rate.
            $rates['flat_rate'] = $flat_rate;
        }
    }

    return $rates;
}

I am not sure which WooCommerce version you are using but I have tested for version 2.6 but not the versions before it.


text:
Q: Compile if condition from String Variable in javascript I have a variable
var condition = "if(2 > 5)";

And sometime it will be
var condition = "if(3>5 && 4<2){quantity = 45;} else quantity=60;";

How I can compile these conditions, as these are in string variable?

A: It's dangerous to use because it can allow most anything to be injected into your code, but eval is the right thing to use here, if you really do have to have string evaluated to code.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
eval(condition)


text:
Q: How many functions satisfy the following properties? How many functions $f:\{a,b,c,d,e\} \rightarrow \{1,2,3,4,5\}$ satisfy the following two properties:
$f(a)+f(b)+f(c) = 8$
$f(d)+f(e) = 6$
Using the stars-and-bars method of sorting, I was able to identify that there are 8 "ones" that need to be sorted in the first equation, and 6 in the second. The first has 3 categories (a,b,c) and the second has 2.
Because $f(a)$, $f(b)$, $f(c)$ must each be at least $1$, we know that we have 5 remaining "ones" to sort out. We can solve this problem (5 remaining ones, 2 different categories, 3 already distributed ones) using $\binom{7}{2}$.
We can apply this same strategy for the second property, to get $\binom{5}{1}$. If we multiply these, we get $105$ different functions that satisfy these properties.
I am concerned that some of these $105$ are not actually viable since there must be some combination of function that overlaps the available numbers, i.e., some kind of intersection that needs to be subtracted? How would one go about doing this?

A: The set $ \{a,b,c \}$ can be mapped onto the sets $\{1,2,5\},\{1,3,4\},\{2,2,4\},\{2,3,3\}$ in respectively $6,6,3,3$ ways. ($18$ in total).
The set $\{d,e\}$ can be mapped onto the sets $\{1,5\},\{2,4\},\{3,3\}$ in respectively $2,2,1$ ways. ($5$ in total).
So there are $18 \times 5= \color{red}{90}$ possible functions.


text: Q: Detecting highlightable text over an app in Android? Is there a way I can make a popup or notification in Android that can detect text over any app. I want to be able to detect readable text (not images) using a popup or external background app over the entire phone screen.


text:
Q: WPF Control is not tracking the mouse movement on click and drag Sorry if this is a poor question, but I'm trying to get a click and drag effect on a control where the control will follow the users mouse movement as long as the left mouse button is pressed. I followed this tutorial first to get basic click and drag functionality https://msdn.microsoft.com/en-us/library/hh144799(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-7
I modified the code a bit to try and get the control to follow.
Circle.xaml
<UserControl x:Class="DragDropExample.Circle"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:DragDropExample"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300"
         AllowDrop="True">
    <UserControl.Resources>
        <Storyboard x:Key="TestStoryboard">
            <DoubleAnimation Storyboard.TargetProperty="RenderTransform.(TranslateTransform.X)" To="0"/>
            <DoubleAnimation Storyboard.TargetProperty="Opacity" From="0" To="1"/>
        </Storyboard>
    </UserControl.Resources>
    <Canvas x:Name="canv">
        <Ellipse x:Name="circleUI" Height="100" Width="100" Fill="Blue"/>
    </Canvas>
</UserControl>

Circle.xaml.cs
namespace DragDropExample
{
public partial class Circle : UserControl
{
    private Brush _previousFill = null;
    private bool _isDragging;

    public Circle()
    {
        InitializeComponent();
    }

    public Circle(Circle c)
    {
        InitializeComponent();
        this.circleUI.Height = c.circleUI.Height;
        this.circleUI.Width = c.circleUI.Height;
        this.circleUI.Fill = c.circleUI.Fill;
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        base.OnMouseMove(e);

        if (e.LeftButton == MouseButtonState.Pressed)
        {
            DataObject data = new DataObject();
            data.SetData(DataFormats.StringFormat, circleUI.Fill.ToString());
            data.SetData("Double", circleUI.Height);
            data.SetData("Object", this);

            Point position = e.GetPosition(this);
            double x = position.X;
            double y = position.Y;

            Canvas.SetLeft(circleUI, x);
            Canvas.SetTop(circleUI, y);

            DragDrop.DoDragDrop(this, data, DragDropEffects.Copy | DragDropEffects.Move);
        }
    }

    protected override void OnGiveFeedback(GiveFeedbackEventArgs e)
    {
        base.OnGiveFeedback(e);

        if (e.Effects.HasFlag(DragDropEffects.Copy))
        {
            Mouse.SetCursor(Cursors.Cross);
        }
        else if (e.Effects.HasFlag(DragDropEffects.Move))
        {
            Mouse.SetCursor(Cursors.Pen);
        }
        else
        {
            Mouse.SetCursor(Cursors.No);
        }

        e.Handled = true;
    }

    protected override void OnDrop(DragEventArgs e)
    {
        base.OnDrop(e);

        if (e.Data.GetDataPresent(DataFormats.StringFormat))
        {
            string dataString = (string) e.Data.GetData(DataFormats.StringFormat);

            BrushConverter converter = new BrushConverter();
            if (converter.IsValid(dataString))
            {
                Brush newFill = (Brush) converter.ConvertFromString(dataString);
                circleUI.Fill = newFill;

                if (e.KeyStates.HasFlag(DragDropKeyStates.ControlKey))
                {
                    e.Effects = DragDropEffects.Copy;
                }
                else
                {
                    e.Effects = DragDropEffects.Move;
                }
            }
        }
        e.Handled = true;
    }

    protected override void OnDragOver(DragEventArgs e)
    {
        base.OnDragOver(e);
        e.Effects = DragDropEffects.None;

        if (e.Data.GetDataPresent(DataFormats.StringFormat))
        {
            string dataString = (string) e.Data.GetData(DataFormats.StringFormat);

            BrushConverter converter = new BrushConverter();
            if (converter.IsValid(dataString))
            {
                if (e.KeyStates.HasFlag(DragDropKeyStates.ControlKey))
                {
                    e.Effects = DragDropEffects.Copy;
                }
                else
                {
                    e.Effects = DragDropEffects.Move;
                }
            }
        }
        e.Handled = true;
    }

    protected override void OnDragEnter(DragEventArgs e)
    {
        base.OnDragEnter(e);
        _previousFill = circleUI.Fill;

        if (e.Data.GetDataPresent(DataFormats.StringFormat))
        {
            string dataString = (string) e.Data.GetData(DataFormats.StringFormat);

            BrushConverter converter = new BrushConverter();
            if (converter.IsValid(dataString))
            {
                Brush newFill = (Brush) converter.ConvertFromString(dataString);
                circleUI.Fill = newFill;
            }
        }
    }

    protected override void OnDragLeave(DragEventArgs e)
    {
        base.OnDragLeave(e);
        circleUI.Fill = _previousFill;
    }
}
}

MainWindow.xaml
<Window x:Class="DragDropExample.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:DragDropExample"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Canvas>

    <StackPanel
                Background="Beige"
                AllowDrop="True"
                DragOver="panel_DragOver"
                Drop="panel_Drop" Height="319" Width="517">
        <TextBox Width="Auto" Margin="2,2,413,2" Text="green"/>

        <local:Circle Margin="2"/>
        <!--<local:Circle Margin="2"/>-->

    </StackPanel>
</Canvas>
</Window>

MainWindow.xaml.cs
private void panel_DragOver(object Sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent("Object"))
        {
            if (e.KeyStates == DragDropKeyStates.ControlKey)
            {
                e.Effects = DragDropEffects.Copy;
            }
            else
            {
                e.Effects = DragDropEffects.Move;
            }
        }
    }

    private void panel_Drop(object sender, DragEventArgs e)
    {
        if (e.Handled == false)
        {
            Panel _panel = (Panel) sender;
            UIElement _element = (UIElement) e.Data.GetData("Object");

            if (_panel != null && _element != null)
            {
                Panel _parent = (Panel) VisualTreeHelper.GetParent(_element);

                if (e.KeyStates == DragDropKeyStates.ControlKey && e.AllowedEffects.HasFlag(DragDropEffects.Copy))
                {
                    Circle _circle = new Circle((Circle)_element);
                    _panel.Children.Add(_circle);
                    e.Effects = DragDropEffects.Copy;
                }
                else if (e.AllowedEffects.HasFlag(DragDropEffects.Move))
                {
                    _parent.Children.Remove(_element);
                    _panel.Children.Add(_element);
                    e.Effects = DragDropEffects.Move;
                }
            }
        }
    }
}
}

It's really pretty simple code, and when I click on the circle and move the mouse with the left mouse button pressed it jumps across the screen to the right and down. I'm wondering if I should use a storyboard or Transformation of some sort on the circle to get it to move. I'm sure it's just something simple I'm missing, but it's escaping me right now. I would greatly appreciate any advice.


text:
Q: Group by, convert to factor and extract levels as integers issue R? I have 2 dataframes with same columns (vars) and 2 different user id's:
df1:
structure(list(user_id = c(1, 1, 1, 1, 1, 1), obs_id = c("717b1913-0c0f-4963-8bc9-81a06a3bb1c0",
"717b1913-0c0f-4963-8bc9-81a06a3bb1c0", "717b1913-0c0f-4963-8bc9-81a06a3bb1c0",
"717b1913-0c0f-4963-8bc9-81a06a3bb1c0", "717b1913-0c0f-4963-8bc9-81a06a3bb1c0",
"717b1913-0c0f-4963-8bc9-81a06a3bb1c0"), timestamp = c(337837075445301,
337837075445301, 337837077455301, 337837077455301, 337837079457301,
337837079457301), acc_x = c(0.5363176, 0.5363176, 0.5243462,
0.5243462, 0.5243462, 0.5243462), acc_y = c(6.4693303, 6.4693303,
6.4693303, 6.4693303, 6.4693303, 6.4693303), acc_z = c(6.8093176,
6.8093176, 6.821289, 6.821289, 6.821289, 6.821289)), .Names = c("user_id",
"obs_id", "timestamp", "acc_x", "acc_y", "acc_z"), row.names = c(NA,
6L), class = "data.frame")

and df2:
structure(list(user_id = c(2, 2, 2, 2, 2, 2), obs_id = c("8027eac3-8839-498e-98b9-3b46da98d1f4",
"8027eac3-8839-498e-98b9-3b46da98d1f4", "8027eac3-8839-498e-98b9-3b46da98d1f4",
"8027eac3-8839-498e-98b9-3b46da98d1f4", "8027eac3-8839-498e-98b9-3b46da98d1f4",
"8027eac3-8839-498e-98b9-3b46da98d1f4"), timestamp = c(336965414272993,
336965414272993, 336965414272993, 336965416627384, 336965418627300,
336965420627376), acc_x = c(-1, -1, -1, 0.81644773, 0.80208206,
0.8140534), acc_y = c(-1, -1, -1, 6.648901, 6.646507, 6.651295
), acc_z = c(-1, -1, -1, 7.2618356, 7.257047, 7.233104)), .Names = c("user_id",
"obs_id", "timestamp", "acc_x", "acc_y", "acc_z"), row.names = c(NA,
6L), class = "data.frame")

Now I want to bind them, group by user_id turn obs_id to factor and extract the levels out of it to be an integers column:
bind_rows(df1,df2) %>%
  group_by(user_id) %>%
  mutate(obs_id = as_factor(obs_id),
         replicate = as.numeric(levels(obs_id)))

returns an error:

Error in mutate_impl(.data, dots) : Column replicate must be length
  6 (the group size) or one, not 0

Please advise what I am doing wrong here?
I want obs_id column to be turned to factor column, take the levels and "encode" it to be integer and instead the long string you may observe in obs_id.

A: After binding the datasets, convert the 'obs_id' to factor, then do the group_by as there is a conflict when we convert to factor within the group_by as the levels can be different.  An easier option would be to match the 'obs_id' with unique elements of 'obs_id'
bind_rows(df1, df2) %>%
  group_by(user_id) %>%
  mutate(Rep = match(obs_id, unique(obs_id)))

The issue is in storing a factor column in each 'user_id' having different levels.  If the objective is to get the 'Rep' column, we don't need a factor intermediate column
bind_rows(df1, df2) %>%
     group_by(user_id) %>%
     mutate(Rep = as.integer(factor(obs_id)))


text:
Q: Is there a Ruby on Rails layouts/css archive? Does anybody know a place with a bunch of Ruby On Rails Layouts/CSS combinations? I am starting new applications and would like to give them different look, but I am not a designer, so I would love to use someone's else free layouts/css for starters.

A: There's nothing special about CSS for Ruby on Rails and layouts tend to be so application specific that you're unlikely to see much advantage in reuse across different applications.  However, there are some tools that might help for the non-designer programmer.
Some people like haml and sass as an alternative to erb templates.  Personally, I prefer to stick to erb than learn a different template markup language.
Blueprint CSS is an excellent grid-based CSS/layout starter kit.  I use it for many sites these days.  There are other "CSS frameworks" that you might want to investigate.
And honestly, you can take any free design template and modify it for Ruby on Rails if you can find something you like and fits the layout of your application.
Good luck.

A: Maybe you can use a widget plugin. This plugin helps you to build Tabnav, navigations menu, progression bar and so on...
Have a look at this presentation:
http://www.slideshare.net/paolo.dona/rails-widgets-by-paolo-dona-at-railstoitaly?src=embed
and this is the official plog page:
http://blog.seesaw.it/

A: I stumbled onto this question while searching for this type Rails css archive.  It CAN be done, and I think it should be.
It would be awesome if there was a site for sharing css layouts specifically for styling Rails sites.  The layouts could style form fields, set a color scheme, set fonts, styles, baseline grids -- all this stuff is not application specific.  Some layouts might even offer different commonly used UI configurations (Basecamp-style top nav, sidebars, etc) that could be easily used form the application.
It would be even better if there was a place for SASS layouts, since they could offer mixins without littering the main css files with stuff until it's used.  It would also be cool if there were also Formtastic form style sheets.
Anyone else think a site like this should exist?  How would you like it to work?
If you want to start a site like this together, drop me a message.

A: Several people here are saying that there is nothing specific about Rails templates, and that is correct.  What people, and I am guessing the questioner, refer to is the look and feel that many if not most of Rails apps have.  This may have grown out of imitating 37 signal designs, and their emphasis on simplicity without looking cheap as expressed in this http://37signals.com/design
So, if anybody has links to such designs/templates, please provide the links.

A: Check out Twitter Bootstrap a html/css/javascript framework fro web apps.

A: You should definitely take a look at yaml It is a CSS framework with default settings for all HTML elements. (remember to include default_content.css) The good thing about yaml is that you don't need to hack your CSS/HTML to death to make it look good in all browsers. Yaml has all the hacks and tweaks included. Use the yaml builder to set up your columns etc.
Best regards.
Asbjørn Morell.

A: It's not exactly what you're asking for, but the ActiveScaffold plugin provides a fair amount of pre-fab look and behavior. It's useful if you want to throw up something quickly that you feel comfortable showing to people before the actual styling gets done by a designer (or by you at a later stage of development).

A: There are plenty of free templates sites, or open source designs, but they are usually not designed for applications (there are a few but they'll often need customisation)
to start up with new projects, I love to use templates form themeforest http://themeforest.net/  usually around 10-20$ so it's not free, but it's yours, no need to leave copyrights notice.
the templates on themeforest almost always include fancy jQuery animations, they can be removed if you prefer prototype.
Helpers like paolo donna's widgets will help, but you really need some basic knowledge of HTML and CSS to get results, I think the hard part is to create from scratch, but once you understand basic formatting and document structure it ain't that hard.
anyway you really need to understand html and css to use javascript (ajax, effects, behaviors..)

A: Streamlined Rails plugin is another way of easing user interface generation.
Screenshots and description of the plugin can be found at Rails Inside and in the 'Java Kicks Ruby In The What Now' article

A: If you are have a Rails 3 app and are looking for pre-made layouts or themes for your app, check out http://railsthemes.com. There are a bunch of templates for purchase, and as of yesterday, some free themes as well. (Full disclosure: I am part of the team working on RailsThemes.)

A: CSS is easy.  Just find a site you like and download its css files.  To figure out what elements on the page correspond to which css classes use firebug's inspect feature.
Another thing you can do is find an open source rails app you like and look at there views and css.

A: The question isn't a good question. Ruby on Rails is a programming framework. You can create a variety of different types of applications on it. You can create a craigslist type app, an ebay-like app, a shopping cart system like amazon.com or even a search engine like Google. You cannot really have a template design for a ruby on rails app.
Instead, you are looking to ask one of these two questions:
1) Is there an open source Ruby on Rails application that does blah blah blah?
or
2) I'm planning on using XYZ open source Rails app (such as typo or beast or spree) ... does anyone know of design templates for it?

A: When you make a Rails app, you write all the HTML yourself. There is nothing specific about a Rails specific template.

A: I've developed a rails ready theme called {rails}strap. You can save alot of developer time with it.


text:
Q: Reading JSON with PHP {"items":[
{
"name":"xyz",
"traits":["a","b","c","d"],
"specialities":["a","b","c","d"]
},
{
"name":"abc",
"traits":["a","b","c","d"],
"specialities":["a","b","c","d"]
}
]}

How do I read traits and specialities ... items->traits and items->traits[0] doesnt seem to work !
Guide me through it please

$data=json_decode($json);
foreach($data->items as $playerdata)
{
/*
I tried
$traits=$playerdata->traits;
and
$traits=$playerdata->traits[0];
and
$traits=$playerdata[0]->traits (althought i dont know why)
*/
}
I want to store all the values inside traits and specialities inside a $traits and $specialities respectively
P.S: Please ignore syntactical errors.. i hope you get the general gist

A: you need to use json_decode() function,
$my_object = json_decode($json_string);

then you should be able to access it as you normaly do with objects
this is an example of how you should do it
<?php

$json = '{"items":[ { "name":"xyz", "traits":["a","b","c","d"],    "specialities":["a","b","c","d"] }, { "name":"abc", "traits":["a","b","c","d"],    "specialities":["a","b","c","d"] } ]}';

$my_object = json_decode($json);

var_export($my_object->items[0]->name);

and this is how you can access traits and specialities
$traits = [];
$specialities = [];

echo "the traits are:\n";
foreach($my_object->items as $item)
{
    var_dump($item->traits);
    $traits[] = $item->traits;
    echo "\n";
}

echo "\n\n";
echo "the specialities are:\n";
foreach($my_object->items as $item)
{
    var_dump($item->specialities);
    $specialities[] = $item->specialities;
    echo "\n";
}

from var_dump you can see that traits and specialities are both arrays, then you can simply access them as array, or write a function that accept an array and return wathever you are looking for.

A: Use the json_decode function from php and decode you string. Then you have an array and you can access it.
http://php.net/manual/en/function.json-decode.php

A: <?php

$d = '{"items":[
{
"name":"xyz",
"traits":["a","b","c","d"],
"specialities":["a","b","c","d"]
},
{
"name":"abc",
"traits":["a","b","c","d"],
"specialities":["a","b","c","d"]
}
]}';

$h = json_decode($d);

foreach($h->items as $i){
    $traits[] = $i->traits;
    $specialities[] = $i->specialities;
}

echo "<pre>";
print_r($specialities);
echo "<pre>";

?>


text:
Q: How to pass dynamic data from page1 to page2 in jquery mobile I have two pages in Jquery mobile(page1.html,page2.html,page1.js,page2.js). A form with dynamic list available in page1. I want to submit this form, then this form data pass to page2  and display in page2.
 So how to pass the "page1" form data to "page2" using jquery mobile. Also page1 form contains dynamic list, so how to get dynamic list parameters in page2.

A: I believe $.mobile.loadPage will help you.
Although you have to use PHP.
$.mobile.loadPage( "page2.php", {
    type: "post",
    data: $("form#form_id").serialize();
});

And then in page2.php you should see the data
<?php
  print_r($_POST);
?>

If you can't use PHP then I believe you could use same script above, but use Js to extract GET parameters. Which I do not prefer.


text:
Q: Why don't I gain disk space back when emptying the site collection recycle bin? I'm trying to recoop some diskspace on a test SharePoint environment of mine. I've removed as much content as I can in the portal and also emptied the site collection recycle bin but the free space on the disk hasn't moved. What am I missing?

A: In order to recuperate the space you will need to manage your SQL Server database files (MDF/LDF). My suggestion is that unless your disk space is critical that you not do this. Shrinking databases has some serious implications for performance and can cause some headaches. IMO, unless you really need the disk space, just leave it.
Here are some sources to back this opinion up from SQL Server MVPs:
http://www.brentozar.com/archive/2009/08/stop-shrinking-your-database-files-seriously-now/
http://blog.sqlauthority.com/2011/01/19/sql-server-shrinking-database-is-bad-increases-fragmentation-reduces-performance/
http://blogs.msdn.com/b/sqlserverstorageengine/archive/2006/06/13/629059.aspx

A: Personally I have never had an issue when shrinking SharePoint DBs - Keep in mind I am only releasing the white space, but have had no performance impact to any of my sites


text:
Q: Delete logs in loki is there any way to delete logs from Loki without table manager config like this:
table_manager:
  retention_deletes_enabled: true
  retention_period: 336h

This way is too destructive and not very useful, so I was wondering is there any better way to do it, for example by label or something?

A: Now, in master branch, the feature has been developed, but it's not in latest release (tag v2.2.1). so wait a moment.
master

*

*https://github.com/grafana/loki/blob/main/pkg/storage/stores/shipper/compactor/compactor.go#L39

*https://github.com/grafana/loki/blob/main/pkg/loki/modules.go#L620
2.2.1

*

*https://github.com/grafana/loki/blob/v2.2.1/pkg/storage/stores/shipper/compactor/compactor.go#L27

*https://github.com/grafana/loki/blob/v2.2.1/pkg/loki/modules.go#L570


text:
Q: How does printf("Hello" "World"); work I have started to write my first kernel-module and used the KERN_INFO macro.
The line itself looks like that
printk(KERN_INFO "Hello world");

So I was confused, why there is no comma after KERN_INFO and used the preprocessor to print the expanded version.
printk("\001" "6" "Hello world 2\n");

Now I was confused even more. I wrote a little program test this with printf.
#include <stdio.h>

int main (void)
{
        printf("Hello" "World");
        return 0;
}

Which works just fine, but why?
I do not think those are 2 arguments because arguments are comma-separated.
I know C ignores all whitspaces but I have never
heard of it concatenating 2 strings without a function.
Is there an official documentation showing that this is possible or how it works?

A: C concatenates string literals which are adjacent. So for C language:
"abc" "def"

is the same as:
"abcdef"

It's important to remember it only works on compile time literals, not on char * variables, so:
char s[10] = "abc";
printf(s "def");

wouldn't work.

A: Adjacent string literals are treated as a single literal, made up by concatenating the parts.
So "Hello" " there " "world" is equivalent to "Hello there world".
Incidentally, the adjacent parts can be broken across lines (which is a bit hard with a single literal).
So
"Hello"
" there "
"world";

and
"Hello there world";

are equivalent.


text:
Q: Is there a way to install FileGDB driver after QGIS has been installed? I have QGIS 3.2 installed (Windows 7 64-bit), and I need to be able to read and write to Esri file geodatabases.
I have read the thread Installing File Geodatabase (*.gdb) support in QGIS?, which explains how to install the necessary FileGDB driver during a fresh install of QGIS; however, I would like to install the FileGDB driver for my existing install of QGIS.
So, my question is:
Is there a way to install the FileGDB driver after QGIS has been installed?
p.s. If this were on my personal computer at home, I'd just do a fresh install. As it stands, it took me a few years of pestering my IT folks to even get them to allow an install of QGIS on my machine as a "test case", so the fewer hoops I have to ask them to jump through to get QGIS to meet all of our needs, like read/write to File GDB, the better!

A: To install gdal-filegdb on an existing QGIS (not installed with osgeo4w):
close QGIS,
run osgeo4w shell from QGIS 3.x program group as an administrator.

Run setup with -l option indicating the gdalplugins directory (under QGIS/bin) and -P option gdal-filegdb.
You will be prompted for setup options (like qgis osgeo4w install). Select advanced and in the lib section be sure to have gdal-filegdb checked.
Run QGIS, you will get the ESRI file gdb option on loading vector layers->directory.

A: I had my IT department do a clean install of QGIS, following the instructions in the aforementioned thread Installing File Geodatabase (*.gdb) support in QGIS?
At this point, I'm not sure if there's a way to install the FileGDB driver after installing QGIS, so this seems like the only workaround.
EDIT: Atilio's answer above achieves what I was originally trying to do (install the driver after QGIS was installed), so I've marked it as the answer. A clean install will still work, of course, but it's not optimal.


text:
Q: Dual-boot Ubuntu and Win 10 resulting in 2 empty partitions I decided to install Ubuntu alongside Windows (dual-boot). I've unchecked things like Fast Startup and Secure Boot and I freed 30 GB space in diskmgmt.msc for Linux. Then I installed Ubuntu with my USB.
Everything was right, installation showed up as successfull, but while restarting the computer there didn't appear any grub menu where I could choose the OS.
I tried some solutions found in the internet like the command:
bcdedit /set {bootmgr} path \EFI\ubuntu\grubx64.efi

but it didn't help.
Then I looked up again in the diskmgmt.msc and I found 2 completely empty partitions with total size of these 30 GB I released before. I don't know why, but it seems that Ubuntu installation only created these 2 partitions and that's it.
Just to make it clear, while installing Ubuntu I've chosen for "Install Ubuntu alongside Windows Boot Manager" option (or something like this), not the "Something else" option.
The question is, did I actually really successfully install Ubuntu, and if yes, how to make the grub menu appear, and if not, what should I do then? Delete these partitions to make free space for Ubuntu or just reinstall Ubuntu using the USB?
Thanks for your answers.

A: The Ubuntu installation has probably failed, as 30 GB is too near to the bare minimum.
The
 Installation System Requirements
recommended minimum is 25 GB, but does not say with which installation options.
If you wish to try again, I suggest to unify the two partitions into
one partition of 60 GB for the installation.
However, you should know that Ubuntu is now available inside Windows via the
Microsoft Store. This is much safer than dual boot and requires no partition
work.


text:
Q: Button Text - UIColor from Hex? SWIFT Here's a line to change my button text to green
self.button.setTitleColor(UIColor.greenColor(), forState: .Normal)

That gives me just your standard green color.  Is there a way to use a hex number?  I've got a hex number for the pale shade of green I need just not at my computer at the moment sorry.
*Also this color change is happening after I click the button, just didn't bother posting that part of the code.  I do know I can select any color it initially displays in my storyboard section.
Any guidance or help greatly appreciated.  Thanks.

A: You add a UIColor extension in your project to do so:
extension UIColor {

    convenience init(rgb: UInt) {
        self.init(rgb: rgb, alpha: 1.0)
    }

    convenience init(rgb: UInt, alpha: CGFloat) {
        self.init(
            red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgb & 0x0000FF) / 255.0,
            alpha: CGFloat(alpha)
        )
    }
}

Then you can use it like:
let brown = UIColor(rgb: 0xBE5300)  // BE5300 is the hex value

A: This would be the code:
UIColor(red: 255/255, green: 204/255, blue: 0/255, alpha: 1.0) /* #ffcc00 */

also a very useful tool/ website for converting the colors into useful Swift code:
https://www.ralfebert.de/snippets/ios/swift-uicolor-picker/
Edit:
Example:
self.button.setTitleColor(UIColor(red:0.96, green:0.28, blue:0.28, alpha:1.0), forState: .Normal)

or if you want a cleaner solution:
var myColor = UIColor(red:0.96, green:0.28, blue:0.28, alpha:1.0)
self.button.setTitleColor(myColor, forState: .Normal)

A: Let's say you have hex components {dd, fe, a8}. You can construct a UIColor from them by using initializer that takes individual components, like this:
color = UIColor(
    red: Float(0xDD) / 255.0
, green: Float(0xFE) / 255.0
,  blue: Float(0xA8) / 255.0
, alpha: Float(1)
)


text:
Q: How to manually set the dispersion parameters for truncated negative binomial distribution in glmmTMB? I am using glmmTMB to run a glmm with a zero-truncated error distribution. I would like to manually set the dispersion parameter in my model and found a webpage that suggests that this is possible. However, there are no examples of how to actually use them with glmmTMB and the documentation is vague. For example, it doesn't explain what "value" means for x.
I tried to create one with the following, filling in values of size and mu with values from the fitdistr function from the package MASS:

disp.parameter<-(x, size, mu, k = 0, log = FALSE)

Unfortunately, this didn't work.


text:
Q: How to see the 'example provider' in processing toolbox of QGIS? I would like to create my own provider with the processing toolbox. I see the example provider in my folder C:\QgisWien\bin...\algs\ExampleProvider.
It seems to be a good start but unfortunately, I don't see the example provider in the processing toolbox.
I see this post : Is there a way to integrate my own custom tools into the Processing toolbox in QGIS?
I try to copy the folder ExampleProvider to my qgis plugins path but nothing.
I have Windows se7en and qgis wien installed.

A: 1) add the ExampleProvider folder in the qgis plugins ;
2) fix the path of the module in the different python files in order that the import does correctly.
 (one module seems to point to C:\QGISPATH\bin...\algs\ExampleProvider) ;
3) activate the plugin in the plugin manager.
And now, the Example aglorithms provider appears in my processing toolbox.


text:
Q: Probability of bit strings Suppose you pick a bit string of length $10$. Find the probability that the bit string has exactly two $1$'s, given that the string begins with a $1$.
Can someone please explain to me how to do it?

A: Since you know that the first bit is $1$, you just want to find the probability that exactly one of the remaining $9$ digits is $1$. The total number of possible $9$-bit sequences is $2^9$. Of these only $9$ have exactly a single $1$, one for each possible position of the $1$. So the probability is $\frac{9}{2^9}$.

A: There is a nice and clean way to do it. The number of possible bit strings are $2^{9}$.
This is because each and every position in the string can be zero or one except the first which can only be one.
Now, you want one out of the nine places in the string to be 1. In order to do that, just select two places using $9\choose 1$.
Now, the probability is rendered as $$\frac{\text{favourable events}}{\text{total events}}= \frac{{9\choose {1}}}{2^{9}}$$

A: X~The number of 1s in a bit string of length 10
X~B(10,0.5)
We just split it by cases since we know first one is already 1.
Y~The number of 1s in a bit string of length 9
Y~B(9,0.5)
P(Y=1)=0.01757
P(given first is 1 and we want 2 1s)=(0.01757×0.5)/P(X=2)
=0.2


text:
Q: Format Dynamic Text Using PHP I have text fields which are populated from a database, the text when entered by the user is punctuated correctly with full stops and carriage returns etc.
Using VB with an ordinary db request:
<%=(rsMyrecordset.Fields.Item("text").Value)%>

I would get this result:
Mary had a little Lamb. Its fleece was as white as snow.

even if the user entered a return after the full stop after the word Lamb.
Using this code:
<%= Replace(rsMyRecordset.Fields.Item("text").Value, VbCrLf, "<br>") %>

The text returned would be:
Mary had a little Lamb.
Its fleece was as white as snow.

How would I achieve the same result using PHP?  Currently I have:
<?php echo $row_rsMyRecordset['text']; ?>

Many thanks

A: maybe you are looking for nl2br: http://php.net/manual/function.nl2br.php
<?php echo nl2br($row_rsMyRecordset['text']); ?>


text:
Q: Dynamically size both UICollectionViewCell and UICollectionView, maybe UITableViewCell I'm building something as shown in the image below:

I'll try to explain a bit more what my goal is. I have a UITableView. One UITableViewCell (1) in here will contain a title (left out in this image) and a UICollectionView (2) (same width as tableview/screen). This collectionview uses a subclass of UICollectionViewLayout to make it horizontally scrollable, evenly spacing the items.
Each UICollectionViewCell (3) in here contain a title and description, both with dynamic heights. Also, this cell contains a new collectionview (4). This new collectionview contains a number of items (5). In this most inner collectionview a row can contain a maximum of 5 items.
Currently I have a tableviewcell (1) with horizontally scrollable collectionview (2), putting the items (3) next to each other. I also have the most inner collectionview (4) putting the items (5) in the correct way.
The difficulty I'm facing now is:

*

*To dynamically size the height of collectionview (4), depending on how many rows for the items are needed, so depending on the number of items.

*To dynamically size the height of collectionviewcell (3), depending on the height of the title, description and collectionview (4).

*If possible, to dynamically size the height of the collectionview (2) and the tableviewcell (1) containing this, as high as the biggest cell (3).

I hope someone would have an idea how to do this, if it is even possible. I do hope so, while keeping the code 'easy' to follow.
I can do a lot with constraints / autolayout, but this I can't get my head around.


text:
Q: printf padding from left by number other that zero I have a=10 var that I want to pad from left with integer 1 with 5 padding.
Output should be below:
11110

when Im doing:
printf "%05d\n" "${a}"

it gives me 00010.

A: I think I would just:
printf "% 5d\n" "10" | tr ' ' '1'

fill with spaces and then substitute spaces for ones.

A: As per bash printf man page, it supports only zero padding, so you can't directly use integer padding other than zero.
You can do by string printing or pad by manipulating
a=10
printf '%s\n' 111${a}

or
 printf "% 5d\n" "10" | tr ' ' '1'

A: You may use this instruction:
printf "%5d" "$a" | sed 's/ /1/g'

It outputs:
11110


text:
Q: How to reference internal delegate of a different assembly in C# I have following code
public class MyClass{
     internal static Dictionary<string, ActivityManager.TagSerializer> TagHandlers = new Dictionary<string, ActivityManager.TagSerializer>(StringComparer.OrdinalIgnoreCase);
}

where TagSerializer is a delegate in ActivityManager like following
public class ActivityManager
{ internal delegate string TagSerializer(string tag, ActivityTemplateVariable atv, ContentType ct, CultureInfo ci);}

Because myclass and ActivityManager are in different assembly, my code will return error

Inconsistent accessibility: field type 'System.Collections.Generic.Dictionary
  <string,Microsoft.Office.Server.ActivityFeed.ActivityManager.TagSerializer>' is less accessible than field 'MyClass.TagHandlers'

ActivityManager class is in a third party assembly, and I can't change it.
How do I use reflection to solve this problem?

A: You'll need to use the InternalsVisibleToAttribute.


text:
Q: Aperture showing videos with odd lines, how to see videos nicely in OSX? I imported my tennis couching videos to Aperture but Aperture shows them with odd lines while QuickTime Player more nicely shows them. Which software should I use for videos because Aperture is clearly not meant for this?
Aperture

QuickTime Player

P.s. I imported my videos from Sony Nex-3N.

A: I just went with Final Cut Pro: stored the videos to external HDD and then viewed them there with FCP. Also VLC player as suggested may be an option. Yet FCP is also for editing, VLC for playing. For this purpose just for analysing the shots, FCP and VLC may be a bit off-topic but they can nicely show videos.

A: Your video appears to have interlacing encoded by the source recorder. You can use HandBrake to remove interlacing while re-encoding. Aperture, btw, is photo editing and management software. It may play video, but there are players that are far better suited to video, such as QuickTime, or VLC. VLC, btw, is a defacto standard, and usually the answer to the question: "what will play this odd video format I can't seem to view with any decoder I've tried?" VLC has streaming and encoding functions as well. Final Cut Pro will of course play videos, but it is a video editing suite first, not "also," which means it is rather heavy amount of software for such a light task as playing video. You seemed to have answered your own question, but I thought I'd give you better confidence in your own answers.


text:
Q: Can 10.0.0.0/8 network range used for public ip? Recently I used utorrent, where I saw that it was fetching files from ip of the range 10.0.0.0/8 which were running ftp service. But in computer networking I learned that 10.0.0.0/8 range is used for private ip. So please clear my doubt of this range

A: The address range is reserved as "private", but that merely means that ISPs of the world have agreed to not accept any routes for it, and that the meaning of such addresses varies from place to place.
However, it doesn't really limit how broad the "private" usage might be – it might be building-wide, company-wide, even ISP-wide or country-wide. My ISP uses 10./8 for its device management; my $WORK uses 10./8 for its LAN that spans six buildings, and is connected to a country-wide "secure" network that also uses 10./8. Some ISPs, who have run out of global addresses, use CGNAT and provide all customers with private addresses only.
So you might be seeing another host on your own network, found via PEX or LPD or such.


text:
Q: How to read different columns in rows in AnyLogic? I would like to ask you for advice. While working on my diploma thesis in AnyLogic (based on java) I got stuck with a problem. I have an Excel table imported to AnyLogic as a database and the table looks like this:

I need to read all columns called "route" row by row and load them to a collection as an array list.
I think the problem is that the "route" column isn't at the beginning and also I want the program to read more than one column. In addition, each row has a different number of "route" columns that the program is supposed to read.
I tried to create a function, but I struggle with the writing of the function body. I was able to read only one column ("route1") so far.
selectFrom(test_data)
    .where(test_data.id.eq(ID))
    .list(test_data.route1)
);

Can anyone help me please? Any advice will be greatly appreciated.
Thank you in advance.

A: Depending on how many records you have, it might actually be simpler to create a type of agent that maps to a record using this method and selecting Use database table option.
Then you can create a population of that type of agent and point it to your database table. At model start up it will load the records, create an agent per record and then you can operate on them directly without having to write a database query.


text:
Q: How do I disable EDNS in systemd-resolved I am experiencing long DNS lookup times (> 5s) due to non-compliant EDNS responses from my DNS server triggering (I think) this bug in systemd-resolved. I'd like to turn off EDNS in resolved to see if that fixes the problem, however  I have been unable to figure out how to do this.
My /etc/resolv.conf is a symlink to /run/systemd/resolve/stub-resolv.conf and contains the line options edns0 trust-ad. I have tried removing the symlink and replacing it with a real file that does not have this "options" line and then restarting resolved, however after doing that I still see the following log message in syslog:
Feb 15 09:07:35 charon systemd-resolved[1007519]: Using feature level UDP+EDNS0 for transaction 31630.

What is the correct way to disable EDNS in resolved on Ubuntu 20.04?


text:
Q: Waiting for *ngFor to build the page to perform DOM Manipulation Community,
i am having some problems with my Angular 6 - App which i'm unfortunately not able to solve after hours of thinking & searching on google.
I've got a component that is displaying Meetings, Projects and Tasks in a Form. Those forms require a lot of data from different collections to select from (if the user wants to change something). All of those are being loaded in my ngOnInit:
  ngOnInit() {
    this.meetServ.getCompanyMeetings(false)
      .subscribe(data => this.meetings = data as meeting[]);
    this.deptServ.getCompanyDepartments()
      .subscribe(data => this.depts = data as department[]);
    this.CusServ.getCompanyCustomers()
      .subscribe(data => this.customers = data as customer[]);
    this.UserServ.getCompanyUsers()
      .subscribe(data => {
        this.users = data as user[];
      })
  }

When I'm done loading all the data, I want to set all of the dropdown menus to the right values. So I put a setDropdowns method in the subscription of the last http-request I am doing (also tried out of subscription).
The extend() Method is called by onclick event as soon as the User selects a Meeting:
extend(meetingID) {
    document.getElementById("overlay").remove()
    this.meetServ.getMeetingbyID(meetingID)
      .subscribe(data => {
        this.singleMeeting = data as meeting
        this.init(); //gets all the projects by ID of selected Meeting
        this.setMeetingAccessLevel();
        this.setMeetingComments();
        this.setDropdowns(); // tried like this
      })
      this.setDropdowns(); // and like this
  }

and my setDropdowns() Method looks like this:
  setDropdowns() {
    var projectDivs = document.querySelectorAll("div.projectContent");
    console.log(this.projects.length)
    for (var i = 0; i < this.projects.length; i++) {
      // Access Level
      var opts = projectDivs[i].querySelector("#access").querySelectorAll("option");
      (<HTMLOptionElement>opts[this.projects[i].accessLevel]).selected = true;
      // Department
      opts = projectDivs[i].querySelector("select#dept").querySelectorAll("option");
      for (var j = 0; j < this.depts.length; j++) {
        if (this.depts[j]._id == this.projects[i].department) {
          opts[j + 1].selected = true
        }
      }
      //Customer
      opts = projectDivs[i].querySelector("select#proCustomer").querySelectorAll("option")
      for (var k = 0; k < this.customers.length; k++) {
        if (this.customers[k]._id == this.projects[i].customer) {
          opts[k + 1].selected = true
        }
      }
      //Official
      var asd = (<HTMLSelectElement>projectDivs[i].querySelector("select#proinCharge")).querySelectorAll("option")
      for (var l = 0; l < this.users.length; l++) {
        /* if (this.users[l]._id == this.projects[i].inCharge) {
          asd[l].selected = true
        } */
      }
    }
  }

But when I look at the console, this.projects.length is either 0 or 2 (which is the actual number of projects in that meeting). The thing is, when I get it to log 2, the projectDivs[i].querySelector("#access") part errors "Cannot read property 'querySelector' of undefined", which actually makes no sense, since projectDivs are generated like this:
<div class="projectContent" id="projectContent" *ngFor="let project of projects">

and console.log(this.projects.length) returns 2 earlier.
So projects are loaded but the HTML seems to not be loaded properly at that point.
Now for sure i googled this a lot and tried out stuff like jQuery document.ready and checked if document.readyState == complete, but it seems to only apply to the static document and not to the *ngFor generated elements.
So obviously my question in the end is: Is there any way to wait for all *ngFor generated elements or is there just a much easier way of doing this which is wasn't able to spot?
Thanks in advance for all the upcoming answers.
Greetings


text:
Q: $geoWithin query fail to retrieve point included in the queried polygon - v2 I've already ask the same question in this post. My example was subject to earth curvature issue so lets have a look to another one.

This time I have two nested polygons. A large one and a smaller one. Performing a $geoWithin query with the larger one return no document while the document is found using the smaller polygon. Any thoughts?
https://mongoplayground.net/p/V_3-s-itngA

The document I'm trying to query which is located on an island on France west coast.
  {
    "_id": {
      "$oid": "625fec0f6476793a4581d172"
    },
    "featureOfInterest": {
      "samplingFeature": {
        "geometry": {
          "type": "Point",
          "coordinates": [
            -2.3433781679840138,
            46.713764788942484
          ]
        },
        "name": [
          {
            "lang": "en",
            "text": "France"
          }
        ],
        "type": "Feature"
      }
    }
  }

And the query
db.collection.aggregate([
  {
    $match: {
      "$or": [
        //Largest polygon - return no document
        {
          "samplingFeature.geometry": {
            "$geoWithin": {
              "$geometry": {
                "type": "Polygon",
                "coordinates": [
                  [[-55.722656,34.161818],[58.007813,34.161818],[ 58.007813,53.540307],[ -55.722656, 53.540307], [-55.722656,34.161818]]]
              }
            }
          }
        },
        //Smallest polygon - return the document
        //{
        //  "samplingFeature.geometry": {
        //    "$geoWithin": {
        //      "$geometry": {
        //        "type": "Polygon",
        //        "coordinates": [[[-5.800781, 42.682435], [9.316406, 42.682435], [9.316406, 50.625073], [-5.800781, 50.625073], [-5.800781, 42.682435]]]
        //      }
        //    }
        //}
        //}

      ]
    }
  }
])

A: You've bent the planet other way round. The coordinates in your post make these boxes:

the marker is clearly outside the the larger box.
Please use the link to jsfddle in my answer to your previous question instead of globes, or wherever you get your image from. The shortest path between 2 points far away does not necessarily follow longitudes and latitudes. Please read about the math of Geodesic calculations used in mongo geospatial queries.


text:
Q: How to seek/keyset pagination on alphabetical data
*

*I have 2 tables

resources

resource_votes_aggregate which stores the number of likes per resource_id

*

*I want to paginate through resources in descending order of their title using seek/keyset pagination

*Without Pagination, this is what you get

*

*I want the results in batches of 5 as I am paginating 5 results at a time

My PAGE 1 query worked without issues using the query below
SELECT
   r.resource_id,
   title,
   COALESCE(likes, 0) AS likes
FROM
   resources r
   LEFT JOIN
      resource_votes_aggregate a
      ON r.resource_id = a.resource_id
WHERE
   category_id = 1
ORDER BY
   title DESC,
   resource_id DESC LIMIT 5;

*

*How do I get the next page using keyset/seek pagination?

My attempt
SELECT
   r.resource_id,
   title,
   COALESCE(likes, 0) AS likes
FROM
   resources r
   LEFT JOIN
      resource_votes_aggregate a
      ON r.resource_id = a.resource_id
WHERE
   category_id = 1
   AND
   (
      likes,
      title
   )
   < (586, 'Zatoichi Meets Yojimbo (Zatôichi to Yôjinbô) (Zatôichi 20)')
ORDER BY
   title DESC,
   resource_id DESC LIMIT 5;

Incorrect Results

UPDATE 1
I have created a FIDDLE HERE which loads 20 results? How to paginate this in batches of 5 using seek pagination?

A: There are two options that would do what you need:
OFFSET n FETCH FIRST n ROWS ONLY and sort_column > last_val
Example 1:
SELECT
   r.resource_id,
   title,
   COALESCE(likes, 0) AS likes
FROM
   resources r
   LEFT JOIN
      resource_votes_aggregate a
      ON r.resource_id = a.resource_id
WHERE
   category_id = 1
   AND
   (
      likes,
      title
   )
   < (586, 'Zatoichi Meets Yojimbo (Zatôichi to Yôjinbô) (Zatôichi 20)')
ORDER BY
   title DESC,
   resource_id DESC
OFFSET 5
FETCH FIRST 5 ROWS ONLY;

You would then just change the OFFSET value each time.
Then the other way would be to keep track of the title and resource_id in your application layer, and then pass this to the query so that you start further down the result set:
SELECT
   r.resource_id,
   title,
   COALESCE(likes, 0) AS likes
FROM
   resources r
   LEFT JOIN
      resource_votes_aggregate a
      ON r.resource_id = a.resource_id
WHERE
   category_id = 1
   AND
   (
      likes,
      title
   )
   < (586, 'Zatoichi Meets Yojimbo (Zatôichi to Yôjinbô) (Zatôichi 20)')
   AND
     (title,resource_id) > (last_title_id_from_before,last_resource_id_from_before)
ORDER BY
   title DESC,
   resource_id DESC LIMIT 5;

This would ensure you skip rows from previous pages, but then downside with this strategy is you wouldn't have a way of going back a page again.


text:
Q: What does it mean: Should explicitly set 'android:fullBackupContent' to avoid backing up the GCM device specific regId? What does this Lint warning mean:

Should explicitly set 'android:fullBackupContent' to avoid backing up
  the GCM device specific regId?

I've googled but haven't found anything yet.

A: CommonsWare is correct. However, GCM does not store that regid for you - The GCM quickstarter used to suggest (it has since been updated) that you store it yourself in a shared prefs file.
The lint rule is detecting that you have declared a receiver for GCM and therefore assumes that you are stashing the regid somewhere. Because you haven't declared a fullBackupContent flag in your manifest it is warning you that your app will likely break across restore.
You use the fullBackupContent to exclude or include whatever data you would like to not leave the device and be restored on another device (gcm instance id token is one example)
more details here

A: Let me be more specific here, regarding the Lint warning.
As mentioned in the Known Issues with the automatic backup service:,

backing up the registration ID returned by Google Cloud Messaging registration can break push notifications for the restored app

So it is advised to exclude the gcm registration id from the set of backed up files. And query the API for a new registration ID whenever the app is restored.

A: Part of the disturbing "auto backup for apps" is the ability to control what files get backed up, via android:fullBackupContent. That attribute points to an XML resource (e.g., @xml/backup_rulez), that describes either a whitelist or a blacklist controlling what gets backed up.
What the Lint warning is warning you about is not backing up the GCM registration ID, as that is per-device, and so it would need to be re-generated if your app's data is restored from the backup onto a new device. Personally, off the top of my head, I don't know where GCM is storing that registration ID.


text:
Q: Remove underline and link from tooltip I try to implement a tooltip with picture. That works. But I have 2 problems:

*

*If I move mouse over word TooltipText only a dashed line should be displayed. But the word is also underlined (because Link).

*I would like to disable the link, since it is a tooltip. The CSS attribute 'pointer-events: none;' disables the link, but then the tooltip is not working.

HTML:

TooltipText

CSS:
a .hover-img {
    position:relative;
}
a .hover-img span {
    position:absolute; left:-9999px; top:-9999px; z-index:9999;
    border: 2px solid #000;

}
a:hover .hover-img span {
    top: 40px;
    left: 0;
}
.dotted {
    color: #4e555b;
    border-bottom: 2px dashed #4e555b;
    text-decoration: none!important;
}
.dotted:hover {
    text-decoration: none!important;
}

JSFiddle:
https://jsfiddle.net/kdzb108h/

A: Add this:
 a  {
   text-decoration: none;
 }

text-decoration should be applied directly to , not to its child tags.
Refer to: https://jsfiddle.net/ewtysb4c/

A: The word is underlined because the  tag has a href attribute. If you remove the attribute, both the underline will disappear and the link will be disabled.
However, the cursor will also not behave like a link. You could enforce the text-decoration: none in the  tag and add a cursor: pointer to the the a:hover rules. I'd suggest you create an a.tooltip-link class and add these styles to it so they won't be applied to all  tags in your page.

A: *

*The .dotted class is being applied to the 'strong' element, this does not have a text-decoration property. You need to apply a class to the 'a href="#"' tag and set the text-decoration: none; on that element.

A: So, first of all want to explaint few things. You used  as container, what's wrong. If you see any year w3.org documentation, you'll see that link is inline document. This link here: https://www.w3.org/TR/html401/struct/global.html#h-7.5.3 says, that inline elements can contain only other inline elements or text.
Second thing. I'd rather make the structure next way:

Tooltip Text

Than set div.tooltip-text display:block, and change it by hovering p.tooltip-provoke. By using + in css ('.a + .b') you say to apply styles to first element after element with class="a" and only if it's class="b".
You can see example here: https://jsfiddle.net/0pmknx4g/9/


text:
Q: Ubuntu 14.04 wont reboot after choosing nvidia drivers (optimus laptop) Well I decided to give linux again a try. I was excited when I heard that ubuntu was supporting an alternative to bumblebee. But no luck today so far.
The installation goes flawless, I open the utility that install alternative drivers, nvidia 331, i think it is... then I reboot as requested and thats it. The system wont be able to reboot, it is stuck at the gnome symbol at the very begining of the booting proccess, I forgot to mention I use Ubuntu Gnome.
I have tried to install another choice that is listed, 331-updates, with the same luck
I have tried also installing using the terminal, same.
I would apreciate any help.
I would really like to know how to revert the drivers to nouveau,because every time I have to try... I am reinstalling the whole thing!!! it is kinda embarasing, and time comsuming! thanks folks!


text: Q: Python, Heroku, save Files to Local PC So I know that Heroku is ephemeral and if I undestand it right it deletes a.e. a Text File that was created. So my Question is, is it possible that it just saves a Text File to my local Desktop or somewhere where I don't need to pay any money? Thanks.


text:
Q: How to read/get unicode value for an emoji in Java We are trying to let our application accept emojis. We are trying to limit the emojis to the ones from this list.
So, i am trying to read the unicode value (for example, U+1F600 for ) for emojis - so i can validate that the user entered emoji is from the above list.
can somebody please help me with how to read the unicode value for an emoji? or any other ways i can implement this validation ? using encoded values etc.?
        }

String actualEmojiString = "";
            for(int i=0; i< actualEmojiString.codePointCount(0, actualEmojiString.length()); i++) {
                int codePoint = actualEmojiString.charAt(i);
                if(Character.isSurrogate(actualEmojiString.charAt(i))) {
                    codePoint = Character.toCodePoint(actualEmojiString.charAt(i), actualEmojiString.charAt(i));
                }
                System.out.println( "HexCode value for emoji: [" +  actualEmojiString.charAt(i) + "] is [" +"U+" + Integer.toHexString(codePoint | 0x10000).substring(0) +"]"
                        + "["+"\\u" + Integer.toHexString(codePoint | 0x10000).substring(1) + "]");

Output:
HexCode value for emoji: [?] is [U+1f03d][\uf03d]
HexCode value for emoji: [?] is [U+190200][\u90200]

A: You are overcomplicating your code by mixing code points and chars. Instead use String.codePoints() method:
"".codePoints().mapToObj(Integer::toHexString).forEach(System.out::println);

will print the unicode values as hex:
1f600
1f602

This however might not be needed at all because Java supports unicode String literals. To check if the text contains an emoji you can simply do:
"".contains("");


text:
Q: The cause of this output exception was that: ClientAbortException: java.net.SocketException: Broken pipe I recently moved a site from Railo to ColdFusion 10 and everything went fine except one error that keeps popping up that i never got on Railo.
I have a page for downloading .pdf documents done with just a simple cfheader and cfcontent to deliver the files
The error i keep getting emailed is;
The cause of this output exception was that: ClientAbortException: java.net.SocketException: Broken pipe.
There was a previous question here;
https://stackoverflow.com/questions/19301173/clientabortexception-java-net-socketexception-broken-pipe-while-using-cfcontenquestion
Unfortunately it is unanswered.
I can recreate the error by starting a download, and then cancelling it before its complete. So i thought maybe its just people cancelling downloads. But whats confusing me though is sometimes i'll get a few errors in a row, less than a minute between them, from the same user trying to download the same file, so i'm thinking is there any other reason for this error other than someone cancelling the download?


text:
Q: How to convert mongodb response array from javascript object to JSON string I have written a javascript API which returns all the data from mongodb database on request. However it is sending the data s an array of objects and I want to get the simple json string. The statement returning the objects is
return db.collection('variants').find().toArray();

Do I need to append another function like JSON.stringify()? but I think that work for single object but not for array of objects as in my case.
var fetch = require('graphql-fetch');
const API_URL = `http://localhost:4000/graphql`
const query = `
{
  variants{
    VARIANT_ID
    CHROM
  }
}
`
fetch(API_URL)(query).then(data => console.log(data))

A: Okay I found the solution. All I need is JSON.stringify(data).
var fetch = require('graphql-fetch');
const API_URL = `http://localhost:4000/graphql`
const query = `
{
  variants{
    VARIANT_ID
    CHROM
  }
}
`
fetch(API_URL)(query).then(data => console.log(JSON.stringify(data)))

A: The following snippet will works properly.
fetch('/users.json')
.then(function(response) {
    return response.json()
}).then(function(json) {
    console.log('parsed json', json)
}).catch(function(ex) {
    console.log('parsing failed', ex)
})

A: You can use mongoexport.
In order to perform this operation you need read access to the database.
Eg: mongoexport --db database [--collection traffic] --out file.json


text:
Q: Shared libraries in Poly/ML Is it possible to build a shared library using Poly/ML?
I want to be able to create a C API for a Poly/ML library, and invoke/load it from different programming languages (e.g., Python). Did anybody try to do that?
I know this can be done in OCaml:

*

*How can I call OCaml functions from a Python program?

A: Here is an answer provided by David Matthews, Poly/ML main developer (http://www.polyml.org/):

The simple answer is no, at least at the moment.  I had a look at this
  and wondered if it was possible.  The foreign-function interface
  allows for call-back functions so there is the mechanism to produce a
  C function that when called calls an ML function.  The difficulty I
  could see was that in order to produce a shared library the closure
  for the C function has to be "unpicked" so that relocation information
  can be produced for addresses within the closure.  I'd have to add
  something to libffi to do that.  It doesn't look to be too hard for
  X86 but I haven't taken it any further.  There may be other issues
  that I'm not aware of.


text:
Q: C# .netcore WPF Displaying window with details of background process failure I have a WPF application. A window launches and asks the user to select a launch mode, "Demo" or "Live".
If they click "Live" then an indeterminate progress bar comes up and the application will run a mixture of synchronous and asynchronous tasks which acquire data from a COM+ service while the progress bar is animated.
if the requests for data are unsuccessful a window comes up and the window with the progress bar remains on screen. The unsuccessful window shows high level failure details and gives two options: retry, quit.
the problem is that data calls are blocking the UI so even though the progressbar is set to visible, it is not actually visible until the button click event has returned (either by the data being loaded successfully or not).
If i want to run my data requests in Tasks then the UI is unblocked and the button click event is returned, the progress bar is visible and animated but if the data request fails I have no way to launch the unsucessfull window. I cannot use exceptions thrown in the data request thread to notify the main thread without awaiting the data request Task but cannot await the task as it will freeze the UI thread and not show a responsive UI while data is loaded.
I clearly have an antipattern. What is a good way to display a window when a background task fails without blocking the UI thread?
App.xaml.cs

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            launch.ShowDialog(); //this window has two buttons for live or demo launch. on selection itll show an indeterminate progressbar
            loadingWindow.ShowDialog(); //this shows the window but doesnt stop exectution to the next line
        }

Launch.xaml.cs
        private void btnDemo_click(object sender, EventArgs e)
        {
            ProgressBarVisibility = Visibility.Visible; //ProgressBarVisibility prop is model bound to the progress bars visibility

             // Visibility is not updated yet because the UI is currently blocked by the lines below...

            try
            {
                LoadConfigs();
            }
            catch
            {
                Close(ExitReasons.CONFIGLOADERROR);
            }

            // this is where the data requests might fail and i need to
            //open a new window that says which task failed (getUser or getRecord etc...) and give the
            //user an option to return or close. If i make this task async then i unblock the UI but
            //cannot try catch any of the errors thrown in the call chain withouth awaiting the call
            //which blocks the UI....
            PreCacheEHRData();
            LaunchMainApp(); // if the data loads successfully the launch window is closed
                             //an a new window with the primary functionality is launched.
        }

Thanks for your help

A: You should do the I/O work on an awaited task. Wrap try/catch block with Task.Run, and do the UI calls inside the catch block on Application's dispatcher.
make btnDemo_click async void.
private async void btnDemo_click(object sender, EventArgs e)
{
    ProgressBarVisibility = Visibility.Visible;
    var isDataLoadedSuccessfully = await Task.Run(() =>
    {
        try
        {
            LoadConfigs();
            return true;
        }
        catch
        {
            // Application.Current.Dispatcher.Invoke(() =>
            Dispatcher.Invoke(() =>
            {
                // here you can do UI-related calls..
                Close(ExitReasons.CONFIGLOADERROR);
            });
            return false;
        }
    });

    // next code will be on UI thread
    ProgressBarVisibility = Visibility.Hidden;
    if (isDataLoadedSuccessfully)
    {
        // await Task.Run(() => PreCacheEHRData());
        PreCacheEHRData();
        LaunchMainApp();
    }
    else
    {
        // do something
    }
}

A: Call any long-running operation on a background thread by creating an awaitable Task, e.g.:
private async void btnDemo_click(object sender, EventArgs e)
{
    ProgressBarVisibility = Visibility.Visible;

    try
    {
        await Task.Run(() => LoadConfigs());
    }
    catch
    {
        Close(ExitReasons.CONFIGLOADERROR);
    }

    await Task.Run(() => PreCacheEHRData());
    LaunchMainApp();
}

Note that the methods that run on a background thread, i.e. LoadConfigs and PreCacheEHRData in the sample code above, cannot access any UI element.


text:
Q: How to select first item after filtering ICollectionView I'm binding a ListView to an ICollectionView in my viewmodel. The ICollectionView has some predefined filters that are applied when you click some buttons. However I cannot seem to find any way to (auto) select the first item in the ListView after the collection has been filtered.
I've tried to set SelectedIndex=0, add both Target and Source notification to the binding, but all are ineffective when the filter applies.
Any pointers on how to achieve this?
EDIT: Below code illustrates my issue I'd say.
XAML:
<Window x:Class="CollectionViewTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:CollectionViewTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">

    <Window.DataContext>
        <local:MainViewModel/>
    </Window.DataContext>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>

        <!-- MENU -->
        <StackPanel Orientation="Vertical">
            <Button Content="Numbers below 4" Click="Below4_Click" Width="100"/>
            <Button Content="Numbers below 7" Click="Below7_Click" Width="100"/>
            <Button Content="All numbers" Click="All_Click" Width="100"/>
        </StackPanel>

        <!-- LIST -->
        <ListView
            Grid.Column="1"
            SelectedIndex="0"
            ItemsSource="{Binding Numbers, Mode=OneWay}"
            SelectedItem="{Binding SelectedNumber, Mode=TwoWay}">
            <ListView.Resources>
                <DataTemplate DataType="{x:Type local:Number}">
                    <TextBlock Text="{Binding Value}" />
                </DataTemplate>
            </ListView.Resources>
        </ListView>

        <!-- DETAILS -->
        <TextBlock Grid.Column="2" Text="{Binding SelectedNumber.Text}" Width="100"/>
    </Grid>
</Window>

Code-Behind:
using System.Windows;

namespace CollectionViewTest
{
    public partial class MainWindow : Window
    {
        private MainViewModel vm;
        public MainWindow()
        {
            InitializeComponent();
            vm = (MainViewModel)DataContext;
        }

        private void Below4_Click(object sender, RoutedEventArgs e)
        {
            vm.MenuFilter = f => f.Value < 4;
        }

        private void Below7_Click(object sender, RoutedEventArgs e)
        {
            vm.MenuFilter = f => f.Value < 7;
        }

        private void All_Click(object sender, RoutedEventArgs e)
        {
            vm.MenuFilter = f => true;
        }
    }
}

ViewModel:
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Data;
using System.Collections.ObjectModel;

namespace CollectionViewTest
{
    public class MainViewModel : PropertyChangedBase
    {

        public MainViewModel()
        {
            Numbers = new ObservableCollection<Number>();
            NumberCollection = CollectionViewSource.GetDefaultView(Numbers);
            NumberCollection.Filter = Filter;
            NumberCollection.SortDescriptions.Add(new SortDescription("Value", ListSortDirection.Ascending));

            for (int i = 0; i < 10; i++)
                Numbers.Add(new Number { Value = i, Text = $"This is number {i}." });

        }

        private Func<Number, bool> menuFilter;
        public Func<Number, bool> MenuFilter
        {
            get => menuFilter;
            set
            {
                menuFilter = value;
                NumberCollection.Refresh();
            }
        }

        private bool Filter(object item)
        {
            var number = (Number)item;
            return MenuFilter == null ? true : MenuFilter(number);
        }

        public ObservableCollection<Number> Numbers { get; set; }
        public ICollectionView NumberCollection { get; set; }

        private Number selectedNumber;
        public Number SelectedNumber { get => selectedNumber; set => Set(ref selectedNumber, value); }
    }

    public class Number : PropertyChangedBase
    {
        public int Value { get; set; }

        private string text;
        public string Text { get => text; set => Set(ref text, value); }
    }

    public class PropertyChangedBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void Set<T>(ref T field, T newValue = default(T), [CallerMemberName] string propertyName = null)
        {
            field = newValue;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

As you can see, pressing one of the buttons changes the Filter and calls Refresh on the collection. What I would like to have, is that the first item in the list (here '0') is selected automatically which then would display the text "This is number 0" in the text in column 2.
I have tried both the SelectedIndex=0 and also MoveCurrentToFirst but nothing is selected.

A: Don't set SelectedIndex when binding to an ICollectionView. Instead, set its CurrentItem via MoveCurrentTo() or MoveCurrentToFirst():
myCollectionView.MoveCurrentTo(someItem);
...
myCollectionView.MoveCurrentToFirst();

Also, set IsSynchronizedWithCurrentItem on your ListView:
<ListView IsSynchronizedWithCurrentItem="True" ...

Detect when filter is applied
When the filter is evaluated, the collection view is refreshed which in turn resets the collection. To detect this, listen for the CollectionChanged event and look for the NotifyCollectionChangedAction.Reset flag. Please refer to the CollectionView source code for more details.


text:
Q: The best practice for getting list of items in controller action in Symfony2. See examples below I start to create a RESTFul API using Symfony2 framework. It will return data only in JSON format. I'm trying to create a method in action controller that returns a list of users. The problem is that my code is too excess and is not elegant. I think that I do something wrong because simple SQL queries will be more shorter and be clearer than my code.
My method should get 4 input parameters from URL: limit, offset, sort field and sort direction. The output should be a JSON with array of users. I want to configure the fields in JSON using Symfony2 serializers. And I want to return total quantity of users in "X-Total-Count" header.
As I understood it is better to use FOSRestBundle. So, I tried this:
<?php

namespace AppBundle\Controller;

use FOS\RestBundle\Controller\FOSRestController;
use Symfony\Component\HttpFoundation\Request;
use FOS\RestBundle\Controller\Annotations;
use FOS\RestBundle\Request\ParamFetcherInterface;

class UserController extends FOSRestController
{
    /**
     * List all notes.
     *
     * @Annotations\QueryParam(name="_page", requirements="\d+", default=1, nullable=true, description="Page number.")
     * @Annotations\QueryParam(name="_perPage", requirements="\d+", default=30, nullable=true, description="Limit.")
     * @Annotations\QueryParam(name="_sortField", nullable=true, description="Sort field.")
     * @Annotations\QueryParam(name="_sortDir", nullable=true, description="Sort direction.")
     *
     * @Annotations\View()
     *
     * @param Request               $request      the request object
     * @param ParamFetcherInterface $paramFetcher param fetcher service
     *
     * @return array
     */
    public function getUsersAction(Request $request, ParamFetcherInterface $paramFetcher)
    {
        $sortField = $paramFetcher->get('_sortField');
        $sortDir = $paramFetcher->get('_sortDir');
        $page = $paramFetcher->get('_page');
        $limit = $paramFetcher->get('_perPage');

        $orderBy = null;
        if ($sortField && $sortDir) {
            $orderBy = [
                $sortField => $sortDir
            ];
        }
        $offset = ($page - 1) * $limit;

        $repository = $this->getDoctrine()
            ->getRepository('AppBundle:User');
        $users = $repository->findBy([], $orderBy, $limit, $offset);

        return $users;
    }
    ...
}

I think that this code is good because it is short and I can use serializer. And I can configure wich fields should be in response. But in this example I don't have a response object and I can't set "X-Total-Count" header. Also I don't know how to get total rows quantity.
I tried another one case:
<?php

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\JsonResponse;
use FOS\RestBundle\Controller\FOSRestController;
use Symfony\Component\HttpFoundation\Request;
use FOS\RestBundle\Controller\Annotations;
use FOS\RestBundle\Request\ParamFetcherInterface;
use Doctrine\ORM\Tools\Pagination\Paginator;

class UserController extends FOSRestController
{
    /**
     * List all users.
     *
     * @Annotations\QueryParam(name="_page", requirements="\d+", default=1, nullable=true, description="Page number.")
     * @Annotations\QueryParam(name="_perPage", requirements="\d+", default=30, nullable=true, description="Limit.")
     * @Annotations\QueryParam(name="_sortField", nullable=true, description="Sort field.")
     * @Annotations\QueryParam(name="_sortDir", nullable=true, description="Sort direction.")
     *
     * @param Request               $request      the request object
     * @param ParamFetcherInterface $paramFetcher param fetcher service
     *
     * @return array
     */
    public function getUsersAction(Request $request, ParamFetcherInterface $paramFetcher)
    {
        $sortField = $paramFetcher->get('_sortField');
        $sortDir = $paramFetcher->get('_sortDir');
        $page = $paramFetcher->get('_page');
        $limit = $paramFetcher->get('_perPage');
        $offset = ($page - 1) * $limit;

        $em = $this->getDoctrine()->getEntityManager();
        $qb = $em->createQueryBuilder();

        $qb->select('u')
            ->from('AppBundle:User', 'u');

        if ($sortField && $sortDir) {
            $qb->orderBy('u.' . $sortField, $sortDir);
        }

        $query = $qb->getQuery();

        $query->setFirstResult($offset)
            ->setMaxResults($limit);

        $paginator = new Paginator($query);
        $totalCount = $paginator->count();

        $users = $query->getResult();

        $response = new JsonResponse($users);
        $response->headers->set('X-Total-Count', $totalCount);
        return $response;
    }
    ...
}

In this case I have a response object, I can set a "X-Total-Count" header. I can get total rows quantity using Paginator. But I can't use serializer like in previous example. And I think that this code is too excess and is not elegant. I use query builder, query, paginator just for getting a list of users.
Please, tell me how to get the list of users using simple, elegant code.

A: Instead of just returning $users like in the first code sample, you can do it like this:
$view = $this
    ->view($users, 200);
    ->setHeader('X-Total-Count', $totalCount);
return $this->handleView($view);

Also you could create your repository that extends base repository, and move your pagination logic there. That way you controller would be very thin.


text:
Q: System.Uri("") in default browser? I am using special program where it loads some url imagine it like window with automatically load www.google.com - program starts and it load the site - BUT when you click on some links in the program window it opens in default browser - how it can be opened in default browser - I am using this code:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
Inherits System.Windows.Forms.Form

<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
    Try
        If disposing AndAlso components IsNot Nothing Then
            components.Dispose()
        End If
    Finally
        MyBase.Dispose(disposing)
    End Try
End Sub

Private components As System.ComponentModel.IContainer
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
    Me.components = New System.ComponentModel.Container
    Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Form1))
    Me.WB = New System.Windows.Forms.WebBrowser
    .....
    .....

Me.WB.Url = New System.Uri("http://www.google.com/", System.UriKind.Absolute)

Using Visual Basic 2008

A: If I understand your question correctly (let me know if I am wrong), you are asking how to open the system default browser on a specific URL. This can be achieved like this:
Process.Start("http://www.example.com/")

If the path is stored in a Uri object, you will need to use its ToString() method:
Process.Start(someUri.ToString())


text:
Q: Load PDF document with PDF-LIB on Node gives "No PDF header found" Im loading a PDF document I have to modify on the fly with PDF-lib.
const { PDFDocument } = require('pdf-lib');

The PDF file is built with Acrobat and its called dental_insurance.pdf.
I tried to load the file the following ways:
const pdfDoc = await PDFDocument.load("/documents/cards/dental_insurance.pdf")

const pdfDoc = await PDFDocument.load("C:/Website/test/desk_routes/documents/cards/dental_insurance.pdf")

const pdfDoc = await PDFDocument.load("./documents/cards/dental_insurance.pdf")

const pdfDoc = await PDFDocument.load("../documents/cards/dental_insurance.pdf")

But no matter how I set the route where the file is located, I get this error:

(node:15196) UnhandledPromiseRejectionWarning: Error: Failed to parse
PDF document (line:4 col:2 offset=27): No PDF header found

I checked at PDF-lib documentation, they only state the following to load a file:
const pdfDoc = await PDFDocument.load("...")

I dont believe the problem is on the PDF file since I get the very same error even if I enter a file that doesn't exist:
const pdfDoc = await PDFDocument.load("blablabla.pdf")

Thanks.

A: Per the documentation, PDFDocument.load() accepts a string which is the contents of the pdf file, not the name.
const fs = require('fs/promises');

const pdfData = await fs.readFile('./documents/cards/dental_insurance.pdf');

const pdfDoc = await PDFDocument.load(pdfData);


text:
Q: finding the smallest number $n$ such that $n!=n(n+1)(n+2)(n+3)$ What is the smallest number $n$ such that $n!=n(n+1)(n+2)(n+3)$?
How will I solve this type of problems?

A: Okay... Is there only one solution?  Well, yeah... because $n!$ increases by a factor of $(n+1)!/n! = n+1$ as $n$ increases by one, while $n(n+1)(n+2)(n+3)$ only increases by $(n+1)(n+2)(n+3)(n+4)/n(n+1)(n+2)(n+3) = (n+4)/n = 1 + 4/n$.  As $n!$ increases faster for $n > 2$ there is at most one solution.
(Unless there is a solution for $n = 1$ or $0$ which obviously there isn't.)
So.....  Let's start.
$n! = n(n+1)(n+2)(n+3) \iff (n-1)! = (n+1)(n+2)(n+3)$
So $(n-4)!(n-3)(n-2)(n-1) = (n+1)(n+2)(n+3)$
$(n+1)(n+2)(n+3) = n^3 + 6n^2 + 11n + 6$and $(n-1)(n-2)(n-3) = n^3 - 6n^2 + 11n - 6$
So $(n-4)!(n^3 - 6n^2 + 11n-6) = n^3 + 6n^2 + 11n + 6$
So $[(n-4)!-1](n^3 + 11n) =[(n-4)!+1](6n^2 + 6)$
$\frac{(n-4)! - 1}{(n-4)! + 1} = 6\frac{n^2+1}{n^3+11n}$
$\frac{(n-4)!+1}{(n-4)! + 1}- \frac{2}{(n-4)! + 1} = 6(\frac{n^2+11}{n^3+11n}- \frac{10}{n^3+11n})$.
$1 - idgybit = 6\frac 1 n - oodgybit$
So $n \approx 6$.
Iff $n=6$
$1 - \frac 2 3 = 1 - \frac{10}{36+11}$... Mmm.  not quite.
Iff $n = 7$
$1 - \frac 2{3! + 1} = 6/7 - \frac{60}{7^3 + 77}$
$1 - 2/7 = 6/7[1 - 10/(49 + 11)]$
$5/7 = 6/7[1 - 1/6] = 6/7*5/6 = 5/7$.  So that does it.
$n = 7$ is the only solution.