text:
Q: Unable to sort a mat-table with MatSort I am trying to enable sorting on a mat-table using matSort.
Unfortunately I cannot get the sorting to work. I have tried following the instructions in the documentation on Angular Material but I cannot figure out what's wrong.
Here is my code:
Thanks alot in advance!
order-details.component.html
    <mat-table [dataSource]="dataSource" matSort>

        <ng-container matColumnDef="customerNumber">
            <mat-header-cell *matHeaderCellDef mat-sort-header>CustomerNumber</mat-header-cell>
            <mat-cell *matCellDef="let row"> {{row.customerNumber}} </mat-cell>
        </ng-container>

        <ng-container matColumnDef="customerName">
            <mat-header-cell *matHeaderCellDef mat-sort-header>CustomerName</mat-header-cell>
            <mat-cell *matCellDef="let row"> {{row.customerName}} </mat-cell>
        </ng-container>

        <ng-container matColumnDef="orderNumber">
            <mat-header-cell *matHeaderCellDef mat-sort-header>OrderNumber</mat-header-cell>
            <mat-cell *matCellDef="let row"> {{row.orderNumber}} </mat-cell>
        </ng-container>

        <ng-container matColumnDef="orderAmount">
            <mat-header-cell *matHeaderCellDef mat-sort-header>OrderAmount</mat-header-cell>
            <mat-cell *matCellDef="let row"> {{row.orderAmount}} </mat-cell>
        </ng-container>

        <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
        <mat-row *matRowDef="let row; columns: displayedColumns;">
        </mat-row>
    </mat-table>
</div>

order-details.component.ts
import { Component, OnInit, Inject, ViewChild } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA, MatTableDataSource, MatSort } from '@angular/material';
import { Order } from 'src/app/models/order.model';
import { MinimalUser } from './../../../models/minimal-user.model';

@Component({
    selector: 'order-details',
    templateUrl: './order-details.component.html',
    styleUrls: ['./order-details.component.scss']
})
export class OrderDetailsComponent implements OnInit {
    displayedColumns = ['customerNumber', 'customerName', 'orderNumber', 'orderAmount'];
    dataSource: MatTableDataSource<Order>;
    @ViewChild(MatSort) sort: MatSort;
    loadingIndicator: boolean;

    constructor(public dialogRef: MatDialogRef<OrderDetailsComponent>,
        @Inject(MAT_DIALOG_DATA) public data: { orders: Order[], user: MinimalUser }) {
         }

    ngOnInit() {
        this.dataSource = new MatTableDataSource(this.data.orders);
        this.dataSource.sort = this.sort;;
    }

}

A: Please read the documentation  you are missing <th> and <td> tags
    <ng-container matColumnDef="customerNumber">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>CustomerNumber </th>
        <td mat-cell *matCellDef="let row"> {{row.customerNumber}} </td>
    </ng-container>

A: Import MatSortModule in imports list in app.module.ts to
imports: [
    BrowserModule,
    MatTableModule,
    MatSortModule
  ],


text:
Q: How to pass variables to Custum view after 1rst onDraw() I've been searching for this for a very long time but nothing I found was really helpful... I have an layout with a customView, which gets drawn when the layout is loaded. So in my init() in the Activity I start an TCP-Connection to my Server which returns an ArrayList. I want that ArrayList to be passed throw to the onDraw() where I work with its values. My problem is that I can call a method that sets a local variable to the new value but because of some reason the onDraw() method still uses the empty ArrayList which isnt filled. I think that the code explains it better... Is that the right way to do it or is my approch at first place wrong ?
HistoryActivity:
public class HistoryActivity extends AppCompatActivity {

private ListView history_List;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_history);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    initialize();
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
    finish();
    return true;
}

private void initialize(){
    history_List = (ListView) findViewById(R.id.history_List);
    new TCP_Client(new TCP_Client.AsyncResponse() {
        @Override
        public void processFinish(String[] output) {
            ArrayList<String[]> day_Averrage_History = new ArrayList<String[]>();
            for(String encoded_Array:output){
                day_Averrage_History.add(Encoder.unserialize(encoded_Array));
            }
            Diagramm_Builder diagramm_builder = new Diagramm_Builder(HistoryActivity.this);
            diagramm_builder.set_Drawing_Parameters(day_Averrage_History);//Here I pass the variable
            diagramm_builder.invalidate();
        }
    }

    ).execute(new String[]{"r","dah","TecHFreaKAV"});
}

}

DiagrammBuilder:
public class Diagramm_Builder extends View {

public Context ctx;
private ArrayList<String[]> parameters;

public Diagramm_Builder(Context context){
    super(context);
}

public Diagramm_Builder(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

public void set_Drawing_Parameters(ArrayList<String[]> given_Parameters){
    parameters = given_Parameters;
}

public Diagramm_Builder(Context context, AttributeSet attrs) {
    super(context, attrs);
    ctx = this.getContext();
}

public ArrayList<String[]> get_Drawing_Parameters(){
    try {
        Log.e("Message", "Lenght = " + this.parameters.size());
    }catch(NullPointerException e){
        Log.e("Message","Lenght = 0");
    }
    return parameters;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if(get_Drawing_Parameters() == null) {
        Rect test_rect = new Rect();
        test_rect.set(1, 1, canvas.getWidth(), canvas.getHeight());
        Paint color = new Paint();
        color.setColor(Color.DKGRAY);
        color.setStyle(Paint.Style.FILL);
        canvas.drawRect(test_rect, color);
    }else{
        Log.e("Message","Recived Array");
    }

}

}

The Consule outputs two times E:/Message: Length = 0 which means that the ArrayList does not arrive...
I would be very grateful for any help ;-)

A: I solved the problem with just seting a global Varibale in my HistoryActivity and call setContentView() after the,which gave me the opertunity to just call in onDraw() HistoryActivity.ArrayList

redpajama_set_name: RedPajamaStackExchange


text:
Q: GCC infers pass-by-value copy assignment with jsoncpp const Descriptor* descriptor_ptr = msg.GetDescriptor();
const Reflection* reflection_ptr = msg.GetReflection();
const FieldDescriptor* field_ptr = descriptor_ptr->field(i);
Json::Value value;

if (field_ptr->cpp_type() == FieldDescriptor::CPPTYPE_UINT32)
{
    value[field_ptr->name()] = reflection_ptr->GetUInt32(msg, field_ptr);
}

In our case, we tried to build a shared lib with a proto to json function
The linked app would crash with no core dump and we got output in gdb as
Inferior 1 (process xxx) exited with code 0177

and _dl_signal_error frame.
Code line resulted in the error was
value[field_ptr->name()] = reflection_ptr->GetUInt32(msg, field_ptr);

and we found that ldd -r shows the shared lib has undefined symbol pointing to _ZN4Json5ValueaSES0_, demangled as Json::Value::operator=(Json::Value) by c++filt
It surprised us a lot because there was no pass-by-value copy assignment function in jsoncpp's headers or source code. We tried recompile it with latest release of jsoncpp and the problem remains
However, when we make a stand alone jsoncpp demo, it works fine and ldd -r no longer shows the undefined symbol output
We guess it's gcc which interprets and chooses a non-existent copy assignment operator. It may be relevant to copy emision or other optimization, how can we fix it? or how to explicitly use a valid copy assignment operator?
Linux version we use is Linux version 2.6.32-696.el6.x86_64 CentOS release 6.9 (Final), gcc version is gcc (GCC) 9.1.0
compiling options are
C_FLAGS          = -Wall -D_GNU_SOURCE  -Wno-deprecated -fPIC -g -pipe -D_DEBUG -Woverloaded-virtual -Wpointer-arith -fno-strict-aliasing -std=c++17

and link with jsoncpp static lib

A: The by-value assignment operator has been replaced by by-reference assignment operators starting with version 1.9.0 of the library, see https://github.com/open-source-parsers/jsoncpp/commit/0c1cc6e1a373dc58e2599ec7dd68b2e6b863990a#.
The assignment operators are not defined inline and so a pre-1.9.x version of the library will contain a definition of the by-value version, while a 1.9.x version will not.
It is likely that you are either compiling against the headers of a pre-1.9.x version while trying to link/load a 1.9.x version of the library or the other way around.
According to the readme page on the github major versions (not sure if only 1.x or 1.9.x is meant) are supposed to be binary-compatible, but I don't think that this change is a binary-compatible change.
There is a closed issue on the project's github describing the same problem without conclusive answer: https://github.com/open-source-parsers/jsoncpp/issues/738


text:
Q: How to make Automated Dynamic Breadcrumbs with AngularJS + Angular UI Router One key component to web applications is breadcrumbs/navigation. With Angular UI Router, it would make sense to put the breadcrumb metadata with the individual states, rather than in your controllers. Manually creating the breadcrumbs object for each controller where it's needed is a straight-forward task, but it's also a very messy one.
I have seen some solutions for automated Breadcrumbs with Angular, but to be honest, they are rather primitive. Some states, like dialog boxes or side panels should not update the breadcrumbs, but with current addons to angular, there is no way to express that.
Another problem is that titles of breadcrumbs are not static. For example, if you go to a User Detail page, the breadcrumb title should probably be the user's Full Name, and not a generic "User Detail".
The last problem that needs to be solved is using all of the correct state parameter values for parent links. For example, if you're looking at a User detail page from a Company, obviously you'll want to know that the parent state requires a :companyId.
Are there any addons to angular that provide this level of breadcrumbs support? If not, what is the best way to go about it? I don't want to clutter up my controllers - I will have a lot of them - and I want to make it as automated and painless as possible.
Thanks!

A: I did solve this myself awhile back, because nothing was available. I decided to not use the data object, because we don't actually want our breadcrumb titles to be inherited by children. Sometimes there are modal dialogs and right panels that slide in that are technically "children views", but they shouldn't affect the breadcrumb. By using a breadcrumb object instead, we can avoid the automatic inheritance.
For the actual title property, I am using $interpolate. We can combine our breadcrumb data with the resolve scope without having to do resolves in a different place. In all of the cases I had, I just wanted to use the resolve scope anyway, so this works very well.
My solution also handles i18n too.
$stateProvider
    .state('courses', {
        url: '/courses',
        template: Templates.viewsContainer(),
        controller: function(Translation) {
            Translation.load('courses');
        },
        breadcrumb: {
            title: 'COURSES.TITLE'
        }
    })
    .state('courses.list', {
        url: "/list",
        templateUrl: 'app/courses/courses.list.html',
        resolve: {
            coursesData: function(Model) {
                return Model.getAll('/courses');
            }
        },
        controller: 'CoursesController'
    })
    // this child is just a slide-out view to add/edit the selected course.
    // It should not add to the breadcrumb - it's technically the same screen.
    .state('courses.list.edit', {
        url: "/:courseId/edit",
        templateUrl: 'app/courses/courses.list.edit.html',
        resolve: {
            course: function(Model, $stateParams) {
                return Model.getOne("/courses", $stateParams.courseId);
            }
        },
        controller: 'CourseFormController'
    })
    // this is a brand new screen, so it should change the breadcrumb
    .state('courses.detail', {
        url: '/:courseId',
        templateUrl: 'app/courses/courses.detail.html',
        controller: 'CourseDetailController',
        resolve: {
            course: function(Model, $stateParams) {
                return Model.getOne('/courses', $stateParams.courseId);
            }
        },
        breadcrumb: {
            title: '{{course.name}}'
        }
    })
    // lots more screens.

I didn't want to tie the breadcrumbs to a directive, because I thought there might be multiple ways of showing the breadcrumb visually in my application. So, I put it into a service:
.factory("Breadcrumbs", function($state, $translate, $interpolate) {
    var list = [], title;

    function getProperty(object, path) {
        function index(obj, i) {
            return obj[i];
        }

        return path.split('.').reduce(index, object);
    }

    function addBreadcrumb(title, state) {
        list.push({
            title: title,
            state: state
        });
    }

    function generateBreadcrumbs(state) {
        if(angular.isDefined(state.parent)) {
            generateBreadcrumbs(state.parent);
        }

        if(angular.isDefined(state.breadcrumb)) {
            if(angular.isDefined(state.breadcrumb.title)) {
                addBreadcrumb($interpolate(state.breadcrumb.title)(state.locals.globals), state.name);
            }
        }
    }

    function appendTitle(translation, index) {
        var title = translation;

        if(index < list.length - 1) {
            title += ' > ';
        }

        return title;
    }

    function generateTitle() {
        title = '';

        angular.forEach(list, function(breadcrumb, index) {
            $translate(breadcrumb.title).then(
                function(translation) {
                    title += appendTitle(translation, index);
                }, function(translation) {
                    title += appendTitle(translation, index);
                }
            );
        });
    }

    return {
        generate: function() {
            list = [];

            generateBreadcrumbs($state.$current);
            generateTitle();
        },

        title: function() {
            return title;
        },

        list: function() {
            return list;
        }
    };
})

The actual breadcrumb directive then becomes very simple:
.directive("breadcrumbs", function() {
    return {
        restrict: 'E',
        replace: true,
        priority: 100,
        templateUrl: 'common/directives/breadcrumbs/breadcrumbs.html'
    };
});

And the template:

            {{breadcrumb.title | translate}}
            {{breadcrumb.title | translate}}

From the screenshot here, you can see it works perfectly in both the navigation:

As well as the html <title> tag:

PS to Angular UI Team: Please add something like this out of the box!

A: I made a Angular module which generate a breadcrumb based on ui-router's states. All the features you speak about are included (I recently add the possibility to ignore a state in the breadcrumb while reading this post :-) ) :
Here is the github repo
It allows dynamic labels interpolated against the controller scope (the "deepest" in case of nested/multiple views).
The chain of states is customizable by state options (See API reference)
The module comes with pre-defined templates and allows user-defined templates.

A: I'd like to share my solution to this. It has the advantage of not requiring anything to be injected into your controllers, and supports named breadcrumb labels, as well as using resolve: functions to name your breadcrumbs.
Example state config:
$stateProvider
    .state('home', {
        url: '/',
        ...
        data: {
            displayName: 'Home'
        }
    })
    .state('home.usersList', {
        url: 'users/',
        ...
        data: {
            displayName: 'Users'
        }
    })
    .state('home.userList.detail', {
        url: ':id',
        ...
        data: {
            displayName: '{{ user.name | uppercase }}'
        }
        resolve: {
            user : function($stateParams, userService) {
                return userService.getUser($stateParams.id);
            }
        }
    })

Then you need to specify the location of the breadcrumb label (displayname) in an attribute on the directive:
<ui-breadcrumbs displayname-property="data.displayName"></ui-breadcrumbs>

In this way, the directive will know to look at the value of $state.$current.data.displayName to find the text to use.
$interpolate-able breadcrumb names
Notice that in the last state (home.userList.detail), the displayName uses the usual Angular interpolation syntax {{ value }}. This allows you to reference any values defined in the resolve object in the state config. Typically this would be used to get data from the server, as in the example above of the user name. Note that, since this is just a regular Angular string, you can include any type of valid Angular expression in the displayName field - as in the above example where we are applying a filter to it.
Demo
Here is a working demo on Plunker: http://plnkr.co/edit/bBgdxgB91Z6323HLWCzF?p=preview
Code
I thought it was a bit much to put all the code here, so here it is on GitHub: https://github.com/michaelbromley/angularUtils/tree/master/src/directives/uiBreadcrumbs

A: I do not believe there is built in functionality, but all the tools are there for you, take a look at the LocationProvider.  You could simply have navigation elements use this and whatever else you want to know just inject it.
Documentation

A: After digging deep into the internals of ui-router I understood how I could create a breadcrumb using resolved resources.
Here is a plunker to my directive.
NOTE: I couldn't get this code to work properly within the plunker, but the directive works in my project. routes.js is provided merely for example of how to you can set titles for your breadcrumbs.

A: Thanks for the solution provided by @egervari. For those who need add some  $stateParams properties into custom data of breadcrumbs. I've extended the syntax {:id} for the value of key 'title'.
.state('courses.detail', {
    url: '/:courseId',
    templateUrl: 'app/courses/courses.detail.html',
    controller: 'CourseDetailController',
    resolve: {
        course: function(Model, $stateParams) {
            return Model.getOne('/courses', $stateParams.courseId);
        }
    },
    breadcrumb: {
        title: 'course {:courseId}'
    }
})

Here is an Plunker example. FYI.


text:
Q: How do i find the actual outliers in the boxplot in R I have a boxplot that looks like this:

From what I understand about outliers, the dots that are above the maximum line are outliers but how do I find the points that are actually outliers as I don't think that all the supposed outliers are actually outliers?

A: According to this post which matches my recollection, the whiskers are calculated as (pseudocode):
upper whisker = min(max(x), Q_3 + 1.5 * IQR)
lower whisker = max(min(x), Q_1 – 1.5 * IQR)

Any points outside the whiskers are deemed to be outliers.
If you want to inspect outlier points, you can assign the output of boxplot and look at the out field as the help page suggests:

 out: the values of any data points which lie beyond the extremes
      of the whiskers.

Something like
box <- boxplot(rnorm(100))
box$out

A: Use functionality of boxplot object:
set.seed(59737908)

x <- c(rnorm(10), 10, -55)

outliers <- boxplot(x, plot = F)$out
outliers
#[1]  10 -55

P.S. @alan was first


text:
Q: Xamarin Forms save exceptions in a file I want to be able to view and save in a file the exceptions thrown by my app when it crashes. Is there a tutorial on this topic? I've seen the Advanced App Lifecycle Demos and the crash handling there, but I don't really understand how to implement it in my app.

A: Getting the exception that caused an entire crash is not easy to archieve on your own. Luckily there's a way to get the exception using Xamarin Insights. It's free to use for Xamarin customers.
You simply need to get an API key for your app on the website, add the NuGet package Xamarin.Isights and initialize it as described here in your app.
Then you will receive crash reports everytime the user starts your app after a crash.
If you encounter startup crashes then you can use these lines of code to initialize Xamarin.Insights to receive reports for them:
Insights.HasPendingCrashReport += (sender, isStartupCrash) =>
{
  if (isStartupCrash) {
    Insights.PurgePendingCrashReports().Wait();
  }
};
Insights.Initialize("Your API Key");

A: You'd be better off using Xamarin Insights, an application logging framework that will automatically log crashes and unhandled exceptions for you.

A: In our team we didn't enjoyed the Xamarin Insights so we use such a construction:
    public async Task SafeCall(Func<Task> action)
    {
        var workedWrong = false;
        try
        {
            await action();
        }
        catch (Exception e)
        {
            workedWrong = true;
            // Here you copy all the data you need.
        }

        if (workedWrong)
        {
            // Here you show the notification that something went wrong and write all the relevant information to the file (you can find how to do it in official Xamarin manual).
        }
    }

Although it doesn't catch the iOS exceptions.


text:
Q: How to round down to half value I'm trying to round like follows.
1.1 -> 1
1.2 -> 1
.
1.4 -> 1
1.5 -> 1.5
1.6 -> 1.5
.
.
1.9 -> 1.5
2 -> 2

How can i achieve this? I tried Math.Round(value), Math.Round(value, 1), Math.Round(value,MidpointRounding.AwayFromZero) Nothing seem to achieve what i need. Any help is highly appreciated

A: One can try:
decimal HalfRound(decimal value)
{
    var floor = Math.Floor(value);

    return floor += (value - floor) < 0.5M ? 0.0M : 0.5M;
}

Lets test above function for some of OP's data:
Console.WriteLine($"1.1 => {HalfRound(1.1M)}");
Console.WriteLine($"1.2 => {HalfRound(1.2M)}");
Console.WriteLine($"1.4 => {HalfRound(1.4M)}");
Console.WriteLine($"1.5 => {HalfRound(1.5M)}");
Console.WriteLine($"1.6 => {HalfRound(1.6M)}");
Console.WriteLine($"1.9 => {HalfRound(1.9M)}");
Console.WriteLine($"2.0 => {HalfRound(2.0M)}");
Console.WriteLine($"3.5 => {HalfRound(3.5M)}");
Console.WriteLine($"3.6 => {HalfRound(3.6M)}");
Console.WriteLine($"3.9 => {HalfRound(3.9M)}");

Result:
//1.1 => 1.0
//1.2 => 1.0
//1.4 => 1.0
//1.5 => 1.5
//1.6 => 1.5
//1.9 => 1.5
//2.0 => 2.0
//3.5 => 3.5
//3.6 => 3.5
//3.9 => 3.5


text:
Q: AngularJS directive modify loaded template in link or compile function I'm loading a template inside my directive and I'd like to modify it based on some given attributes. How can I do that ?
Here is my directive :
directives.directive("myDirective", function($http, $compile){
    return {

    restrict: 'E',

    scope : {
    },

    templateUrl: 'lib/directives/myTemplate.html',

    link : function(scope, element, attrs) {

        // I need template to contain myTemplate.html code, how can I do that ?
        var trThead = template.find("thead").find("tr");

        var headers = scope.attrs["headers"];
        for (var i = 0; i < headers.length; i++) {
            trThead.append('' + headers[i] + '	');
        }

        element.append(template);

    }
  };
});

I don't want to define the HTML code directly in my directive since it's too big.

A: As answered by naeramarth7, the template set in the template or templateUrl parameters can be accessed using the element parameter of the link/compile method :
compile : function(element, attrs) {

}

link : function(scope, element, attrs) {

}


text:
Q: Flexbox - screen splitting on small screens I have found an example on Codepen which splits the screen in two halves.
How to make the example divide the screen vertically when the height is smaller than the width? I want to utilize the screen area on small devices better, because in my opinion a narrow long rectangle looks worse than a nearly square rectangle.
.leftside, .rightside {
height:50vh;
width:100%;
color:#fff;
font-size:40px;
}

@media screen and (min-width:768px)
{
.leftside, .rightside {
    height:100vh;
}
}

A: You can do this with aspect-ratio -> https://developer.mozilla.org/en-US/docs/Web/CSS/@media/aspect-ratio

html,
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

.container {
  display: flex;
  border: 5px solid green;
  flex-flow: row nowrap;
  height: 100%;
}

.container>div {
  flex: 1;
  height: 100vh;
  color: white;
  font-size: 40px;
}

.container>.leftside {
  background: red;
}

.container>.rightside {
  background: blue;
}

@media (min-aspect-ratio: 9/8) {
  .container {
    display: flex;
    border: 5px solid yellow;
    flex-flow: column nowrap;
  }
  .container>div {
    height: 50vh;
  }
}

left

right


text:
Q: Is there a way to delete images from the Media Library programatically? I did a custom user profile page for wordpress that lets you update your profile including uploading your custom avatar and save that photo to the Media Library. Is there a way for the a specific avatar to be deleted using it's attachment ID?

A: Use wp_delete_attachment
<?php wp_delete_attachment( $attachment_id ); ?>


text:
Q: Use Parcelable to pass an object from one android activity to another I want to do this
class A extends Activity{
       private class myClass{
       }
       myClass obj = new myClass();

      intent i = new Intent();
      Bundle b = new Bundle();
      b.putParcelable(Constants.Settings, obj); //I get the error The method putParcelable(String, Parcelable) in the type Bundle is not applicable for the arguments (int, A.myClass)
      i.setClass(getApplicationContext(),B.class);
      startActivity(i);
    }

How do I use Parcelable to pass obj to activity B?

A: Create your class and implements Serializable:
private class myClass implements Serializable  {
   }

And do like:
myClass obj = new myClass();
Intent aActivity = (A.this, B.class);
intent.putExtra("object", obj);

On Receiving side:
myClass myClassObject = getIntent().getSerializableExtra("object");

A: As the error suggests, you need to make your class (myClass in this case) implement Parcelable. If you look at the documentation for Bundle, all the putParcelable methods take either a Parcelable or a collection of them in some form. (This makes sense, given the name.) So if you want to use that method, you need to have a Parcelable instance to put in the bundle...
Of course you don't have to use putParcelable - you could implement Serializable instead and call putSerializable.

A: Parcelable is pain in writing code but more cost effective than Serializable. Have a look at the given below link -
Parcelable Vs Serializable


text:
Q: Special Characters like ❷ ❶ ❸ are not storing correctly in SQL even when the type is nVarchar I facing a weird issue in SQL. Im trying to save these characters ❷❶❸ into SQL. But its storing as Question Marks (?). The field  is nVarchar.
This is my update query

update mytable set keywords='key1❶,key2❶,key3❶,key4❶'  where id=50543

A: The column should be created as
CREATE TABLE mytable (columnname NVARCHAR(40) COLLATE SQL_Latin1_General_CP1253_CI_AI)

Then when insert use prefix Unicode character string
INSERT INTO mytable (columnname) VALUES (N'❷❶❸')


text:
Q: Send request with body with openresty lua-resty-http module I am trying to send request via http module lua-resty-http. How I can send request with body data.
I have tried this
hc:connect("127.0.0.1", 82)

dates = ngx.req.get_post_args()

local hc = http:new()

result, errors = hc:request{
    path = requrl,
    method = "POST",
    body = dates,
    headers = {
      ["Host"] = "localhost",
    },
}

Basically I am trying to send a lua table to another server location. And how to capture on that lua table location.
I'd appreciate a detailed explanation.

A: ngx.req.get_post_args() returns a table of key, value pairs. The body argument for the http client's request function must be in a format supported by OpenResty's cosocket send API. This means either a string, or array like table holding strings.
If you want to send a lua table with an HTTP request then you'll need a way to encode it to a string. A common approach is using JSON, and you can do this with the bundled cjson library:
local json = require "cjson"
local dates = ngx.req.get_post_args()

hc:request {
  body = json.encode(dates),
  ...
}


text:
Q: How to set retention days to a logstream with cloudformation or yaml So, I have been working back and forth with this task.
I have AWS CloudWatch logs where I have to apply retention policies to some logstreams of a Loggroup
Loggroup: "My Loggroup"
and inside it I have different logstreams
Logstream-a
Logstream-b
what I want to do, is to set different retention days to each logstream.
Logstream-a = 180 days
Logstream-b = 90 days
I've found that I can set the retention settings to a loggroup in YAML, but I can't do that to a logstream.
CloudWatchLogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName: MyLoggroup
      RetentionInDays: 180

Is there any way to apply retention settings to a LogStream with Python, Cloudformation or YAML?

A: As you already discovered, you can set log retention on LogGroups, but not on LogStreams.
You could use CloudWatch S3 exports to differentiate retention by LogStream indirectly.  What makes S3 exports work for your use case is that export tasks can filter exports by logStreamNamePrefix.
# CloudWatchLogs.Client
response = client.create_export_task(
    taskName='string',
    logGroupName='string',
    logStreamNamePrefix='string', # Export only log streams that match the provided prefix
    fromTime=123,
    to=123,
    destination='string',
    destinationPrefix='string'
)

*

*Set the LogGroup retention days to the shortest retention category.  All logs in CW expire at that time.

*Create export tasks for the LogSteams that belong to the longer retention categories.

*Create expiry lifecycle rules in S3 to automatically delete objects after a set number of days.  Rules can filter by object prefix, which handily corresponds to the log stream names.

*Run the export tasks periodically.


text:
Q: Moving 3D object data into separate XAML file I have a XAML file of some view where a complex 3D model is defined. The problem is that the part defining the model is quite big, it has over 0.5 MB and it's really hard to browse through the file. Is there a way I can move e.g the Model3DGroup into another file and then include it in my main XAML file? I use a SketchUp to XAML converter which creates files with <Model3DGroup xmlns="..." xmlns:x="..."> as their roots, so I'm almost sure it can be done in a convenient way.
My current XAML file looks like this:
<UserControl x:Class="BigAtom.Views.WorkspaceView"
             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:TestProj"
             mc:Ignorable="d"
             d:DesignHeight="278" d:DesignWidth="274">

    <Grid x:Name="RootVisual" Background="Beige" ClipToBounds="True">
        <Canvas Name="DrawingCanvas" Grid.Row="0" Grid.Column="0" Width="0" Height="0" RenderTransform="1,0,0,-1,0,0" Margin="10">
            <Viewport3D Name="Object3D" Width="50" Height="50" Margin="-25,-25" ClipToBounds="False">
                <Viewport3D.Camera>
                    <OrthographicCamera x:Name="CamMain" Position="0 60 100" LookDirection="0 -60 -100"></OrthographicCamera>
                </Viewport3D.Camera>
                <ModelVisual3D>
                    <ModelVisual3D.Content>
                        <DirectionalLight x:Name="DirLightMain" Direction="-1,-1,-1"/>
                    </ModelVisual3D.Content>
                </ModelVisual3D>
                <ModelVisual3D x:Name="MyModel">
                    <ModelVisual3D.Content>
                        <Model3DGroup>
                            <GeometryModel3D>
                                <GeometryModel3D.Geometry>
                                    <MeshGeometry3D Positions="-5.6166 10.4050 153.1136 [very long line]" TextureCoordinates="-5.616612 -10.405044  -3.582495 [very long line]" TriangleIndices="164 17 57 [very long line]"/>
                                </GeometryModel3D.Geometry>
                                <GeometryModel3D.Material>
                                    <DiffuseMaterial Color="White" Brush="#ffffff"/>
                                </GeometryModel3D.Material>
                                <GeometryModel3D.BackMaterial>
                                    <DiffuseMaterial Color="White" Brush="White"/>
                                </GeometryModel3D.BackMaterial>
                            </GeometryModel3D>
                        </Model3DGroup>
                    </ModelVisual3D.Content>
                </ModelVisual3D>
            </Viewport3D>
        </Canvas>
    </Grid>
</UserControl>

and I want to achieve something like this:
<UserControl x:Class="BigAtom.Views.WorkspaceView"
             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:TestProj"
             mc:Ignorable="d"
             d:DesignHeight="278" d:DesignWidth="274">

    <Grid x:Name="RootVisual" Background="Beige" ClipToBounds="True">
        <Canvas Name="DrawingCanvas" Grid.Row="0" Grid.Column="0" Width="0" Height="0" RenderTransform="1,0,0,-1,0,0" Margin="10">
            <Viewport3D Name="Object3D" Width="50" Height="50" Margin="-25,-25" ClipToBounds="False">
                <Viewport3D.Camera>
                    <OrthographicCamera x:Name="CamMain" Position="0 60 100" LookDirection="0 -60 -100"></OrthographicCamera>
                </Viewport3D.Camera>
                <ModelVisual3D>
                    <ModelVisual3D.Content>
                        <DirectionalLight x:Name="DirLightMain" Direction="-1,-1,-1"/>
                    </ModelVisual3D.Content>
                </ModelVisual3D>
                <ModelVisual3D x:Name="MyModel">
                    <ModelVisual3D.Content>
                        <Model3DGroup --- some kind of reference to the file which keeps the 3D model --- />
                    </ModelVisual3D.Content>
                </ModelVisual3D>
            </Viewport3D>
        </Canvas>
    </Grid>
</UserControl>

@edit
McGarnagle's answer is generally OK, but in my case I also have some DataTemplate defined in my UserControl.Resources. Because of this, I had to create such a structure:
<UserControl.Resources>
    <ResourceDictionary>
        <DataTemplate DataType="{x:Type local:SomeType}" x:Key="SomeTypeTemplate">
            ....
        </DataTemplate>
        <ResourceDictionary.MergedDictionaries>
           <ResourceDictionary Source="Models.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

A: I imagine you should be able to use a resource dictionary for this.  Add a file, say, "Models.xaml" with the definitions:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Model3DGroup x:Key="TheModelContent">
        ...
    </Model3DGroup>
</ResourceDictionary>

Then reference the file in your UserControl, and refer to the models using the StaticResource keyword:
<UserControl>
    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Models.xaml" />
            </ResourceDictionary.MergedDictionaries>

            <!-- other resources here -->
        </ResourceDictionary>
    </UserControl.Resources>
    ...

    <ModelVisual3D Content="{StaticResource TheModelContent}">
    ...

</UserControl>


text:
Q: Session support in self-hosted WCF Data Service I created a self-hosted WCF data service and as you can see here, I discovered that it does not support the ASP.Net context (HttpContext.Current is null).
Am I correct if I suppose that session handling is also not available in a self-hosted data service?

A: Session handling is not available in self-hosted WCF Data Services as it utilizies the HttpContext class which relies on ASP.Net context and it is always null in Data Services.
So you have to implement a custom solution to imitate session handling in WCF Data Services.

A: In the self hosted service, you should be able to Use the SessionMode enumeration with the ServiceContractAttribute.SessionMode property to require, allow, or prohibit bindings to use sessions between endpoints that connect to or support the service contract.
For example, if the SessionMode property is set to SessionMode.Allowed and the ServiceBehaviorAttribute.InstanceContextMode property is set to InstanceContextMode.PerSession, a client can use a binding that supports reliable sessions to make repeated calls to the same service object.  If your service supports sessions, you can then use the `ServiceBehaviorAttribute.InstanceContextMode' property to specify the relationship between instances of your service contract implementation and the channel session.
The following links provide good reference information:
http://msdn.microsoft.com/en-us/library/ff183865.aspx
http://msdn.microsoft.com/en-us/library/system.servicemodel.sessionmode.aspx
Regards,


text:
Q: MySQL - Can't find FULLTEXT index matching the column list I saw so many similar question with this same error and the solution is altering the table by adding FULLTEXT to the columns.
But now the problem is I'm writing the query to a VIEW instead of an table. So I can't alter the columns as mentioned in the solution the I gone through.
So how can I solve this issue when it queries to a VIEW.
VIEW:
CREATE OR REPLACE VIEW result AS  select p.f_name AS fullname,
p.experience AS experience,
group_concat(distinct s.name
order by s.name ASC separator ', ') AS skills,
p.location AS location from (personal p left join
reg r on((p.reg_id = r.id)))
left join prof_skill ps on((r.id = ps.reg_id)) left join skills s
on((ps.skill_id = s.id)) group by r.id ;

FULL-TEXT Query:
SELECT `registration_no`, `location`, `skills`, `fullname`, `experience`, `active`
FROM `result`
LEFT JOIN `review` ON `result`.`registration_no` = `review`.`reg_id` AND
`review`.`active` = 0
WHERE ( MATCH (fullname,experience,skills,location)
AGAINST ('+henna' IN BOOLEAN MODE) )
AND (`result`.`active` =0 ) GROUP BY `registration_no`

Structure:

INDEXES:


text:
Q: Does there exist an uncountable number of isolated points? This question arose from my thinking about order-preserving isomorphisms on the Real numbers. These functions must be injections ("one-to-one")
$$a\ne b \implies f(a)\ne f(b)$$
and preserve order
$$a\le b \implies f(a)\le f(b)$$
In other words, I knew that these functions must be strictly increasing, perhaps with a finite number of points with zero slope. For if there were any intervals $(a,b)$ on which the function had zero or decreasing slope, it would no longer be an injection or preserve order: two different inputs would have the same output.
But then I realized that even an infinite, albeit countable, number of points would suffice, for example, a function that is increasing everywhere except at every integer; something like $f(x)=x+sin(x)$. This function's graph looks like a smoothed-out staircase, and its derivative $f^{\prime}(x)=1+cos(x)$ is tangent to the $x$-axis at those points.
So then taking a step further, I wondered if perhaps an uncountable number of points would suffice, provided that these points weren't "together in a straight line", or put more precisely, they didn't make an interval.
My first thought was an uncountable set of irrational numbers within an interval, say, $[1,2]$. This function would be increasing at all rational points, but have zero slope at all irrational points. (There are uncountably many irrational numbers within $[1,2]$.) If such a function exists, and is continuous and differentiable, its derivative would be something like the Dirichlet function:
$$
g^{\prime}(x) =
\begin{cases}
1 &: &x < 1\\
1 &: &x \in [1,2]\cap\mathbb{Q}\\
0 &: &x \in [1,2]-\mathbb{Q}\\
1 &: &x > 2\\
\end{cases}
$$
I'm not sure if that's possible. If it isn't, then the points in my uncountable set must all be isolated, that is, there must exist an $\epsilon$-neighborhood around each point that doesn't contain any other points in the set.
Is it possible to select uncountably many isolated points?

A: For $x\in\mathbb R$ and $\epsilon\gt0$ let $B(x,\epsilon)$ denote the $\epsilon$-neighborhood $(x-\epsilon,x+\epsilon).$ A set $X\subseteq\mathbb R$ is discrete if, for each point $x\in X,$ there is a number $\epsilon\gt0$ such that $B(x,\epsilon)\cap X=\{x\}.$
Every discrete subset of $\mathbb R$ is countable.
Proof. Assume for a contradiction that there is an uncountable discrete set $X\subseteq\mathbb R.$ For $n\in\mathbb N$ let $X_n=\{x\in X:B(x,\frac1n)\cap X=\{x\}\}.$ Then $X=\bigcup_{n\in\mathbb N}X_n,$ so $X_n$ is uncountable for some $n.$
Choose $n\in\mathbb N$ so that $X_n$ is uncountable. Then the sets $B(x,\frac1{2n}),\ x\in X_n$ constitute an uncountable family of pairwise disjoint open intervals, which is impossible.
However, the fact that discrete subsets of $\mathbb R$ are countable seems unrelated to your question about slopes of order-isomorphisms of $\mathbb R'$
There is a strictly increasing continuously differentiable bijection $f:\mathbb R\to\mathbb R$ such that $\{x:f'(x)=0\}$ is uncountable and even has positive Lebesgue measure.
Proof. Let $C$ be a compact nowhere dense subset of $\mathbb R$ with positive Lebesgue measure, e.g., a so-called fat Cantor set. Define
$$g(x)=d(x,C)=\min\{|x-y|:y\in C\},$$
the distance from $x$ to $C,$ and define
$$f(x)=\int_0^xg(t)dt.$$
Since $g$ is continuous and nonnegative, $f$ is continuously differentiable and nondecreasing. In fact, since $C$ is nowhere dense, $\{x:f'(x)\gt0\}$ is everywhere dense, whence $f$ is strictly increasing. Since $f(-\infty)=-\infty$ and $f(+\infty)=+\infty,\ $ $f$ is a bijection. Finally, the set $\{x:f'(x)=0\}=\{x:g(x)=0\}=C$ has positive Lebesgue measure.


text:
Q: Xamarin.Android WearableRecyclerView Is the WearableRecyclerView missing in Xamarin Android Wear Support Libraries 2.0.1?
I updated the Xamarin Android Wear Support Libraries nuget package to the latest version (2.0.1), but i cannot resolve the WearableRecyclerView.

A: it was a broken hint path's in the Wearable support project
Fixed in version 2.0.1.1
https://github.com/xamarin/GooglePlayServicesComponents/releases/tag/Wear-2.0.1.1


text:
Q: OpenGL ES: Framerate and textureatlas I've noticed that the size of a textureatlas do have an inpact of an OpenGL ES 2 application. The size of the atlas is 2048 X 2048 and when using on a Samsung Galaxy S7 the performance is pretty much in line with 60 frames per second. Even 4096 X 4096 will do, though maybe some loss of performance, but not much.
If I now compile and run the same app on a Samsung Galaxy S3 the framerate is really bad if I use 2048 X 2048 of the textureatlas. It takes about 25 ms to draw a frame. But if I decrease the textureatlas to 1024 X 1024 the performance will improve a lot - 60 frames per second.
So is the conclusion that I should use different sizes of the textureatlas depending on device? But exactly how do the size then correlate to device? To screensize maybe? For instance - a screensize of 720 X 1280 I use a 1024 X 1024 textureatlas, and 1440 X 2560 a 2048 X 2048 textureatlas?
Or is there a problem with my source? By now I do not know how to keep track of let say 100 sprites that shares one and the same frameBuffer. Instead Every sprite has its own buffer and in onDRawFrame I make a separate drawcall for each buffer. But I guess bindBuffer is faster than bindTexture?
OR is there a problem how I load the bitmap to the OpenGL? I am using the flag
Bitmap.Config.RGB_565

but no performance increase.
Renderer source
  public MyGLRenderer(Context context) {

    this.context = context;

    nSprites = 75;

    alienUvs = new float[16][12 * nSprites];
    bgUvs = new float[12];
    vertices = new float[18 *nSprites];
    verticesBG = new float[18];

    vertexBuffer= new FloatBuffer[nSprites];
    vertexBufferBG = new FloatBuffer[1];

    // The indices for all textured quads
    indices = new short[nSprites*6];

    uvBufferAlien = new FloatBuffer[16]; // antalet frames

    uvBufferBG = new FloatBuffer[1];

    bufferId = new int[16 + nSprites + 2]; // 16 stycken för aliens, nsprites antal för punkterna

    modulo = 2;

    start = System.currentTimeMillis();

    //slumpa x o y
    xPos = new float[nSprites];
    yPos = new float[nSprites];

    for (int i = 0; i < nSprites; i++) {

        Random r = new Random();
        xPos[i] = (float)(r.nextDouble()-0.5) * 6;
        r = new Random();
        yPos[i] = (float)(r.nextDouble()-0.5) * 6;
    }
}

@Override
public void onSurfaceCreated(GL10 unused, EGLConfig config) {

    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);

    vertexBuffer = GLData.createVertices(nSprites, vertices);
    vertexBufferBG[0] = GLData.createVerticesBG(verticesBG);
    GLData.createUvsData(nSprites, alienUvs, uvBufferAlien);
    uvBufferBG[0] = GLData.createUvsDataBG(bgUvs);
    GLData.createVertexBufferObject(vertexBuffer, vertexBufferBG, nSprites, uvBufferAlien, uvBufferBG, bufferId.length, bufferId);

    createCamera();

    GLES20.glEnable(GLES20.GL_CULL_FACE);

    GLES20.glEnable(GLES20.GL_BLEND);
    GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA);

    // inlästa shaderprogram (källkod i strängform)
    final String vertexShader = getVertexShader();
    final String fragmentShader = getFragmentShader();

    final int vertexShaderHandle = ShaderHelper.compileShader(GLES20.GL_VERTEX_SHADER, vertexShader);
    final int fragmentShaderHandle = ShaderHelper.compileShader(GLES20.GL_FRAGMENT_SHADER, fragmentShader);

    mProgramHandle = ShaderHelper.createAndLinkProgram(vertexShaderHandle, fragmentShaderHandle,
            new String[] {"a_Position",  "a_Color", "a_Normal", "a_TexCoordinate"});

    //skapa texture
    textureHandle = TextureHelper.loadTexture(context);

    GLES20.glUseProgram(mProgramHandle);

    mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgramHandle, "u_MVPMatrix");
    mMVMatrixHandle = GLES20.glGetUniformLocation(mProgramHandle, "u_MVMatrix");
    mTextureCoordinateHandle = GLES20.glGetAttribLocation(mProgramHandle, "a_TexCoordinate");

    mPositionHandle = GLES20.glGetAttribLocation(mProgramHandle, "a_Position");
}

@Override
public void onSurfaceChanged(GL10 unused, int width, int height) {

    game_width = width;
    game_height = height;

    GLES20.glViewport(0, 0, width, height);

    final float ratio = (float) width / height;
    final float left = -ratio;
    final float right = ratio;
    final float bottom = -1.0f;
    final float top = 1.0f;
    final float near = 1f;
    final float far = 20.0f;

    Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
}

@Override
public void onDrawFrame(GL10 unused) {

    int rest = 0;
    if (modulo > 0) {
        rest = frameCntr % modulo;
    }

    if (rest == 0) {
        bitmapIndex++;

    }

    if (bitmapIndex == 16) {
        bitmapIndex = 0;
    }
    frameCntr++;

    //uvs, 16 bilder
    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, bufferId[bitmapIndex]);
    GLES20.glEnableVertexAttribArray(mTextureCoordinateHandle);
    GLES20.glVertexAttribPointer(mTextureCoordinateHandle, mTextureCoordinateDataSize, GLES20.GL_FLOAT, false, 0, 0);

    for (int i = 0; i < nSprites; i++) {

        Matrix.setIdentityM(mModelMatrix, 0);
        Matrix.translateM(mModelMatrix, 0, xPos[i], yPos[i], -8f);

        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, bufferId[16 + i]);
        GLES20.glEnableVertexAttribArray(mPositionHandle);
        GLES20.glVertexAttribPointer(mPositionHandle, mPositionDataSize, GLES20.GL_FLOAT, false, 0, 0);

        draw();

    }

    //mease framerate
    long stop = System.currentTimeMillis();
    nbFrames++;
    if (stop - start >= 1000) {
        System.out.println("" + (float)1000 / nbFrames);
        nbFrames = 0;
        start += 1000;
    }

}

private void draw() {

    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);

    Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);

    GLES20.glUniformMatrix4fv(mMVMatrixHandle, 1, false, mMVPMatrix, 0);

    Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0);

    GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0);

    GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 6);

}

TextureHelper
 public class TextureHelper {

public static int[] loadTexture(Context context) {

    int[] texturenames = new int[1];
    GLES20.glGenTextures(1, texturenames, 0);

    int resId = context.getResources().getIdentifier("aliens", "drawable", context.getPackageName());
    //Bitmap bmp = BitmapDecoder.decodeSampledBitmapFromResource(context.getResources(), resId, 960, 928);
    //Bitmap bmp = BitmapDecoder.decodeSampledBitmapFromResource(context.getResources(), resId, 780, 1280);
    Bitmap bmp = BitmapDecoder.decodeSampledBitmapFromResource(context.getResources(), resId, 2048, 2048);

    GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texturenames[0]);

    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);

    GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bmp, 0);

    bmp.recycle();

    return texturenames;
 }
}

BitmapDecoder (snippet)
   protected static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inPreferredConfig = Bitmap.Config.RGB_565;
    options.inDither = true;
    //options.inScaled = false;

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    return Bitmap.createScaledBitmap( BitmapFactory.decodeResource(res, resId, options), reqWidth, reqHeight, true);
}


text:
Q: AWS CloudFormation deploy overwrite "name" tag? I like not specifying custom names for my resources (because of how CF won't rebuild them if changed)
But it would be nice if I could change the "name" tag at deploy time, for example:
aws cloudformation deploy --template-file dev-cf.yaml --stack-name mystack --region us-east-1 --tags Name=myapp env=dev

Will this work or break anything? Does CF depend on the "name" tag of resources it creates?

A: No, CF does not depend on Name tags, name tags are largely for your/sysadmins benefit. I haven't used many name tags (that's probably not a good thing) throughout a lot of stuff I've written and I've never had issues. The only thing that I can see being a possibility, is that CF does use some values/resource attrs/cf resource names to generate the CF specific names for things, so they may take your Name tags into consideration for generating those, but other than that, you'll be fine.


text:
Q: Firebase Google sign in issue I'm trying to implement google signin using firebase and i'm getting the following error :
Google sign in failed com.google.android.gms.common.api.ApiException: 10:
I have already excecuted the following attempts:

*

*Added SHA1 key to the firebase project settings

*Linked android studio to firebase login

*I have created OAuth 2.0 client ID as webclientid

*I did not publish my project's APK on google play store. which means I did not accidentally generate another SHA1 fingerprint.

here is my code snippet:
package com.example.audiotransacriber;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;

public class LoginActivity extends AppCompatActivity {

    private static final int RC_SIGN_IN = 234;

    //Tag for the logs optional
    private static final String TAG = "data";

    //creating a GoogleSignInClient object
    GoogleSignInClient mGoogleSignInClient;

    //And also a Firebase Auth object
    FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //first we intialized the FirebaseAuth object
        mAuth = FirebaseAuth.getInstance();

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken("302614807658-u9hs4aei98f66gpu21me3p7srj9vgine.apps.googleusercontent.com")
                .requestEmail()
                .build();

        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
        findViewById(R.id.loginbut).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                signIn();
            }
        });
    }
    @Override
    protected void onStart() {
        super.onStart();
        //skipping firebase siginin

        //if the user is already signed in
        //we will close this activity
        //and take the user to profile activity
        if (mAuth.getCurrentUser() != null) {
            finish();
            startActivity(new Intent(this, MainActivity.class));
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //if the requestCode is the Google Sign In code that we defined at starting
        if (requestCode == RC_SIGN_IN) {

            //Getting the GoogleSignIn Task
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                //Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = task.getResult(ApiException.class);

                //authenticating with firebase
                firebaseAuthWithGoogle(account);
            } catch (ApiException e) {
                Log.d(TAG,e.toString());
                Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

        //getting the auth credential
        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);

        //Now using firebase we are signing in the user here
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            Log.d(TAG, "signInWithCredential:success");
                            FirebaseUser user = mAuth.getCurrentUser();

                            Toast.makeText(LoginActivity.this, "User Signed In", Toast.LENGTH_SHORT).show();
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Toast.makeText(LoginActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();

                        }

                        // ...
                    }
                });
    }

    //this method is called on click
    private void signIn() {
        //getting the google signin intent
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();

        //starting the activity for result
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }
}


text:
Q: Chart JS tick options not working for y axis I have been struggling to make a chart.js line chart start at 0 when all of the values are 0. If all of the data of a dataset is 0 the y axis will always show values below 0 which I don't want there.
Here is the example:

    <canvas id="lineChart"></canvas>

As you can see I am changing the options the scales as suggested in the documentation here (apparently there has been migration and this is the way to go in v3, which is what I am using). But the graph still won't start at 0:

Any axis options other than the ticks work correctly.
Any ideas of what I might be doing wrong?

A: You tried to place the beginAtZero in the V2 place, in V3 you have to put it in the root of the scale object like so:

const options = {
  type: 'line',
  data: {
    labels: [1, 2, 3],
    datasets: [{
      label: '# of Votes',
      data: [0, 0, 0],
      borderColor: 'pink'
    }]
  },
  options: {
    scales: {
      y: {
        beginAtZero: true
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);

  <canvas id="chartJSContainer" width="600" height="400"></canvas>

For all changes between V2 and V3 you can read the migration guide


text:
Q: How to have scrapy iterate over archive using url? I'm trying to have a scrapy spider crawl through several pages in an archive, with the goal of opening each individual link and scraping the contents of the linked page. I'm running into some random HTTP 500 errors, which I am trying to skip by simply doing a try-except to skip over those pages returning 500 errors.
The first part of the parse function iterates over the hrefs in the archive page for the pages to scrape using the parse_art function. The second part is to find the next page in the archive and follow through to that page to continue crawling.
I'm trying to change the program to iterate over an initial URL, but can't seem to get it right. Any help would be appreciated.
Running scrapy on Python 3.7.
import scrapy
url_number = 1

class SpiderOne(scrapy.Spider):
    name = 'spider1'
    start_urls = ["http://www.page2bscraped.com/archive?page=%d" % url_number]

    #Parses over the archive page
    def parse(self, response):
        global url_number
        for href in response.xpath(".//a/@href"):
            yield response.follow(href, self.parse_art)

        for href in response.xpath(start_url):
            yield response.follow(start_url, self.parse)
            url_number += 1

    #Parses page contents
    def parse_art(self, response):
    #code goes here

I'm trying to make it so that the spider crawls through the archive by utilizing the url and simply adding 1 to the current archive number, rather than relying on the (unreliable) "Next Page" Xpath.

A: Changing value url_number can't change value in url.
You have to generate full url again
def parse(self, response):
    global url_number

    for href in response.xpath(".//a/@href"):
        yield response.follow(href, self.parse_art)

    url_number += 1
    url = "http://www.page2bscraped.com/archive?page=%d" % url_number

    yield response.follow(url, self.parse)


text:
Q: How to check whether html has a head element with BeautifulSoup. I have  html file:
<html>
<head>
</head>
<body>

</body>

</html>

Using beautifulsoup how can i traverse this html tree , I want to find out whether the head is inside html tag .
I tried this to find html tag , but how to test whether head is inside html now.
invalid = """<html>
<html>

</html>
</html>"""

soup = BeautifulSoup(invalid, 'html.parser')
if soup.find("html") == 1:
    print ('found')
else:
    print 'no html tag'

A: Beautiful soup has a built-in method for this.
from bs4 import BeautifulSoup

invalid = """<html>
<body>
</body>
</html>"""

valid = """<html>
<head>
</head>
<body>
</body>
</html>"""

def hashead(soup):
    if soup.head:
        print 'found head'
    else:
        print 'no head'

badsoup = BeautifulSoup(invalid, 'html.parser')
goodsoup = BeautifulSoup(valid, 'html.parser')

hashead(badsoup)
# >>> no head
hashead(goodsoup)
# >>> found head


text:
Q: Set an "on demand" only job in HangFire In Hangfire, I have successfully set recurring jobs and am able to trigger manually if I want to, thanks to the Web UI and its "trigger" button.
RecurringJob.AddOrUpdate(..);

But I'm willing to set a job that is never fired automatically. Only on demand from the WebUi. Think of it as a set of maintenance task that are triggered only when needed. Manually.
I was thinking of adding a non-reccuring Job in the await state, but was not able to (and it sounds wrong).
Are "On demand only" jobs possible with Hangfire?

A: I use this CRON expression as Never: 0 0 29 2/12000 WED
At midnight, on a 29th of Feb that happens to be a Wednesday, every century.
As @youen found out, this expression yields a later date. "0 0 29 2/12000 MON"

A: Manual or "on demand" have not yet been implemented in the main trunk. However you can use this fork to have that option.
Currently this is marked as Work in Progress in Hangfire's repo and you can use it as this:
BackgroundJob.Stash(() => Console.WriteLine("STASHING"));

A different approach mentioned in one of the comments is to have somewhere in your site a button that enqueues the job:
BackgroundJob.Enqueue(() => Console.WriteLine("Simple!"));

EDIT: 2017/12/28:
Apparently the previous fork wont be merged back since this extension already supports to manually queue jobs:
Hangfire.Core.Dashboard.Management

A: Yes, on demand jobs are entirely possible with hangfire. You can trigger fire-and-forget jobs using the following:
BackgroundJob.Enqueue(
() => Console.WriteLine("Simple!"));

This however won't appear in the hangfire dashboard, but you can use the above snippet in your code (Perhaps after a button click?)

A: In newer Versions of Hangfire you can simply use this:
RecurringJob.AddOrUpdate(() => ..., Cron.Never());

I know thats basically the same soultion stated above, but stackoverflow won't let me comment since my reputation is yet still at nothing...

A: I used this (hangfire 1.7 on .net 4.6.2)
RecurringJob.AddOrUpdate(() => ..., "0 0 31 2 0");

It shows up in the dashboard as:

Next execution N/A


text:
Q: Generate Imagesource with ZXing.Net.Mobile in UWP Problem
I'm trying using ZXing.Net.Mobile to create barcode image in UWP project.
I found this approach.
But in line var wb = result.ToBitmap() as WriteableBitmap; I'm getting result as byte[], which doesn't have method ToBitmap().
Then I found this straight forward code
var writer = new BarcodeWriter();
writer.Format = BarcodeFormat.QR_CODE;
var wb = writer.Write("12345678");
BarcodeImg.Source = wb;

but last lane throws error byte[] cannot be converted to ImageSource
In my naive mind I thought "Ok that should be easy". HA! Everywhere I look I find something similar to this answer.
BitmapImage doesn't have methods BeginInit and EndInit.
Question
How I can convert byte[] to ImageSource or use ZXing to create one?
I'm stuck, again I'm not familiar with UPW. I'll be thankful for each tip.
Update
Ok at this moment situtation looks like this
private async void updateBarcodeImg(string code) {
    var writer = new BarcodeWriter();
    writer.Format = BarcodeFormat.QR_CODE;
    var wb = writer.Write(code) as Byte[];
    try {
        BarcodeImg.Source = await ImageFromBytes(wb);
    } catch (Exception e) {
        Debug.WriteLine(e.Message);
    }
}

public async static Task<BitmapImage> ImageFromBytes(Byte[] bytes) {
    BitmapImage image = new BitmapImage();
    using (IRandomAccessStream stream = bytes.AsBuffer().AsStream().AsRandomAccessStream()) {
        stream.Seek(0);
        await image.SetSourceAsync(stream);
    }
    return image;
}

Update
And in line await image.SetSourceAsync(stream); an exception is throwing "Exception from HRESULT: 0x88982F50". Google says that this is because stream is not set to position 0. But I do it a one line earlier.

A: According to your question, you are going to use ZXing.Net.Mobile to create barcode image. However the sample you've found is using ZXing.Net. They are not the same library.
To use ZXing.Net.Mobile, we need install ZXing.Net.Mobile from NuGet:
Install-Package ZXing.Net.Mobile

And then use following code:
var writer = new ZXing.Mobile.BarcodeWriter
{
    Format = ZXing.BarcodeFormat.QR_CODE,
    Options = new ZXing.Common.EncodingOptions
    {
        Height = 300,
        Width = 300
    },
    Renderer = new ZXing.Mobile.WriteableBitmapRenderer() { Foreground = Windows.UI.Colors.Black }
};
var writeableBitmap = writer.Write("https://developer.microsoft.com/en-us/windows/windows-apps");

QrCodeImg.Source = writeableBitmap;

Also we can use ZXing.Net by install ZXing.Net from NuGet:
Install-Package ZXing.Net

And use the code in the sample:
ZXing.IBarcodeWriter writer = new ZXing.BarcodeWriter
{
    Format = ZXing.BarcodeFormat.QR_CODE,//Mentioning type of bar code generation
    Options = new ZXing.Common.EncodingOptions
    {
        Height = 300,
        Width = 300
    },
    Renderer = new ZXing.Rendering.PixelDataRenderer() { Foreground = Windows.UI.Colors.Black }//Adding color QR code
};
var result = writer.Write("http://www.bsubramanyamraju.blogspot.com ");
var wb = result.ToBitmap() as Windows.UI.Xaml.Media.Imaging.WriteableBitmap;
//Displaying QRCode Image
QrCodeImg.Source = wb;

Please note that we can not use these two libraries at the same time. Please make sure you are using the right code that matches the library you've chosen.


text:
Q: check if form is dirty on state change start using run() function I am using angular ui-router to defines states, i wish to check if form in the current state is dirty and prompt user when user navigates between ui-router states. When user tries to navigate from one state to another i want to check if the form in the current state is pristine and prompt him if he really wants to propagate to next form. I have written a common run function which will take care of this.
angular.module('module')
.run(function ($rootScope, $compile, $templateRequest) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        if (fromState.name.length > 0) {
            $templateRequest(fromState.templateUrl)
                .then(function (html) {
                    var compiledElement = $compile(html)($rootScope);
                    console.log(compiledElement.find('form'));
                });

        }
        if (fromState.name.length > 0 && !confirm('You have unsaved changes, go back?'))
            event.preventDefault();
    });
});

I want to get the scope of the current UI-Router state so that i can check the forms pristine or any other means to know if the form in the current state is dirty or not.


text:
Q: makefile g++: fatal error: no input files I am taking a C++ class right now and in an effort to embrace CS, I installed Linux Mint 15 (Olivia) and have been going through my homework and lectures on the command line and through vim. We recently went over makefile(s) and I am having an issue with g++. My makefile looks like this:
CXX = g++
CXXFLAGS += -pedantic-errors
CXXFLAGS += -g

OBJS =

SRCS = constructors.cpp

HEADERS =

#target: dependencies
#   rule to build
#

constructors: ${OBJS} ${HEADERS}
    ${CXX} ${LDFLAGS} ${OBJS} -o constructors

${OBJS}: ${SRCS}
    ${CXX} ${CXXFLAGS} -c $(@:.o=.cpp)

When I run:
make constructors

I get the following message:
g++   -o constructors
g++: fatal error: no input files
compilation terminated.
make: *** [constructors] Error 4

I have constructors.cpp in the same folder and if I manually compile it, it works perfect. Any suggestions are greatly appreciated.

A:
OBJS =

You... seem to be missing something here. Like some objects to build.


text:
Q: How to mock/stub websocket requests leaving docker container I want to write e2e tests for a dockerized app, that uses websockets, so i need to mock all external requests. I have tried different kinds of proxy servers using the docker env variables
      HTTP_PROXY: http://nginx:8080
      HTTPS_PROXY: http://nginx:8080
      NO_PROXY: localhost,127.0.0.1

But no matter what i do, the websockets requests just go to it's original host and doesn't hit my proxy server.


text:
Q: Ubuntu 18.04 Boots Even Slower After Disabling Networking & Putting 'noresume' to the Boot kernel? I notice how my Ubuntu 18 boots very slow, so much slower than Windows that previously installed on the same machine. I don't use dual-boot, my machine is :
Ubuntu 18.04.3 LTS
Intel® Core™ i7-7700HQ CPU @ 2.80GHz × 8
64-bit, NVIDIA GeForce GTX 950M

NVIDIA was quite problematic and causing boot issues, so I had to put some kernel boot parameters. Now it looks like this :
 GRUB_CMDLINE_LINUX_DEFAULT="quiet splash pci=nomsi pci=noaer
 acpi_enforce_resources=lax intel_pstate=disable acpi_osi=!Windows
 2012"

The default booting time is : 47s.

I followed suggestion from this post : How to diagnose/fix very slow boot on Ubuntu 18.04, while some answers helped other people, it doesn't work on me.
What I have tried :

*

*Added noresume parameter in kernel boot. Literally from the post above, someone cut booting time by 31s !

I upgraded to 18.04 yesterday and I had the same problem (it took 52
seconds to boot). After setting the "noresume" parameter, it took 21
seconds.

Result : (sorry forgot to take a screenshot): 57s (10s slower). Why ?

*Decrease time process for Network and configuring the timeout for Start Job and Stop Jobs by changing :
/etc/systemd/system/network-online.target.wants/networking.service

Change TimeoutStartSec=5min to TimeoutStartSec=5s.
Also,
/etc/systemd/system.conf

change :
DefaultTimeoutStartSec=5s
DefaultTimeoutStopSec=5s

Result : Failed to boot. (Stuck at booting screen)

*Disable Networking during booting :
systemctl disable NetworkManager-wait-online.service

Result : Booting time was 51s (4s slower).

Why did I miss from steps above ? How did my machine ended up booting slower ?
Why did noresume which was supposed to prevent resume partition makes it slower instead ? Any other advice to decrease booting time ?
UPDATE
Following suggestion from WinEunuuchs2Unix, I tried :

*Disable networking as in step (3), and remove the journal flush service and vacuum it by changing :
nano /etc/systemd/journald.conf

change
Storage=auto
SystemMaxUse=50M
SystemMaxFileSize=1G
SystemMaxFiles=5

My original journal disk usage was 2G, now it's down to 200MB. But system-journal-flush.service time doesn't seem to get faster, it's still 11s.
Also, before changing its settings, flushing time was 3.xx s. Now it's 10.xx s instead.

Result, booting time : 52s (5s slower).

*Disabling tor-service :
/etc/default/tor

change to RUN_DAEMON="no"  and run
sudo systemctl disable tor.service

Then added video=SVIDEO-1:d parameter to the boot kernel (following solution from : Long Kernel Boot Segment in 18.04).
And masked systemd-journal-flush.service and the keyboard-setup.service (following solution from : Long boot time Ubuntu 18.04).
Result. Booting time : 45s. (2s faster), but I believe it can be improved.
On the second trial : 47s (no improvement).
I really thought disabling tor-service would give me 5~7s faster booting time since it originally took 10-13s in booting time.

Still confused at how noresume parameter, disabling networking and vacuum logs from journal lead to slower booting time instead. Further suggestions will be appreciated !
UPDATE 2

*Install haveged. Booting time : 49s (2s slower)

Just why.

A: You can probably disable network waiting altogether:

*

*What does NetworkManager-wait-online.service do?
Remove the journal flush service and vacuum it instead:

*

*What is the use of systemd-journal-flush.service?

*Systemd logs (`journalctl`) are too large and slow
Slow snapd times can be sped up by jiggling your mouse at boot time:

*

*Long boot delay on Ubuntu loading/splash screen following regular dist-upgrade on clean SSD install (18.04)


text:
Q: Angular 9 use material icons in css for a list I have a content management system supplying one of our applications with HTML.
I have been asked to change all "ul"s to use a <mat-icon>check_circle_outline</mat-icon> instead of the default "."
The problem is; I can't modify the content so I have to do it through css.
is there a way to add the icon to the css directly instead of using <mat-icon>check_circle_outline</mat-icon> ?
For example, with font-awesome you could do something like
.list-style-checked {
    margin-left: 2.5em;
    padding: 0;

    li {
        position: relative;

        span {
            font-family: "Font Awesome 5 Free";
            position: absolute;
            left: -2em;
            text-align: center;
            width: 2em;
            line-height: inherit;

            &:before {
                content: "\f14a";
            }
        }
    }
}

is there a similar way to do it with angular material?

A: Turns out it's not that different:
.list-style-checked {
  @include bodyLight;
  color: black;
  margin-left: 36px;
  margin-bottom: 0;
  padding: 0;
  list-style: none;

  p {
    margin-bottom: 0;
  }

  li {
    position: relative;
    text-align: left;

    span {
      font-family: 'Material Icons';
      font-size: 24px;
      position: absolute;
      width: 24px;
      height: 24px;
      left: -30px;
      text-align: center;
      line-height: inherit;

      &:before {
        display: block;
        margin-top: -4px;
        content: 'check_circle_outline';
      }
    }
  }
}

&.list-style-strikethrough p {
  text-decoration: line-through;
}


text:
Q: SDL1 and CLion. Where do I begin? I'm moving from MS Visual Studio to JetBrains' CLion, and I'm trying to setup a extremely simple SDL project, but can't get it to build. I'm not using SDL2, but an older version of SDL, as it's required for this project.
What I have so far are these two files: main.cpp and CMakeLists.txt, whose contents I'm pasting below.
main.cpp
#include <SDL.h>

int main(int argc, char *argv[]) {
    return 0;
}

CMakeLists.txt
cmake_minimum_required(VERSION 3.3)
project(simple_project)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(SOURCE_FILES main.cpp)
add_executable(simple_project ${SOURCE_FILES})

include_directories(simple_project PRIVATE "C:/SDL/include")
target_link_libraries(simple_project "C:/SDL/lib/SDL.lib" "C:/temp/jogos/SDL/lib/SDLmain.lib")

So I'm getting the following error:
c:/win-builds/bin/../lib64/gcc/x86_64-w64-mingw32/4.8.3/../../../../x86_64-w64-mingw32/lib/../lib/libmingw32.a(lib64_libmingw32_a-crt0_c.o):crt0_c.c:(.text.startup+0x25): undefined reference to `WinMain'

I'm completely newbie with CMake and MinGW, so I have no idea of what I am doing wrong.

A: add to the CMAKE_CXX_FLAGS: -lmingw32 -lSDLmain -lSDL


text:
Q: What's a "good" setting for PHP ticks with pcntl_signal? I'm running a PHP daemon with a signal handler to do an orderly cleanup and to reconfigure without stopping:
declare(ticks = 5);
function sig_handler($signo)
{
    ...
}
pcntl_signal(SIGHUP, 'sig_handler');
pcntl_signal(SIGINT, 'sig_handler');
...

A tick is an event that occurs for every N low-level tickable statements executed by the parser within the declare block... Not all statements are tickable. Typically, condition expressions and argument expressions are not tickable.

If we declare ticks = 1 then the signal will be checked between most lines of executing PHP code, which seems inefficient.  So,

*

*If we declare ticks = 5, does that mean we have a 4 in 5 chance the signal handler won't be called at all?

*How can I determine a consistent but efficient setting?

*What happens during blocking calls, like database queries? Is the signal thrown away or processed when it returns?

(Side note: The formal specs are even less specific, as this is probably interpreter-dependent.)

A: The following are my findings, I cannot provide you any reference to documentation to prove my statements. However, I learned the way the PHP interpreter handles the ticks and the signals by reading the PHP's source code (the pcntl extension).

*

*If we set ticks = 5, does that mean we have a 4 in 5 chance the signal handler won't be called at all?

PHP is an interpreted language. Your PHP signal handlers are not called by the OS to handle the signals. The interpreter registers a signal handler with the OS and puts all the signals it receives into a queue.
The OS signals come asynchronous. The interpreter dispatches the signals to the handlers defined by you when it's the most appropriate time for it. This happens between the low-level tickable statements.
declare(ticks = 5); makes the signals dispatcher run once every 5 tickable statements. The signals that arrive during two calls to the dispatcher are not lost; they are added to the queue and processed on the next call.
The code of the signals dispatcher is pretty light; it is not a big overhead to use declare(ticks = 1).

*

*How can I determine a consistent but efficient setting?

It depends on what your program does. There is no recipe for that. Try different settings, pick the one that suits you best.

*

*What happens during blocking calls, like database queries? Is the signal thrown away or processed when it returns?

As I said above, the signals come and are processed asynchronously by the signal handler installed by the interpreter. The handling only puts the signals in the queue. They are picked from the queue and dispatched to your code when it's the most appropriate moment for the interpreter (and your PHP code too). Nothing is lost.
Regarding the database, I only checked (some years ago) with mysql. My code was using pcntl_fork() to create worker processes and was processing SIGCHLD to keep track of workers activity. For mysterious reasons it was failing on the MySQL queries frequently with the message "connection lost" without any apparent reason. After extensive investigation and reading of a lot of documentation, I found out that the signals make the functions from the sleep() family return early and that makes the code of the mysql client library think the connection was lost.
The solution was very simple. I used pcntl_sigprocmask() to block the SIGCHLD signal before running a MySQL query and unblock it immediately after the query completes. I was not interested in other signals. Letting them come would lead to process termination; why bothering about a failed MySQL query when the program was about to exit anyway?
I don't know if the signals affect the operation of mysqli or PDO but I think they do. The operation that was affected in my case was part of the low-level communication between the MySQL client and server, deep down in the libmysql and not in the PHP extension.
In your case, you probably need to block SIGHUP (this is the signal that is usually sent to the daemons to make them re-load their configuration).


text:
Q: What is "STRING" and "+%s" in this script using the date command? I have the following script (based on this):
#!/bin/bash

runtime=$(zenity --title "Send notification repeatedly" --entry "Enter the period in minutes like this: nn minutes")

endtime=$(date -ud "$runtime" +%s)

while [[ $(date -u +%s) -le $endtime ]]
do
    notify-send "Hello"
    sleep 10s
done

man date has this:

   -d, --date=STRING
          display time described by STRING, not 'now'

but I couldn't find an explanation for "STRING".
All of the following work when entered in the zenity window:

*

*1 minute

*1 minutes and

*1 min
But 1 m doesn't. Where is what is acceptable as "STRING" described? I couldn't find anything in man date.
The other thing is the purpose of +%s. What does it do?

A: You find it a bit below in man date:

DATE STRING
The  --date=STRING  is  a  mostly  free format human readable date string such as "Sun, 29 Feb 2004 16:21:42 -0800" or "2004-02-29 16:21:42" or even "next Thursday".
  A date string may contain items indicating calendar date, time of day, time zone, day of week, relative time, relative date, and numbers.
  An empty string indicates the beginning of the day. The date string format is more complex than is easily documented here but is fully described in the info documentation.

To get to know what exactly is allowed and what not, you can read the info documentation.
So, run info date and switch to "Date input formats".

Regarding +%s see the Synopsis:
date [OPTION]... [+FORMAT]

with FORMAT being a long number of possible sequences, so here just the one you need:
%s     seconds since 1970-01-01 00:00:00 UTC

The + is just part of the syntax.

Additionally, some good reading:  How can I get help on terminal commands?

A: All is said inside the manpage :

DATE STRING
The --date=STRING is a mostly free format human readable date string
  such as "Sun, 29 Feb 2004 16:21:42 -0800" or "2004-02-29 16:21:42" or
  even "next Thursday".  A date string may contain items indicating
  calendar date, time of day, time zone, day of week, relative time,
  relative date, and numbers.  An empty string indicates the beginning
  of the day. The date string format is more complex than is easily
  documented here but is fully described in the info documentation.

Here is examples given :

EXAMPLES
Convert seconds since the epoch (1970-01-01 UTC) to a date
$ date --date='@2147483647'

Show the time on the west coast of the US (use tzselect(1) to find TZ)
$ TZ='America/Los_Angeles' date

Show the local time for 9AM next Friday on the west coast of the US
$ date --date='TZ="America/Los_Angeles" 09:00 next Fri'

You could also find that man page on internet

A: From info '(coreutils) date invocation':

The program accepts the following options.  Also see *note Common
  options::.
'-d DATESTR' '--date=DATESTR'
       Display the date and time specified in DATESTR instead of the
       current date and time.  DATESTR can be in almost any common format.
       It can contain month names, time zones, 'am' and 'pm', 'yesterday',
       etc.  For example, '--date="2004-02-27 14:19:13.489392193 +0530"'
       specifies the instant of time that is 489,392,193 nanoseconds after
       February 27, 2004 at 2:19:13 PM in a time zone that is 5 hours and
       30 minutes east of UTC.
       Note: input currently must be in locale independent format.  E.g.,
       the LC_TIME=C below is needed to print back the correct date in
       many locales:
            date -d "$(LC_TIME=C date)"

The +:

If given an argument that starts with a '+', 'date' prints the current
  date and time (or the date and time specified by the '--date' option,
  see below) in the format defined by that argument, which is similar to
  that of the 'strftime' function.  Except for conversion specifiers,
  which start with '%', characters in the format string are printed
  unchanged.  The conversion specifiers are described below.

The  %s:

'date' conversion specifiers related to times. ...
'%s'
       seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.  Leap
       seconds are not counted unless leap second support is available.
       *Note %s-examples::, for examples.  This is a GNU extension.


text:
Q: Constant time std::list resize to a given last element? Resizing a std::list is linear time since it needs to find the nth element first.
But is it possible to point to an element (using iterator) and resize in constant time by declaring that the pointed-to element is the new last element?
It would be something like:
make_last(const_iterator pos).

A: Unfortunately, in C++11 general std::list splicing is O(n), in order to get O(1) size checking.
Otherwise you could have moved the undesired items to another list.
But even that's just a half solution, since the items have to be destroyed at some point. However, if constant time splicing was guaranteed this would make a temporary resize O(1).

A practical solution is to use e.g. std::vector instead of std::list.
Due to necessity of destroying it doesn't give you O(1) resizing either, except when the resizing discards a constant number of items at the end, but it avoids all that complexity.
With the decision to make std::list::size a constant time operation, I do not know of any remaining reason to use std::list for anything.

A: In C++03 you use erase on the first element you don't want - constant time iff the optimiser realises the elements don't need destruction.
In C++11 you're stuffed... it's obliged to work out the new size as Alf explains.


text:
Q: Is Android Volley Dead? I presently use volley for network calls.
But, Google doesn't seem to be actively maintaining volley.
I heard that google initially developed volley to use it for its play store app but they haven't mentioned it in their list of 3rd party libraries used.
Almost everyone uses Retrofit(looking at the benchmarks, Retrofit seems better option), is it time to quit using volley?
p.s: please don't post the pros and cons of volley and retrofit

A:
Google doesn't seem to be actively maintaining volley

That depends entirely on how you define "actively maintaining". Development is ongoing, as you can see by looking at the Volley git repo, which shows many commits over the past year (as of the time of this writing).
Google also shipped an official Volley artifact earlier this year, as version 1.0.0.

but they haven't mentioned it in their list of 3rd party libraries used

Google wrote the Play Store app. Google wrote Volley. Hence, from Google's standpoint, Volley is not a third-party library. For anyone other than Google, Volley is a third-party library.

Almost everyone uses Retrofit

Retrofit is not equivalent to Volley. The triad of Square HTTP libraries (OkHttp3, Retrofit, Picasso) would be equivalent to Volley, and that combination exceeds Volley's capabilities.
Based on questions here at Stack Overflow, I do not believe that "almost everyone uses Retrofit".

is it time to quit using volley?

Nobody can answer that other than you. You are the one with decision criteria of importance to you. You are the one who needs to evaluate which libraries meet those criteria.


text:
Q: How to pass digraph output to a JavaScript variable inside HTML code This is my dot.source output.
I assigned index= dot.source:
index= dot.source

digraph {
    edge [arrowhead=none]
    0 [label=cal360 id=cal360]
    1 [label=or120 id=or120]
    2 [label=ol372 id=ol372]
    3 [label=cal361 id=cal361]
    4 [label=sq513 id=sq513]
    5 [label=ld360 id=ld360]
    6 [label=al300 id=al300]
    7 [label=lf267 id=lf267]
    8 [label=nv479 id=nv479]
    9 [label=yr402 id=yr402]
    10 [label=gd326 id=gd326]
}

<script>
var dotSrc = {{ index }};

var graphviz = d3.select('#graph').graphviz();

function render(dotSrc) {
console.log('DOT source =', dotSrc);
var dotSrcLines = dotSrc.split('\n');

I want to pass it to dotSrc in my JavaScript which in in a different file.


text:
Q: selenium web driver should stop execution of last element I am new to selenium and was trying to make my work automated. My results consists of pagination like next page. At last page "Next" button is disabled and my code should not access that particular element.
List<WebElement> pagesize = driver.findElements(By.xpath("html/body/div[1]/div[3]/div[3]/div/span"));
while(true) {
    for(int i=5; i<=pagesize.size(); i++) {
        WebElement Analystelem = driver.findElement(By.xpath("html/body/div[1]/div[3]/div[3]/div["+i+"]/span"));
        List<WebElement> pagesize = driver.findElements(By.xpath("html/body/div[1]/div[3]/div[3]/div/span"));
        System.out.println(pagesize.size());

        while(true) {
            for(int i=5;i<=pagesize.size();i++) {
                WebElement Analystelem = driver.findElement(By.xpath("html/body/div[1]/div[3]/div[3]/div["+i+"]/span"));
                if(elementpage.isEnabled()) {
                    elementpage.click();
                }
                else {
                    System.exit(1);
                }

note: older search is the next button here.
at last page of results i am getting an exception as
"Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"html/body/div[1]/div[3]/div[3]/div[10]/span"}"

A: First of all I doubt that you have searched for a span and stored its reference to 'Analystelem' but you are calling a click action on 'elementpage'.
If the code you provided is working than below given code will work fine. When Selenium will find the element and tries to click on it; it will throw exception, handle the exception as you feel best but it will not break your execution.
Just put your code in Try Catch block like this:
while(true)
{
for(int i=5;i<=pagesize.size();i++)
{
    WebElement Analystelem=driver.findElement(By.xpath("html/body/div[1]/div[3]/div[3]/div["+i+"]/span"));
    if(elementpage.isEnabled())
    {
        Try
        {
               elementpage.click();
        }
        Catch (Exception ex)
        {
            //Do whatever you want to do here
        }
    }
    else
    {
        System.exit(1);
    }
}
}

Additionally, you do not have to check weather the element is enabled or not. Let the try catch do its work. More suited code:
while(true)
{
for(int i=5;i<=pagesize.size();i++)
{
    WebElement Analystelem=driver.findElement(By.xpath("html/body/div[1]/div[3]/div[3]/div["+i+"]/span"));
    Try
    {
        elementpage.click();
    }
    Catch (Exception ex)
    {
        System.exit(1);
        //Do whatever you want to do here
    }
}
}


text:
Q: Why "do while" loop keeps exiting, even though the condition evaluates to false? When I run the code it should only make the win condition = true after either all dragons have no health or all ships have no health.
But when it runs, it seems the do while loop exits after the first iteration, even though the condition is set to only leave while win condition is true.
I cannot seem to figure out why it wont continue running, I even assigned winCondition = false when declaring the variable.
Any help would be appreciated.
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;

struct ship  //Creates type ship
{
  float shipHealth;
  int numOfPeople;
  bool capturedDragon;
};

struct dragon  //Creates type dragon
{
  string riderName;
  string dragonName;
  float dragonHealth;
  bool isCaptured = false;
};

int main()
{
  srand(time(NULL));

  const int MAX_SHIPS = 7;
  const int MAX_RIDERS = 5;

  int dragonHit;
  int dragonDamage;
  int dragonRemoveMenNumber;
  int shipDamage;
  int shipHit;
  bool winCondition = false;

  ship hunterShips[MAX_SHIPS];  //creates array of ships
  dragon dragonRiders[MAX_RIDERS];  //creates array of dragon/riders.

  for (int i = 0; i <= 4; i++)
  {
      cout << "Rider Name: " << endl;
      cin >> dragonRiders[i].riderName;
      cout << "Dragon Name: " << endl;
      cin >> dragonRiders[i].dragonName;
      dragonRiders[i].dragonHealth = rand() % (20 - 15 + 1) + 15;

  }

  for (int i = 0; i <= 6; i++)
  {
      hunterShips[i].shipHealth = rand() % (40 - 30 + 1) + 30;
      hunterShips[i].numOfPeople = rand() % (15 - 10 + 1) + 10;
  }

  do
  {

    for (int i = 0; i <= 4; i++)  //Dragons turn
    {
      if(dragonRiders[i].dragonHealth > 0 && dragonRiders[i].isCaptured == false)  //Dragon is alive
      {
        dragonHit = rand() % 10 + 1;
        if (dragonHit <= 7)  //Dragon hits target
        {
          if(hunterShips[i].shipHealth > 0 || hunterShips[i].numOfPeople > 0)
          {
            dragonDamage = rand() % (10 - 5 + 1) + 5; //Amount of Damage done
            cout << dragonRiders[i].dragonName << " hit and dealt " << dragonDamage << " damage. " << endl;

            if (dragonHit <= 3)  //Dragon takes men out
            {
              dragonRemoveMenNumber = rand() % (3 - 2 + 1) + 2;
              cout << dragonRiders[i].dragonName << "Took out " << dragonRemoveMenNumber << " men" << endl;
              hunterShips[MAX_SHIPS].numOfPeople = hunterShips[MAX_SHIPS].numOfPeople - dragonRemoveMenNumber;  //Ships lose people
            }

            hunterShips[MAX_SHIPS].shipHealth = hunterShips[MAX_SHIPS].shipHealth - dragonDamage;
          }
          else
          {
            cout << "All ships are destroyed, dragons win!" << endl;
            winCondition = true;
          }

        }

        else //Dragon misses target
          cout << dragonRiders[i].dragonName << " missed" << endl;
      }

      else  //Dragon is dead
        cout << dragonRiders[i].dragonName << " is dead or captured" << endl;
    }

    for (int i = 0; i <= 6; i++) //Ships turn
    {
      if(hunterShips[i].shipHealth > 0 || hunterShips[i].numOfPeople > 0)  //ship is afloat
      {
        shipHit = rand() % 10 + 1;

        if (shipHit >= 7)  //40% chance to hit
        {
          if(dragonRiders[i].dragonHealth > 0 && dragonRiders[i].isCaptured == false)
          {
            shipDamage = rand() % (5 - 4 + 1) + 4; //Damage done
            cout << "Ship dealt " << shipDamage << " damage" << endl;
            dragonRiders[MAX_RIDERS].dragonHealth = dragonRiders[MAX_RIDERS].dragonHealth - shipDamage;
          }
          else
          {
            cout << "All dragons are dead, ships win!" << endl;
            winCondition = true;
          }

        }
        else
          cout << "Ship missed. " << endl;
      }

      else
        cout << "Ship is sunk or out of men" << endl; //ship is sunk
    }

  } while (winCondition == true);
  return 0;
}

A: Your code is
bool winCondition = false;
/* ... */
do {/* ... */}
while (winCondition == true);

and you wonder "Loop keeps exiting even though winCondition = false". You also explain "the condition is set to only leave while win condition is true".
I conclude that you misunderstood the semantics of a do-while loop to be "loop until condition is met". Instead it is however "loop while the condition is met". This means that exiting when winCondition evaluates to false is the intended behaviour.

A: You are initialising the winCondition = false to start with. The do..while loop will run through one iteration and evaluate that the iterate condition winCondition == true is not satisfied, and therefore exit.
In addition, if the do..while loop ever continued, there is no statement inside it where winCondition is ever set to false, so the loop will never exit.
Did you mean to close the do..while loop with winCondition == false?


text:
Q: Using Chicagoboss boss_db and printing list of records I'm trying to print a list of records from mnesia.
Users = boss_db:find(users, []),
lists:foreach(fun(X) ->
[{_,Email,_,_,_,_,AccessToken}] = X,
io:format("Email : ~w~n",[Email]),
io:format("AccessToken : ~w~n",[AccessToken]), end, [Users]).

However I'm getting:
Email : [117,115,101,..,..,.,..]
Similarly for AccessToken.
What am I missing? Any pointer would be really appreciated.

A: You didn't choose the right format: ~w is used to print as erlang term, ~s is used for string, ~p for pretty print, it tries to find the best way to print . See doc at http://www.erlang.org/doc/man/io.html#format-3
1> L = "Hello".
"Hello"
2> io:format("~w~n",[L]).
[72,101,108,108,111]
ok
3> io:format("~p~n",[L]).
"Hello"
ok
4> io:format("~s~n",[L]).
Hello
ok
5> L1 = [1,2,3,4,5].
[1,2,3,4,5]
6> io:format("~w~n",[L1]).
[1,2,3,4,5]
ok
7> io:format("~p~n",[L1]).
[1,2,3,4,5]
ok
8> io:format("~s~n",[L1]).
^A^B^C^D^E
ok
9>