text:
Q: Thinkpad touchpad mouse cursor laggy/choppy | Ubuntu 18.04 I am new to ubuntu so please keep that in mind.
I installed ubuntu 18.04 LTS on my Thinkpad L540. Most often my mouse cursor, if I use my touchpad, is laggy/choppy in a visual way. This does not happen if I use an external mouse (bluetooth). Everything else is working fine (fluid/without lags). After some reboots, it sometimes works.
I take the notebook with me and I often cant use a bluetooth mouse, so I am stuck with rebooting my device as many times as it takes, to get it working.
Did not happen on Windows 10. That is my first try installing Linux on this notebook.
I presume that my touchpad device is a SynPS/2 Synaptics TouchPad (Terminal: xinput).
Any advice on what I can do or check to get rid of this problem?

A: see my answer here:
I can confirm a similar issue with my touchpad on HP ProBook 450 G6 with Ubuntu 18.04, it was very laggy after suspend.
What worked for me:
create /lib/systemd/system-sleep/touchpad:
#!/bin/sh

case $1 in
  post)
    /sbin/rmmod i2c_hid && /sbin/modprobe i2c_hid
  ;;
esac

make file executable chmod +x /lib/systemd/system-sleep/touchpad
and test (suspend computer and wake-up again)

A: I had this (or a similar) problem with a thinkpad 470. The mouse pointer was suddenly choppy after a reboot. Rebooting did not help.
The problem finally went away after I sent it to sleep and woke it up again. (sudo systemctl suspend)

A: I am using a Lenovo T470, I encountered the same problem. I updated to version 19.04 but nothing changed.
Then I disabled the Trackpoint in the Bios settings. My Touchpad doesn't make any more problems since.

A: I have same problem on my Thinkpad T460s with Ubuntu 18.04 (Ubuntu 16.04 and Windows 10 have no problem). I tried the solution here and after reboot, the problem was solved.
sudo apt install xserver-xorg-input-synaptics-hwe-18.04

A: I had a similar problem on my Thinkpad with Ubuntu 18.04. The cursor was very jumpy. It seems to be a problem with the version of the touchpad driver used in Ubuntu 18.04, "libinput". I read somewhere (can't find the link, sorry) that it's fixed in newer versions of the driver which are going to be released for Ubuntu 18.10. Whether it's going to be released for 18.04 as well it was said there is not clear by now.
For me installing the synaptic driver instead of libinput solved my problem:
https://ubuntuforums.org/showthread.php?t=2391805
https://bugs.launchpad.net/ubuntu/+source/libinput/+bug/1696929


text:
Q: Active Directory based custom authorization I have an ASP.NET Core application that needs to decide whether or not to return information from controller end points based on the requesting client's Active Directory groups. I tried to implement custom authorization as follows:
Startup.cs
public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddOptions();
            services.AddSingleton(Configuration);
            services.AddSignalR();
            services.AddAuthorization(options=> {
                options.AddPolicy("RequiredADGroupName", policy=>policy.Requirements.Add(new ActiveDirectoryRequirement("RequiredADGroupName")));
            });

        }

ActiveDirectoryRequirement.cs
public class ActiveDirectoryRequirement: IAuthorizationRequirement
    {
        public string ActiveDirectoryGroupName { get; set; }

        public ActiveDirectoryRequirement(string groupName)
        {
            ActiveDirectoryGroupName = groupName;
        }
    }

ActiveDirectoryHandler.cs
public class ActiveDirectoryHandler: AuthorizationHandler<ActiveDirectoryRequirement>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ActiveDirectoryRequirement requirement)
        {
            //authorization logic
        }
    }

this next one is just an example of how i would use this authorization.
HomeController.cs
public class HomeController : Controller
{
[Authorize(Policy = "RequiredADGroupName")]
        public IActionResult Index()
        {
            return View();
        }
}

When i run the project, i get the following error:
InvalidOperationException: No authenticationScheme was specified, and there was no DefaultForbidScheme found.

what am i doing wrong?

A: Try to register IAuthorizationHandler with ActiveDirectoryHandler like:
            services.AddAuthorization(options => {
            options.AddPolicy("RequiredADGroupName", policy =>
            {
                policy.Requirements.Add(new ActiveDirectoryRequirement("RequiredADGroupName"));
            });
        });
        services.AddSingleton<IAuthorizationHandler, ActiveDirectoryHandler>();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deriving field parameter from table parameter in Python Toolbox? I'm trying to derive a Python Toolbox parameter from another parameter. I'd like to have a tool which determines fields from an input table and applies the list as a filter to a second parameter. This is what I've come up with so far:
class Tool(object):
    def __init__(self):
        self.label = "MFF"
        self.description = ""
        self.canRunInBackground = False

    def getParameterInfo(self):
        #input excel spreadsheet table
        lkTab = arcpy.Parameter (
            displayName = "Leak Excel Worksheet",
            name = "intab",
            datatype = "DETable",
            parameterType = "Required",
            direction = "Input")

        #input table field
        lkLkTab = arcpy.Parameter (
            displayName = "Leak Excel Worksheet Leak Field",
            name = "lkLkFld",
            datatype = "Field",
            parameterType = "Required",
            direction = "Input")

        return [lkTab, lkLkTab]

    def updateParameters(self, parameters):
        flds = []
        tab = parameters [0].valueAsText
        if tab:
            flds = [f.name for f in arcpy.ListFields (tab)]
        if not parameters [1].valueAsText in flds:
            parameters [1].value = None
        #trying here to apply filter list of fields
        parameters [1].filter.list = flds

My field list parameter doesn't get populated however when I indicate a table in the first parameter:

How do filter a parameter with a list of fields from another parameter?

A: My input field parameter needed to be type GPString instead of Field.
lkLkTab = arcpy.Parameter (
        displayName = "Leak Excel Worksheet Leak Field",
        name = "lkLkFld",
        datatype = "GPString", ###changed
        parameterType = "Required",
        direction = "Input")

I've also found that filtering parameters based off an input table can be accomplished with dependencies.
def getParameterInfo(self):
    in_fc = arcpy.Parameter(
        name='in_features',
        displayName='Input Features',
        datatype='GPFeatureLayer',
        direction='Input',
        parameterType='Required')

    vt = arcpy.Parameter(
        name = 'summary_fields',
        displayName = 'Summary field',
        datatype = 'Field',
        direction = 'Input',
        parameterType = 'Required')

    vt.parameterDependencies = [in_fc.name]


text:
Q: Stop an angular-ui-router state change when a simple object can't be resolved? One of my angular-ui-router states depends on a simple object being resolved:
.state(...) {
  ...
  resolve: {
    user: function ($rootScope) {
      if ($rootScope.user) {
        return $rootScope.user;
      }
    }
  }
  ...
}

I figured if the $rootScope.user object didn't exist, then the user dependency couldn't be resolved, and the state wouldn't change. Instead, even when $rootScope.user does not exist, user is resolved to an empty object {}, and the state does change.
Is there a way make the resolve fail when $rootScope.user does not exist? Perhaps by returning a specific value in an else block that signifies that the dependency could not be resolved?
I'm able to reject it using a promise:
resolve: {
  user: function($q) {
    return $q(function (resolve, reject) {
      if ($rootScope.user) {
        resolve($rootScope.user);
      }
      else {
        reject();
      }
    }
  }
}

In this case when $rootScope.user does not exist, the promise is rejected, the user dependency is not resolved, and the state does not change.
Is there a way to do this without a promise? Why? Because using a promise here doesn't make it clear that a simple object needs to be resolved.


text:
Q: Howto send notification from raspberry pi using curl I have an Android app that is receiving notifications via Firebase Cloud Messaging.
Sending notifications from the Firebase Console works fine but I want to send them from a Raspberry Pi using curl like this (found somewhere on stackoverflow):
curl -X POST --header "Authorization:key=<api key>" --header "Content-Type:application/json" https://fcm.googleapis.com/fcm/send -d "{\"to\" : \"<registration id>\", \"notification\" : {\"body\" : \"Yellow\"} \"priority\" : \"high\"}"

That allways givs me:

<TITLE>Internal Server Error</TITLE>

Internal Server Error

Error 500

Does anyone know what the problem might be?
Added:
my registration id looks like this (almost):

dxxxxxxxVEs:APA9xxxcL--JnhswC1w8utjxxxxxxxxxxxxxxxxxxxglosvLbvEAwh7sxxxxxxxxxQo3Fq4sn0yqZUN6Hy89IB9mAS3FusBo68UE4l3xDVRHxxxxxxxxxxpANAHWuLgXHqBoDsLsXBj

A: You're missing a comma before priority high.
Can debug this by entering JSON into jsonlint.com
This can then be added to CURL like so:
curl -X POST --header "Authorization:key=<api key>" --header "Content-Type:application/json" https://fcm.googleapis.com/fcm/send -d '{"to": "<registration id>", "notification": {"body": "Yellow"},"priority": "high"}'

NOTE: The single quotes to avoid having to escape the double quotes.


text:
Q: Xcode 10. Your account does not have permission to create iOS App Store provisioning profiles Xcode 10. When I try to upload app to TestFlight I get the following error 'Your account does not have permission to create iOS App Store provisioning profiles.'
I have 'Admin' role in Apple Developer Program and I have 'App Manager' role in App Store Connect (https://help.apple.com/app-store-connect/#/dev82a173c41)

A: It has been already discussed here: https://stackoverflow.com/a/40670695/3930651
Admin role is not sufficient, you need to be the Team Agent.


text:
Q: Algorithm for determining inside and outside regions of a 3D model (multiple meshes) I am trying to implement an efficient precomputed culling scheme in my 3D city model viewer program (a user can upload a 3D model of a city from any number of architecture programs, meaning that there can be a huge number of separate different unique meshes). And one major culling optimization that I would like to implement is culling out the interior of buildings when you are outside and culling out every other building when you are inside a model (this will help with frame rate, as I am running on an android device).
How would I algorithmically calculate what is the outside and what is the inside and then differeniate between the different interiors?
I was thinking if there was a way to pre calculate these regions, then during runtime it would be a simple position check against those small number of regions.


text:
Q: How to get nested Kivy widgets to interact between each other? I'm playing around with the examples provided in the Kivy tutorial. I was able to create nested widgets, but can't seem to get the buttons to modify objects in the other parts of the screen.
In this example, I've tried to modify the Kivy example script to turn it into a simple login window with a numpad drawn from buttons (let's ignore the vkeyboard for this case, I'm trying to get a hold of buttons...). In short, buttons on the left, login textinput on the right. I cannot seem to have the actions on the buttons affect the text input on the right. It sounds very simple, but I can't seem to figure it out. Should I use a global variable? Am I creating my objects incorrectly for this purpose?
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput

class AddNumpad(GridLayout):
    def __init__(self, **kwargs):
        super(AddNumpad, self).__init__(**kwargs)
        self.cols = 3
        self.padding = 50

        def callback(instance):
            print('The button <%s> is being pressed' % instance.text)
            # TODO: trying to populate the password textinput here

        for i in range(1,10):
            btn = Button(text=str(i))
            btn.bind(on_press=callback)
            self.add_widget(btn)
        self.add_widget(Label(text=''))
        btn = Button(text='0')
        btn.bind(on_press=callback)
        self.add_widget(btn)

class LoginScreen(GridLayout):

    def __init__(self, **kwargs):
        super(LoginScreen, self).__init__(**kwargs)
        self.password = TextInput(password=True, multiline=False)
        self.cols = 2
        self.numpad = AddNumpad()
        self.add_widget(self.numpad)
        self.entry = ''
        self.password.text = self.entry
        self.add_widget(self.password)

class MyApp(App):
    userInput = ''
    def build(self):
        return LoginScreen()

if __name__ == '__main__':
    MyApp().run()

A: You can use a custom property and bind it to a callback in your LogginScreen class:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.properties import StringProperty

class AddNumpad(GridLayout):
    passwIn = StringProperty()                            # <<<<<<<<<<<<<

    def __init__(self, **kwargs):
        super(AddNumpad, self).__init__(**kwargs)
        self.cols = 3
        self.padding = 50

        for i in range(1, 10):
            btn = Button(text=str(i))
            btn.bind(on_press=self.callback)
            self.add_widget(btn)

        self.add_widget(Label(text=''))
        btn = Button(text='0')
        btn.bind(on_press=self.callback)
        self.add_widget(btn)

    def callback(self, instance):
        self.passwIn += instance.text                     # <<<<<<<<<<<<<

class LoginScreen(GridLayout):
    def __init__(self, **kwargs):
        super(LoginScreen, self).__init__(**kwargs)
        self.password = TextInput(password=True, multiline=False)
        self.cols = 2
        self.numpad = AddNumpad()
        self.numpad.bind(passwIn=self.numpad_pressed)     # <<<<<<<<<<<<<
        self.add_widget(self.numpad)
        self.add_widget(self.password)

    def numpad_pressed(self, instance, value):
        self.password.text = value

class MyApp(App):
    def build(self):
        return LoginScreen()

if __name__ == '__main__':
    MyApp().run()


text:
Q: how to upload a Map of files to php server I want to send multiple files attached to a post to a Laravel backend. They should all be in a field named media which is an array which maps filetype to the actual file. Here is a representation of what backend expects:
'media' => [
    'image' => UploadedFile,
    'video' => UploadedFile,
    'music' => UploadedFile,
   // other type of files
]

I've tried many solutions from the Internet. If I use @Query annotation backend receives the structure right, but files are not being received as expected. If I use @Part annotation, I cannot send a named array (i.e. media).

A: I found the solution myself through trial and error.
Here is the corresponding method in my route interface:
@Multipart
@POST("posts")
Call<ResponseBody> createPost(
    @Part ArrayList<MultipartBody.Part> files
    //other parameters
);

Whenever in your code that you are packing data for sending, initialize an ArrayList and add files like the following:
RequestBody reqFile;

reqFile = RequestBody.create(MediaType.parse(mimeType), file);

ArrayList<MultipartBody.Part> partArrayList = new ArrayList<>();
partArrayList.add(MultipartBody.Part.createFormData("media[image]",file.getName(),reqFile));
partArrayList.add(MultipartBody.Part.createFormData("media[video]",file.getName(),reqFile));

route.createPost(
    partArrayList
    /*other_parameters*/
);


text:
Q: Trying to send MMS through SmsManager (Android - Kotlin) So I need to send one PNG via SMS, and I'm using the SmsManager, here's my code:
                val smsManager: SmsManager = SmsManager.getDefault()

                val file = File(context?.filesDir?.path, "receipt.png")

                val png = context?.let {
                    FileProvider.getUriForFile(
                        it,
                        "com.mydomain.fileprovider",
                        file
                    )
                }
                smsManager.sendMultimediaMessage(context, png, phoneNumber, null, null)

Gives me the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.PendingIntent.send(android.content.Context, int, android.content.Intent)' on a null object reference

Any ideas?
Thanks in advance :D


text:
Q: Right border of the edit summary field is not aligned When editing a post, the right border of the Edit Summary field is not aligned as done for Title, Body and Tags fields:

Moreover, for Stack Overflow Title and Rev fields also are not aligned:

A: Currently the right border of the Rev, Title, Body, Tags and Edit Summary are aligned correctly in all the Stack Exchange sites.
Screenshot taken from Meta Stack Exchange:

Screenshot taken from Stack Overflow:


text:
Q: using js variable in mysql Ok I have a problem here. I'm trying to get a JS variable to use in an sql query. Now i know that's not possible so i passed the variable using jquery and use the get method to assign it to a variable in php. But the php alwways loads before JS so the sql query doesn't update. Here's there code:
var monthS = calenderMonths[monthNow];
$.get('load2.php', {location:monthS} );

This is in my JS file in a function that's being onloaded in HTML
This is my php:
$monthS = $_GET['location'];

echo "alert($monthS);";
// Connect to MySQL
if ( !( $database = mysql_connect( "localhost",
  "root", "" ) ) )
  die( "Could not connect to database " );

// open Events database
if ( !mysql_select_db( "Events", $database ) )
die( "Could not open Events database " );

$result = mysql_query("SELECT * FROM posted_events WHERE Month_ = '$monthS' ")
  or die ('Error updating database because: '.mysql_error());

I alert $monthS to see if it passed but the alert ends up empty at first but after clicking 'ok' like 3 secs another alert box comes up with the variable. So I believe the PHP is loading before the variable gets passed. Is there anyway i could solve this? Thanks

A: You should wait for .get() to complete before continuing with the rest of your script (if it relies on the response as yours does).
$.get('load2.php', {location:monthS} )
   .done(function(data) {
   alert(data);
   //rest of your code
 });


text:
Q: Where is the best place to store supporting JSON on dynamic AJAX load? Scenario: I have an HTML page with a dynamic modal dialog. Links on the page open the dialog, but with different contents according to the clicked link. Dialog contents are loaded using an AJAX request, and include only the required HTML - no html or head tags, for example.
In the dialog, there is a 'Status' display, and a couple of date pickers (e.g. 'Activated' and 'Removed'). As the dates change, the Status should update to show the current status according to the dates. That I can do, no worries.
In the application I have an enum for the Status, and I want the JavaScript in this dialog to make use of the same list of statuses as the server-side app. I figure the MVC (server-side) should generate some JSON, listing the enum entries, for example:
{ "active": "Active", "removed", "Removed" }

Now the question! Where's the best place to put this JSON in the page, if it is loaded with the modal contents?
Here are some options I've considered:

*

*I could store it in a var in the head, but I don't need it to appear in every page in the application.

*I could insert it into the head, or add it to the document element, when the modal is loaded, using a JS function called by the modal contents.

*I could store it in the data tag of the Status display element.

A: I would store this in the data attribute of an element that is associated with it given your description.
Example:

You could then populate this using Razor in the view from the back end.
This way it gets in the markup/page associated with that element and you have access to it from script easily.
Example: (jQuery but it is just an example)
var initialstatus = {
    "active": "Active",
        "removed": "Removed"
};
// push it in there
$('#myelementid').data("status", initialstatus);
// access it later
var status = $('#myelementid').data("status");
// access one property:
alert($('#myelementid').data("status").active);
// update one property
$('#myelementid').data("status").active = "FRED";
//list the properties(keys)
for (var key in status) {
    if (status.hasOwnProperty(key)) {
        /* useful code here */
        alert(key + ":" + status.active + status[key]);
    }
}

PRACTICAL EXAMPLE:  Store a URL for your ajax in an element.

NOW the fun part: use this URL in an ajax call:
var myStoredUrl = $('#myfriend').data("url");
var myajax = $.ajax({
    url: myStoredUrl,
    //...other ajax stuff
});
myajax.done(function (data) {
//done stuff
});

Now if you refactor you don't have to remember the URL, the root etc. of the site to stick on the front, this does it for you.
Same net effect as your question (where to store stuff) just a different perspective that has worked well in production for me.

A:
Where's the best place to put this JSON in the page, if it is loaded
  with the modal contents?
let's say I don't want it to load until it's needed; if it is applied
  to the page on the first modal dialog and it's used by all other
  dialogs, that's grand, but it could also be included only in the
  dialog and used only when that dialog is open. So where would the JSON
  be?

Well, keeping JSON data on a web page is easy. There is no need to think in terms of HTML elements as the bearers of data. You can just put it in the global object, window. Let's say you call the place to keep your data VAULT:
    // So, we have the JSON come from the sevrer side:
    var options = { "active": "Active", "removed", "Removed" };
    // Now, let's save it on the page:
    window.VAULT = {};
    VAULT.options = options;

Or put options in window directly (not recommended though because it might create mess in the global scope and cause collisions):
    window.modalOptions = options;

However, if you are loading your JSON with every AJAX request that loads your modal contents anyway, why put it anywhere outside the dialog? Just keep it within:
    // So, we have the JSON come from the server side:
    var options = { "active": "Active", "removed", "Removed" };

    // We have the dialog element (can be obtained in any other way):
    var dialog = document.getElementById('dialogId');

    // Now, just PUT the data in there:
    dialog.data = options;

    // Reuse it later:
    options = dialog.data;

Again, there is no need to use HTML elements' attributes to store data in your case. That technique is used to deliver data from the server side, but using it once data is already available only complicates things.
UPDATE: Best practice for delivering JSON via AJAX
Short answer: use JSON for the whole thing where keep the data and HTML markup separate.
Full answer:
Your server side responding for AJAX calls for the purpose of showing modal dialogs should return JSON where HTML markup should be kept separate from any other data. For example, the JSON returned could look like this:
    {
        "html": "
Dialog.. blablabla
",
        "data": {
            "options": { "active": "Active", "removed", "Removed" }
        }
    }

Your AJAX callback will need to be aware of the response structure to find and apply the HTML markup. The actual code will be different depending on whether/what JavaScript framework you are using, but roughly:

*

*The response JSON will need to be parsed (typically done automatically with most modern JavaScript goodies):
var response = JSON.parse(responseText);

*The HTML markup will be available for applying to the modal dialog as:
response.html

*The options data (what constitutes "JSON" in your question) will be available as:
response.data.options

A: Ideally, the place to 'keep/store' the data would be in a view model. Then you would use something like angularS or knockout.js to bind the necessary DOM elements to their relative json datasets. If you want an example of this I can spin one up. If you want to go the traditional route, unless those datasets are dynamically changing, I'd say the best bet is to serve the page, then loop each dataset after document.ready() to keep your load times down.
It's kind of an open answer, where you'll have to choose what's best for your given scenario/needs.

A: Another solution for this particular case involves no JSON at all. I seem to have gotten it in my head that JSON (or something similar) would be necessary to provide the solution I needed, whereas there is a much simpler solution.
The Status property updates according to the settings applied through the date fields. A piece of JavaScript code would determine which of the date fields contains the most recent date, and set the status accordingly.
Solution: Store the Status string in the date picker controls.
In a Razor example, it might look like this:

Thanks for all the answers, it's great to get some insight into possible ways to approach situations not just like this one.


text:
Q: Make DIV max-height equal to `window height - 100px` There is a way to set max-height in %, but is here any way  to set DIV max-height, so it would be 100px smaller than window height with only CSS?
It must not be a fixed layout, user must be able to scroll page vertically, but DIV always should be resized to window height - 100px. Is this possible, or will I have to use JS for that?

A: Yes:
#specificElement {
    height: calc(100vh - 100px);
    box-sizing: border-box;
}

This uses the CSS calc() function to subtract 100px from  100vh (1vh being one percent of the view-port's height) and uses the result as the value of the height property.
The box-sizing forces the browser to include padding, and borders, in the calculated height of the element.
Obviously use a relevant selector for your use-case.
References:

*

*calc().

*CSS lengths.

A: #specificElement {
  height: calc(100vh - 100%);
  min-height: calc(100vh - 100px);
}
set min height so that your dyanmic content should not get effect and give height in percentage for dymanic result.


text:
Q: MaterialDatePicker not working on Android I want to change the date picker of my project to the date picker provided by the Material Components for Android, but it is not working.
This is the code I've tried:
MaterialDatePicker.Builder<Long> builder = MaterialDatePicker.Builder.datePicker();

MaterialDatePicker<Long> picker = builder.build();

picker.show(getSupportFragmentManager(), picker.toString());

This is how it looked like:

An this is how it should've looked like:

Can anybody tell me what's missing?
Thanks

A: The problem was in the colorPrimary.
The default color of my project to colorPrimary was "white" and the Material Date Picker style uses that colorPrimary to color the background and the text of the buttons. Since the color of the header text was also white, it appear that there was nothing there when there was everything.
I solved it by importing the styles file to my project and making some adjustments to the styles in my project.
Thank you all for your answers, all of them helped in finding the problem!

A: With the Material Components for Android you can use the new MaterialDatePicker.
To work fine, in your app you have to use a Material Components Theme.
In this way you inherit the style and theme for the pickers.
To select a single date just use:
MaterialDatePicker.Builder<Long> builder = MaterialDatePicker.Builder.datePicker();
builder.setTitleText(R.string.your_text);
MaterialDatePicker<Long> picker = builder.build();
picker.show(getSupportFragmentManager(), picker.toString());

To select a range date you can use a DateRange Picker using:
MaterialDatePicker.Builder<Pair<Long, Long>> builder =
                    MaterialDatePicker.Builder.dateRangePicker();
CalendarConstraints.Builder constraintsBuilder = new CalendarConstraints.Builder();
builder.setCalendarConstraints(constraintsBuilder.build());
MaterialDatePicker<?> picker = builder.build();
picker.show(getSupportFragmentManager(), picker.toString());

Check the colors used in your theme.
These attributes define your style. You don't need to add them, they are provided by default with the Material Components theme.
<!-- Picker styles and themes. -->
<item name="materialCalendarStyle">@style/Widget.MaterialComponents.MaterialCalendar</item>
<item name="materialCalendarFullscreenTheme">@style/ThemeOverlay.MaterialComponents.MaterialCalendar.Fullscreen</item>
<item name="materialCalendarTheme">@style/ThemeOverlay.MaterialComponents.MaterialCalendar</item>

Based on these style, the colors used by the picker are:
HeaderLaoyout     -> background:colorPrimary, textColor:colorOnPrimary
HeaderSelection   -> background:colorPrimary, textColor:colorOnPrimary
ConfirmButtons    -> background:colorPrimary, textColor:colorOnPrimary
Buttons           -> background:colorPrimary, textColor:colorOnSurface
HeaderToggleButton->                          textColor:colorOnPrimary
Day               ->                          text:colorOnSurface  stroke:colorOnSurface
SelectedDay       -> background:colorPrimary, textColor:colorOnPrimary
RangeFillColor    -> background:colorPrimary

A: I had the same issue with my primary color being white.
The simple solution is to override the primaryColor in the Calendar style:
Base Theme:
<style name="Base.Theme.YV.Bible" parent="Theme.MaterialComponents.DayNight.NoActionBar">
  <item name="materialCalendarStyle">@style/Theme.YV.Bible.DatePicker</item>
  <item name="android:datePickerDialogTheme">@style/Theme.YV.Bible.DatePicker</item>
</style>

Calendar / Datepicker Theme
<style name="Theme.YV.Bible.DatePicker" parent="ThemeOverlay.MaterialComponents.MaterialCalendar">
  <item name="colorPrimary">?colorPrimaryDark</item> // this is the key, we need to use a dark color instead of our theme's primary color
</style>

Usage
val picker = MaterialDatePicker.Builder
    .datePicker()
    .setCalendarConstraints(CalendarConstraints.Builder().setStart(now().time).build())
    .setSelection(c.timeInMillis)
    .setTheme(com.bible.base.R.style.Theme_YV_Bible_DatePicker)
    .build()
picker.show(fragmentManager, null)

A: For getting your desired output, make sure to add this before calling show():
builder.setTitleTextResId(R.string.your_text);
// Where R.string.your_text must be equal to "Selected Date" or whatever you want

For Material DatePicker specifically, you need to first implement the latest library
implementation 'com.google.android.material:material:1.1.0-alpha09'

Then
  MaterialDatePicker.Builder<Long> builder =
                        MaterialDatePicker.Builder.datePicker();
  builder.setTitleTextResId(R.string.your_text);
  MaterialDatePicker<Long> picker = builder.build();
  picker.show(getSupportFragmentManager(), picker.toString());

You can also simply show the DatePickerDialog instead of using Builder. The Dialog is
For showing dialog and getting selected data:
EditText date;
DatePickerDialog datePickerDialog;

// Calendar object to hold the selected data
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog = new DatePickerDialog(MainActivity.this,
        new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year,
                                  int monthOfYear, int dayOfMonth) {
                // set day of month , month and year value in the edit text
                date.setText(dayOfMonth + "/"
                        + (monthOfYear + 1) + "/" + year);

            }
        }, mYear, mMonth, mDay);
datePickerDialog.show();

A: Add latest dependency:
implementation 'com.google.android.material:material:1.1.0-alpha10'

MaterialDatePicker.Builder<Long> builder = MaterialDatePicker.Builder.datePicker();
       builder.setTitleTextResId(R.string.your_text);// here is the title for your datepicker
       MaterialDatePicker<Long> picker = builder.build();
       picker.show(getSupportFragmentManager(), picker.toString());

Other options:
https://github.com/wdullaer/MaterialDateTimePicker


text:
Q: Use nfs version 3 on RHEL 7 I tested using nfs version 3 on my lab system, and it works fine.
[root@server2 ~]# tail -1 /etc/mtab

server1:/nfs /nfs nfs rw,relatime,vers=3,rsize=262144,wsize=262144,namlen=255,hard,proto=tcp,timeo=600,retrans=2,sec=sys,mountaddr=192.168.150.134,mountvers=3,mountport=20048,mountproto=udp,local_lock=none,addr=192.168.150.134 0 0

[root@server2 ~]# cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.4 (Maipo)
[root@server2 ~]#

However. when I do the same thing on Azure, it fails. I followed this guide
Link to vers 3 nfs
But when I mount it using version 3, it gives below error
mount -vv  -t nfs -o vers=3 server1:/appl /wbr

mount.nfs: timeout set for Thu Aug  1 02:38:02 2019
mount.nfs: trying text-based options 'vers=3,addr=10.200.254.8'
mount.nfs: prog 100003, trying vers=3, prot=6
mount.nfs: trying 10.200.254.8 prog 100003 vers 3 prot TCP port 2049
mount.nfs: prog 100005, trying vers=3, prot=17
mount.nfs: trying 10.200.254.8 prog 100005 vers 3 prot UDP port 20048
mount.nfs: portmap query retrying: RPC: Timed out

Version 4 works just fine, but version 3 does not!
Any ideas?

A: The vendor provides NFSv3 support in RHEL7 (see Introduction to NFS).
Please do the following checks:
1) Ensure NFSv3 support is enabled in the /etc/sysconfig/nfs file:
NFS3_SERVER_SUPPORT="yes"

To prevent clients from using NFSv4, add the setting
RPCNFSDARGS= -N 4

2) Check if NFS daemons are running on the NFS server:
# service nfs status
# service portmap status

3) Check if your NFS server in Azure is available from the client system via NFS network ports:

*

*port 111 (TCP and UDP);

*port 2049 (TCP and UDP)

with any tool you prefer, e.g.:
# telnet nfs_server_ip_addr 2049
# nmap -sU -p 111,2049 nfs_server_ip_addr
# nmap -sT -p 111,2049 nfs_server_ip_addr

4) Check if existing mounts are visible from the client system:
# showmount -e nfs_server_name

A: Got it working!
I put this in the /etc/sysconfig/nfs file
RQUOTAD_PORT=875
LOCKD_TCPPORT=32803
LOCKD_UDPPORT=32769
MOUNTD_PORT=892
STATD_PORT=662
Then
systemctl restart nfs-config
Then I opened the above ports tcp/udp on azure and was able to mount it!
Thanks to everyone for their support!


text:
Q: Brandbank API PHP Extract Data I am working on a project that requires access to Brandbank API, however their documentation seems pretty limited as to how to access their information.
I have been given access keys and the documentation seems to direct you to extract data via SOAP siting this link https://api.brandbank.com/svc/feed/extractdata.asmx?WSDL
Can anyone provide an example of how to access the product feed of this API?

A: At a minimum you will need code that looks like this:
$wsdl = "https://api.brandbank.com/svc/feed/extractdata.asmx?WSDL";

try {
  $soapclient = new SoapClient($wsdl, array(
      'soap_version'  => SOAP_1_1,
      'trace' => 1,
      'exceptions' => true,
    )
  );

  $parameters = new stdClass();
  $response = $soapclient->GetUnsentProductData($parameters);

} catch (Exception $e) {
  var_dump($e ->getMessage());
}

The call won't work until you finish it with your access credentials, but it provides an example of how most SOAP calls look in PHP.


text:
Q: Can't get webpack usedExport / treeshaking to work Been trying for hours to get webpack to treeshake my code. Here's the repro: https://github.com/dmt0/treeshake-repro
The problem is that even though I'm importing only a few icons from @mdi/js, the whole bundle of 2.6MB gets imported.
Reread the webpack docs multiple times and saw multiple SO questions and GH issues. I do have the following in place:

*

*package.json has

   "sideEffects": [
    "*.scss",
    "*.css"
  ],

*

*Babel is configured with "modules": false

*webpack config has usedExports: true.

*Terser is configured to do 3 passes (see that sometimes one pass is not enough).

*production mode is enabled.

*providedExports and usedExports are enabled.

*sideEffects are set to false in the package.json of the imported library:
What am I missing?

A: The problem was in some completely unrelated setting - devtool. No idea why it breaks treeshaking. It was never changed in this config file since some ancient version of webpack. Had to change from this:
  devtool: env.production ? 'hidden-source-map' : 'eval-source-map',

to this:
  devtool: argv.mode === 'production' ? 'hidden-source-map' : 'eval-source-map',

Now treeshaking works correctly and my bundle size went down significantly.


text:
Q: Why my image slider only show the first image instead of all 3 images? I want to make an image slider in my application using the 'react-simple-image-slider
' package. But it only show the first image only..
In my firestore, my imageUrl is stored like this:

In the documentation of the package, it shows that the 'images' should be stored in this format:
The website of this package:
https://www.npmjs.com/package/react-simple-image-slider

Then, in my application, I have fetched the data and store the imageUrl into the 'image' and pass it into 'SimpleImageSlider' to use it.
const ProductPage = ({ collection, match }) => {
    const { items } = collection;

    const image = [{url: items[match.params.itemId - 1].imageUrl}];

    console.log(image);

    return (

        <SimpleImageSlider
            width={500}
            height={500}
            images={image}
            showBullets={true}
            showNavs={true}
        />

                {items[match.params.itemId - 1].name}

    )
};

However, the application only show the first image in the slider:

I have console.log(image) and I thought I already store the 3 imageURL into the array, but I have no idea why it only displays the first one? Is it something wrong on the method I store the 'image' and how can I convert it to fit the structure that the documentation need from the data I fetched from database?

A: Your array is of format url: [], when the docs say each object in the array should be of format { url: "" }. So, ensure your array looks like this:
[
    { url: "https://..." },
    { url: "https://..." },
    { url: "https://..." },
]

A: This should work as it will assign an object to each item

const ProductPage = ({ collection, match }) => {
    let { items } = collection;

    let image = []

    useEffect(()=>{
      items.map(item=>image.push({url: item.imageUrl}))
    },[])

    console.log(image);

    return (

       {image.length && <SimpleImageSlider
            width={500}
            height={500}
            images={image}
            showBullets={true}
            showNavs={true}
        />
        }

                {items[match.params.itemId - 1].name}

    )
};


text:
Q: Can't log into console on ESXi 5.5 server I'm having the strangest problems with an ESXi 5.5 server. Due to problems getting it added into vSphere, I need to log into the console to do some troubleshooting. I can log into the menu system directly on the server, and also the Windows vSphere client works fine.
From the "direct" console (Alt+F1), I can't log in as root:

Enabling SSH from the vSphere client and then using SSH is even weirder:
$ ssh root@192.168.1.84
CentOS release 6.5 (Final)
Kernel \r on an \m

Password:

CentOS?!? My root password, which works OK to authenticate both to the direct menu and the Windows vSphere client, doesn't work.
There are three CentOS VM's running on this server, but they're not on that IP. I've checked ARP to make sure I'm hitting the correct physical address: I've verified that the IP is really VMWare by:
$ telnet 192.168.1.84 902
Trying 192.168.1.84...
Connected to 192.168.1.84.
Escape character is '^]'.
220 VMware Authentication Daemon Version 1.10: SSL Required, ServerDaemonProtocol:SOAP, MKSDisplayProtocol:VNC , VMXARGS supported, NFCSSL supported

If I disable SSH using the vSphere client:
$ ssh root@192.168.1.84
ssh: connect to host 192.168.1.84 port 22: Connection refused

So I'm baffled as to what's going on here. Why does ESXi think it's CentOS, and why can't I log into the console directly?

A: The VMWare Esxi server is a utility running on Centos 6.5. That's why it allows you to ssh on the server itself. Hence the reason you get the prompt when you login.
The messages that you get "/bin/bash: No such file or directory" is critical and indicates a problem with the filesystem on the host. However, since it is a minimalistic OS, not all operations are available and you have limited troubleshooting options.
If you are running the Esxi server on a VM, make sure all the mapped drives or partitions are fine and perform a filesystem check if you can, but in order to do that you need to enable SSH access on the Esxi host, remote login and perform troubleshooting on the OS. Another solution would be to replicate your data from the Esxi server and migrate it to another disk or physical server.
This might help to perform file system check on the Esxi host: http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2004299


text:
Q: Java jar error: Incompatible magic value
Exception in thread "main" java.lang.ClassFormatError: Incompatible magic value
  1347093252 in class file

Though the question is similar to this question, error continues after following the best answer. (i.e. after clearing the java cache from java control panal and deleting all temporary files.)


text:
Q: How can I make a div and its text disappear when window gets resized? I have a big container (over 2400 px wide) with 2 DIVs in it (see pictures attached). When the window gets resized or the computer's supported resolution is low, only DIV 1 should be visible, DIV 2 then should disappear.
I tried that:
@media all and (max-width: 1800px) {
  #DIV2 { display: none; }
}

and it worked, of course, but I want the text in DIV2 stay at its position and not shift to the left, when the window gets resized – even if it's just a few pixels. I played around with position properties and margins, but it didn't work. How can I fix the text?
Thanks in advance!

A: you can use border:none for this issue instead of display:none :
@media all and (max-width: 1800px) {
  #DIV2 { border: none; }
}


text:
Q: What part of initramfs (Ubuntu) runs scripts/local? I'm trying to understand how Ubuntu 12.04's initramfs runs scripts/local and in what order. I don't see it in init. What line of code runs scripts/local?

A: scripts/local is only run when using a local root filesystem (as opposed to a network filesystem). The BOOT variable in the init script is set to either local or nfs accordingly, so the following line sources scripts/local:
$ grep -A1 Mounting init
log_begin_msg "Mounting root file system"
. /scripts/${BOOT}


text:
Q: Python Grouping Transpose I have my data in a pandas dataframe
out[1]:
    NAME     STORE      AMOUNT
0   GARY     GAP          20
1   GARY     GAP          10
2   GARY     KROGER       15
3   ASHLEY   FOREVER21    30
4   ASHLEY   KROGER       10
5   MARK     GAP          10
6   ROGER    KROGER       30

I'm trying to get grouping by name, sum their total amount spent, while also generating columns for each unique store in the dataframe.
Desired:
out[1]:
    NAME      GAP      KROGER     FOREVER21
0   GARY      30        15            0
1   ASHLEY    0         10            30
2   MARK      10        0             0
3   ROGER     0         30            0

Thanks for your help!

A: You need pivot_table:
df1 = df.pivot_table(index='NAME',
                    columns='STORE',
                    values='AMOUNT',
                    aggfunc='sum',
                    fill_value=0)
print (df1)
STORE   FOREVER21  GAP  KROGER
NAME
ASHLEY         30    0      10
GARY            0   30      15
MARK            0   10       0
ROGER           0    0      30

Alternative solution with aggregating by groupby and sum:
df1 = df.groupby(['NAME','STORE'])['AMOUNT'].sum().unstack(fill_value=0)
print (df1)
STORE   FOREVER21  GAP  KROGER
NAME
ASHLEY         30    0      10
GARY            0   30      15
MARK            0   10       0
ROGER           0    0      30

Last if need column from index values and remove column and index names:
print (df1.reset_index().rename_axis(None, axis=1).rename_axis(None))
     NAME  FOREVER21  GAP  KROGER
0  ASHLEY         30    0      10
1    GARY          0   30      15
2    MARK          0   10       0
3   ROGER          0    0      30


text:
Q: How to filter data from Sqlite IOS Swift? Hi i am using following library for sqlite implementation in my project.
https://github.com/stephencelis/SQLite.swift
In my sqlite i am storing huge amount of data from there i am filtering my values. This is my tried code.
let user = self.usersTable.filter(self.id == textfild.text!)

        do {
            for row in try self.database.prepare(user) {
                print("id: \(row[self.id]), code: \(row[self.email])")

            }
        }catch {
            print(error)
        }

this code is working if the two values are same ex: ( 171(self.id value) == 171 )(textfield value) but i am looking for if i enter "17" it should shows all related data in sqlite.
user[self.id].localizedCaseInsensitiveContains(textfild.text) i tried this but its not working.


text:
Q: Extract HTML from  comment to a closing tag using jsoup java I have some HTML that looks like

Blah...

blah

I need to extract the HTML from the comment to a closing dl tag.  The closing dl is the first one after the comment (not sure if there could be more after, but never is one before).  The HTML between the two is variable in length and content and doesn't have any good identifiers.
I see that comments themselves can be selected using #comment nodes, but how would I get the HTML starting from a comment and ending with an HTML close tag as I've described?
Here's what I've come up with, which works, but obviously not the most efficient.
    String myDirectoryPath = "D:\\Path";
    File dir = new File(myDirectoryPath);
    Document myDoc;
    Pattern p = Pattern.compile("([\\S\\s]*?)</\\s*dl\\s*>");
    for (File child : dir.listFiles()) {
        System.out.println(child.getAbsolutePath());
        File file = new File(child.getAbsolutePath());
        String charSet = "UTF-8";
        String innerHtml = Jsoup.parse(file,charSet).select("body").html();
        Matcher m = p.matcher(innerHtml);
        if (m.find()) {
            Document doc = Jsoup.parse(m.group(1));
            String myText = doc.text();
            try {
                PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("D:\\Path\\combined.txt", true)));
                out.println(myText);
                out.close();
            } catch (IOException e) {
                //error                }
        }
    }

A: To use a regex, maybe something simple
 #  "([\\S\\s]*?)</\\s*dl\\s*>"

 ([\S\s]*?)
 </ \s* dl \s* >

A: Here's some example code - it may need further improvements - depending on what you want to do.
final String html = "
abc
" // Additional tag before the comment
        + "\n"
        + "
Blah...
\n"
        + "

blah

"
        + "
def
"; // Additional tag after the comment

// Since it's not a full Html document (header / body), you may use a XmlParser
Document doc = Jsoup.parse(html, "", Parser.xmlParser());

for( Node node : doc.childNodes() ) // Iterate over all elements in the document
{
    if( node.nodeName().equals("#comment") ) // if it's a comment we do something
    {
        // Some output for testing ...
        System.out.println("=== Comment =======");
        System.out.println(node.toString().trim()); // 'toString().trim()' is only out beautify
        System.out.println("=== Childs ========");

        // Get the childs of the comment --> following nodes
        final List<Node> childNodes = node.siblingNodes();

        // Start- and endindex for the sublist - this is used to skip tags before the actual comment node
        final int startIdx = node.siblingIndex();   // Start index - start after (!) the comment node
        final int endIdx = childNodes.size();       // End index - the last following node

        // Iterate over all nodes, following after the comment
        for( Node child : childNodes.subList(startIdx, endIdx) )
        {
            /*
             * Do whatever you have to do with the nodes here ...
             * In this example, they are only used as Element's (Html Tags)
             */
            if( child instanceof Element )
            {
                Element element = (Element) child;

                /*
                 * Do something with your elements / nodes here ...
                 *
                 * You can skip e.g. 'p'-tag by checking tagnames.
                 */
                System.out.println(element);

                // Stop after processing 'dl'-tag (= closing 'dl'-tag)
                if( element.tagName().equals("dl") )
                {
                    System.out.println("=== END ===========");
                    break;
                }
            }
        }
    }
}

For easier understanding, the code is very detailed, you can shorten it at some points.
And finally, here's the output of this example:
=== Comment =======

=== Childs ========

Blah...

  blah

=== END ===========

Btw. to get the text of the comment, just cast it to Comment:
String commentText = ((Comment) node).getData();


text:
Q: Display time to timeout session As Title, how to check/ display time to timeout session in the menu page?
We have web applicaion using ASP.NET, C# with menu.aspx is main page, when we click to menu then a new page will be opened. User could idle or interact with child page to reset session timeout.
I searched and found this, answer said to use javascript and reset timer whenerver detect an Ajax/WebSocket call.
But how to detect an Ajax/WebSocket call to reset the countdown?
Thank for any help!


text:
Q: header stretches instead of To make a long story short, the header class should be a black line across the entire screen. In HTML it will be a list. The list's children will be styled as buttons and should begin after the first 20% of the page. Somewhere along the line this is going terribly wrong, because:

*

*The list children aren't styled at all (the margin)

*The page stretches itself a lot.
Here is the entire source code:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title></title>

A: Replace your CSS with the following:
html, body {
     padding: 0;
     background-color:#FFFCF2;
     margin: 0 auto;
}

.header {
    list-style:none;
    width:100%;
    height:65px;
    font-size:3%;
    background: black;
    padding-left: 20%;
}

.header:first-child {
}

.headerChild {
    margin-left:0;
    float:left;
     height:65px;
     width:10%;
     background: white;
}

A: A few issues that I see:

*

*.header:first-child is applied to the
, so change it to .header>li:first-child and that will target the first
 and set its left margin

*You set your font size to 3% in .header and the
 inherit that, make sure that is what you want

*set padding:0 on .header as well to prevent the horizontal scrollbars.

Here's a Fiddle for you to look at. I've put red borders around the
 and text so you can see them.


text:
Q: Write c++ regular expression to match a #include preprocessing directive I want to write a regular expression in c++ to match a #include preprocessing directive.
So I wrote this:
std::regex includePattern("^[[:blank:]|[:space:]]*#[[:blank:]|[:space:]]*include[[:blank:]|[:space:]]+[<|\"]{1}[_[:alpha:]]+[_[:alnum:]]*");

This is worked for:
std::string matchString = "#include <vector>";

But only matches parts of the string excluded the trailing ">",
but if I change the regex to this:
std::regex includePattern("^[[:blank:]|[:space:]]*#[[:blank:]|[:space:]]*include[[:blank:]|[:space:]]+[<|\"]{1}[_[:alpha:]]+[_[:alnum:]]*[>|\"]{1}");

It just won't give me the desired result, just tell me "not found" ! Is there anything wrong?
Can anybody help me to write an accurate regular expression in c++ to match a #include preprocessing directive?
Thanks in advance!

A: It depends on whether the input to be matched may contain new
lines?  [[:space:]] will match any white space, including new
lines, [[:blank:]] will match any white space except new lines
(and I'm not sure it is supported by the standard).  Anyway,
something like:
"^\\s*#\\s*include\\s+[<\"][^>\"]*[>\"]\\s*"

should do the trick, but...

*

*If your source has new lines where it shouldn't, it still
might match.

*If your source has escaped new lines, say in the middle of the
token include or the file name, it won't match.  (This is
legal C++, but no one in their right mind would do it.)

*If your source has mismatched delimiters, a " at one end,
and a < or a < at the other, it will still match.

*And it doesn't handle comments at the end of line.  Handling
C++ style comments (//) should only be a matter of adding
"(?://.*)?" to the end of the expression.  Handling C style
comments (particularly since there can be several) is a bit more
complicated.
To ensure that the delimiters match, you'd probably have to put
everything after the include in an or:
"^\\s*#\\s*include\\s+(?:<[^>]*>|\"[^\"]*\")\\s*"

Again, you'd need to add to the end to handle comments.

A: You aren't validating are you ?
One thing, you might be able to count on include's coming after the BOL and possible spaces.
And delimited on its right side with a whitespace.
Other than that, I wouldn't try to validate whats on the right of that.
Using Multi-line modifier only -
"(?m)^[^\\S\\r\\n]*#include[^\\S\\r\\n]+(.*?)[^\\S\\r\\n]*"
Expanded:
 (?m)
 ^ [^\S\r\n]*
 \#include
 [^\S\r\n]+
 ( .*? )               # (1)
 [^\S\r\n]*

A: If you need to capture the type of inclusion < or " and the included file name you could use:
std::string reg = "\\s*#\\s*include\\s*([<\"])([^>\"]+)([>\"])"; // escaped version

- or -
std::string raw = R"reg(\s*#\s*include\s*([<"])([^>"]+)([>"]))reg"; // raw string version

Live Demo
Group 1 = `<` or `"`
Group 2 = file name
Group 3 = `>` or `"`

A: The following regex will match #include directives such as #include <vector>
^#include\s+<\w+>$

Note: this won't include directives such as #include stdio.h.


text:
Q: Scp issue with Keychain program In my Bash script, I use SCP to copy some files to another machine.
But I'm using Keychain program on all my hosts.
When the ssh-agent is already loaded by Keychain, there is no problem.
But, when the key of the remote host isn't already loaded, after the connection, Keychain displays a message to add the key, but never ask the passphrase...   The file is not copied...  and the connection isn't closed.
* keychain 2.7.1 ~ http://www.funtoo.org
* Waiting 5 seconds for lock...
* Found existing ssh-agent: 31914
* Adding 1 ssh key(s): /root/.ssh/id_rsa

With SSH, the passphrase prompt is correctly displayed, if the key is not loaded :
* keychain 2.7.1 ~ http://www.funtoo.org
* Found existing ssh-agent: 27551
* Adding 1 ssh key(s): /root/.ssh/id_rsa
Enter passphrase for /root/.ssh/id_rsa:

Is there a way/workaround to detect if the file has been copied ?
In fact, the root cause is the distant .bashrc I think ...  Keychain is launched when the .bashrc is sourced.
Edit : Keychain has a --noask option.  So SCP command works with this option, because passphrase isn't asked, but I really need to be asked about the key with SSH.
On Destination server, is it possible to detect if ssh OR scp command is launched ?

A: Assuming you have control of the .bashrc file on the remote system, why not just change the way keychain is started based on whether the session is a tty or not?  This way you could start it with the --noask option as you described when scp (no tty) is being used, and without that option for ssh.
if [ -t 1 ] then
  <start keychain normally>
else
  <start keychain with --noask>
fi


text:
Q: How can I reverse an ASCII character array? The objective of this program is inverting, or reversing, an array. For example, if I have "Hello, world!" the program is supposed to print "!dlrow ,olleH".
But instead of doing so, the program prints: "!dlrow world!". Can someone explain to me why?
My code so far is:
.data

msg:    .ascii    "Hello, world!\n"

len = . - msg

_start:

movl $msg, %eax
movl $len, %ebx
dec %ebx
dec %ebx
save:

movb msg(%ebx), %dl
mov %dl, (%eax)
inc %eax
dec %ebx
jnz save

movl $len,%edx
movl $msg,%ecx
movl $1,%ebx
movl $WRITE,%eax      # pedir write ao sistema
int  $LINUX_SYSCALL   # chama o sistema

movl $0,%ebx
movl $EXIT,%eax       # pedir exit ao sistema
int  $LINUX_SYSCALL   # chama o sistema


text:
Q: Delphi | Перерисовка высоты строк DBGridEh Имеется цикл, в котором перебираются гриды и записывается определенный размер шрифта. При этом размер высоты строк подстраивается только в том случае, когда я растягиваю грид. Пробовал обновить грид методом Refresh, но высота строк не изменяется. Как всё-таки сделать перерисовку высоты строк?

A: Для начале проверьте есть ли у грида в options включённым параметр Titles. Если выключен, то включите. Объявите класс
 TMyCustomGridHack = Class(TCustomGrid)
   Public
     Property RowHeights;
 end;

Далее, в том месте где у вас строки кода меняют размер шрифта припишите
  TMyCustomGridHack(DBGrid1).RowHeights[0] := 20; //где 20, это значение, на которое следует увеличивать.
  DBgrid1.Update;


text:
Q: AngularJs $resource use of isArray for both request and response Not sure if this is a stupid question or not, maybe I'm missing something. When customizing methods on $resource I can use isArray to specify if the resource is an array or not. The problem is that isArray is used, for example with POST, to check both the shape of the request body and of the response. This means that I cannot have, for example, a POST where I need an array of anything (i.e. a set of operations to add to a batch task) in my request and I send a single object as a response (the batch task itself).
This is not a coding problem, I can work around this, it's more a design question: why do response and request have to have the same shape? I do not think that's stated anywhere around how to build REST services, they might usually have the same shape but they do not have to. What am I missing?


text:
Q: Php: Why does my code echo all values in the table rather than just a subset of those values? My category table has the columns cat_id, cat_name, user_id and time_stamp.
I am trying to echo the cat_name rows that have a matching user_id of say 10, but instead all the cat_names in the table are being echoed. Can you tell me why please?
The user table is queried correctly: user_id is the corresponding value of username:
    //here is the user_id, which is the corresponding user_id for username Joe Blogs
    echo $user_id;

I just can't understand why my code echoes all the cat_names in the whole table - and not only those cat_names associated with the user_id.
Here's my code:
 $Number = "Joe Blogs";

$query = "SELECT * FROM user WHERE username = ?";
$stmt = $con->prepare($query) or die(mysqli_error($con));
$stmt->bind_param('s', $Number) or die ("MySQLi-stmt binding failed ".$stmt->error);
$stmt->execute() or die ("MySQLi-stmt execute failed ".$stmt->error);
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    //get the corresponding user_id in the row
    $user_id = $row["user_id"];

    //here is the user_id, which is the corresponding user_id for username Joe Blogs
    echo $user_id;
}

$sql = "SELECT cat_name FROM category WHERE $user_id = ?";

$stmt2 = $con->prepare($sql) or die(mysqli_error($con));
$stmt2->bind_param('i', $user_id) or die ("MySQLi-stmt binding failed ".$stmt2->error);
$stmt2->execute() or die ("MySQLi-stmt execute failed ".$stmt2->error);
$result2 = $stmt2->get_result();

while ($row[] = $result2->fetch_assoc()) {
    $data = $row;

    $json = json_encode($data);

}

echo $json;

A: If you look closely this line
$sql = "SELECT cat_name FROM category WHERE $user_id = ?";
// specifically here                        ^

will equate to
SELECT cat_name FROM category WHERE 10 = 10

As 10 = 10 will always be true, it returns all rows from your table
Correct this line like so
$sql = "SELECT cat_name FROM category WHERE user_id = ?";


text:
Q: Extracting a substring without delimiters comprising specific characters from a string in python I have a string and I want to extract a sub-string comprising of the following characters [A,T,C,G,\n] only.
This characters can appear in the sub-string in any order and number without a specific pattern.
I also don't have any constant delimiter before and after this sub-string that I can use.
Example of a full string and the sub-string I would like to extract in BOLD.

*

*

AC068547.7 Homo sapiens BAC clone RP11-458J7 from 2, complete sequence GAATTCAACTTTCTAGACCAATGATTTTTGGACTAATGATGTTTGGAGGGCCCAACAACCCAGAAAGTTGAATTCCAGTC\nTCCTTTAGTGAAAATAAA\n

*

AC1284347.7 Homo sapiens XXX clone RP11-1238J7 from 3,CDSTAGGGCTGAGATCGGCGTAAG\nGAGATCGGAGAGCTGAAT

A: You can use a regular expression to find all sequences consisting only of the given characters, and then select the longest match with max():
import re

example = 'AC1284347.7 Homo sapiens XXX clone RP11-1238J7 from 3,CDSTAGGGCTGAGATCGGCGTAAG\nGAGATCGGAGAGCTGAAT'
pattern = '[ACGT\n]*'

max(re.findall(pattern, example))

'TAGGGCTGAGATCGGCGTAAG\nGAGATCGGAGAGCTGAAT'
In case the string may contain several sequences of interest, you can use a list comprehension to return only those of a certain length:
[seq for seq in re.findall(pattern, example) if len(seq) >= 7]

['TAGGGCTGAGATCGGCGTAAG\nGAGATCGGAGAGCTGAAT']


text:
Q: Position object on screen in different resolutions / aspect ratios (orthographic) To be honest I am quite lost with world, screen and viewport coordinates in Unity.
My question is rather simple: in a 2d game how do I place an object in bottom left corner no matter what the resolution and screen aspect ratio is?

A: It is a little vague your description, but I think your talking about this:
Vector3 screenPos = new Vector3(x,y,z);

camera.ScreenToWorldPoint(screenPos);

As a side note, there are specific algorithms for 2D Unity, search for that also.
For Orthographic check this unity space which might help you:
http://answers.unity3d.com/questions/501893/calculating-2d-camera-bounds.html

A: I see no one ever followed up on this. Let's get some terms straight first:
Camera.main = the main camera that is looking at your game world
"game world" = the entire game map you've drawn
World Point = an absolute, unique position in the game world. Can be 2D or 3D (x,y,z)
Screen Point = a 2D x,y location of a pixel on the screen
So, when you want to place an object (i.e.transform its location) what you are really doing is placing it somewhere within the Game World. If the camera happens to be looking at that location in the World then it will appear on screen.
To figure out what parts of the World are currently on screen, you must convert a Screen Point to a World Point. So...assuming your object's size is 20x20, try this:
//Attach this script to the item you want "pinned" to the bottom, left corner of the screen
void Update() {
  //fetch the rectangle for the whole screen
  Rect viewportRect = Camera.main.pixelRect; //again, this has nothing to do with the World, just the 2D screen "size", basically

  //now, let's pick out a point on the screen - bottom, left corner - but leave room for the size of our 20x20 object
  Vector3 newPos = new Vector3(viewportRect.xMin + 20, Camera.main.pixelHeight - 20, 0);

  //now calculate where we need to place this item in the World so that it appears in our Camera's view (and, thus, the screen)
  this.transform.position = Camera.main.ScreenToWorldPoint(newPos);
}

I'm 98% certain this is all accurate info but if someone sees a mistake please point it out.


text:
Q: Check float value in dictionary for conditions in Python I have a dictionary as shown in the picture and I'm wondering how should I code something in to check for each value for each key and check them to see if they meet a certain condition like a value above 8 and such.
http://i.imgur.com/qtfkK61.png
The values are float and there are multiple values per a dictionary value of region.
def main(): #defining main function
    magList = [] #magnitude list of all together
    regionList = [] #creating list to hold region names
    wholeList = []
    combinedList = []

    with open("earthquakes.txt", "r") as eqList: #opens earthquake text file and gets the magnitudes
        eqList.readline()
        for line in eqList:
            line = line.split()
            magList.append(float(line[1])) #appends magnitude as float values in list

    with open("earthquakes.txt", "r") as eqList2: #open file 2nd time for gathering the region name only
            eqList2.readline()
            for line in eqList2:
                line = line.split()
                line = line[0:7] + [" ".join(line[7:])] #takes whole line info and adds to list
                wholeList.append(line)

    greatMag = [] #creating lists for different category magnitudes
    majorMag = []
    strongMag = []
    moderateMag = []

    for x in magList: #conditions for seperating magnitude
        if x >= 8:
            greatMag.append(x)
        elif  7 <= x <= 7.9:
            majorMag.append(x)
        elif 6 <= x <= 6.9:
            strongMag.append(x)
        elif 5 <= x <= 5.9:
            moderateMag.append(x)

    for line in wholeList: #takes only magnitude and region name from whole list
        combinedList.append([line[7], line[1]])

    infoDict = {} #creates dictionary
    for key, val in combinedList: #makes one key per region and adds all values corresponding to the region
        infoDict.setdefault(key, []).append(val)
    print(infoDict)

    for k, v in infoDict.items():
        for i in v:
            if i >= 8:
                print("Great Magnitude:", i)
                pass

if __name__ == "__main__": #runs main function
    main()

A: for k,v in d.items(): # iterate through key, value of dict 'd'
  for i in v: # iterate to dict value which is a list
    if i > 8: # your condition
      # do something here
      pass


text:
Q: display the CMD console in a window in GUI - PySimpleGUI I'm creating a GUI using PySimpleGUI and want to have a frame that displays the output prints of all the functions in the program (as in the cmd console).
I tried using (relevant code lines):
def hello():
    print('hello')

layout = [[sg.Frame("Output console", [[sg.Text(" ", size=(0, 1), key='-OUTPUT-')]])]]
window['-OUTPUT-'].update(hello())

I can see the print in the console but not in the Frame in the GUI.
How can i do that?

A: To show the output like in CMD console, you should use the sg.Multiline, not the sg.Text which is just a label.
To redirect the output of stdout and stderr, set options reroute_stdout=True and reroute_stderr=True, also set option autoscroll=True to automatically scroll as more data added to the end of element.
Demo Code - GUI will update only back to window.read
import PySimpleGUI as sg

def hello():
    print('hello')

frame_layout = [[sg.Multiline("", size=(80, 20), autoscroll=True,
    reroute_stdout=True, reroute_stderr=True, key='-OUTPUT-')]]

layout = [
    [sg.Frame("Output console", frame_layout)],
    [sg.Push(), sg.Button("Say Hello")],
]
window = sg.Window("Title", layout, finalize=True)

while True:
    event, values = window.read()
    if event == sg.WINDOW_CLOSED:
        break
    elif event == "Say Hello":
        hello()

window.close()

To update GUI in realtime, you can call update(value, append=True) and window.refresh, not to use the print statement, or
Following code show the way to print to sg.multiline immediately. To avoid   stop GUI working for long printing, mutlithread required here. It will not work for real time printing during event loop because loop is working on your printing statement, then back to window.read after it done.
It is much complex, not sure if any bug.
import sys
from time import sleep
from datetime import datetime
import threading
import PySimpleGUI as sg

def print_task():
    global printing
    while printing:
        print(datetime.now().strftime("%H-%M-%S"), datetime.now().strftime("%H-%M-%S"))
        sleep(0.5)

class Unbuffered(object):
    def __init__(self, window):
        self.window = window
    def write(self, data):
        self.window.write_event_value("OUT", data)
    def writelines(self, datas):
        self.window.write_event_value("OUT", ''.join(datas))

frame_layout = [[sg.Multiline("", size=(80, 20), autoscroll=True, key='-OUTPUT-')]]

layout = [
    [sg.Frame("Output console", frame_layout)],
    [sg.Push(), sg.Button("Print"), sg.Button('Stop')],
]
window = sg.Window("Title", layout, finalize=True)
old_stdout, old_stderr = sys.stdout, sys.stderr
sys.stdout = Unbuffered(window)
sys.stderr = Unbuffered(window)
printing = False

while True:
    event, values = window.read()
    if event == sg.WINDOW_CLOSED:
        break
    elif event == 'Print':
        if not printing:
            printing = True
            threading.Thread(target=print_task, daemon=True).start()
    elif event == 'Stop':
            printing = False
    elif event == "OUT":
        window['-OUTPUT-'].update(values["OUT"], append=True)

printing = False
sys.stdout, sys.stderr = old_stdout, old_stderr
window.close()


text:
Q: retrieve data from database recursively I am new to node.js and working with database. how can I change my html to fetch next 4 items from database continuously?
I can show only 4 items now.

const BlogPost = require('../models/BlogPost.js')

module.exports = async (req, res) =>{
    const blogposts = await BlogPost.find({}).sort({_id:-1}).limit(4).skip(4).populate('userid')

    res.render('index',{
        blogposts
    });
}

d

  <% for (var i = 0; i < blogposts.length; i++) { %>

      <a href="post/<%= blogposts[i]._id %>">
      <img src="<%= blogposts[i].image %>" class="card-img-top " alt="...">

<%= blogposts[i].title %>

        <%= blogposts[i].datePosted.toDateString() %>

  <% } %>

below code is for infinite scroll I wanna append my above html code every time user scrolls to bottom

 window.addEventListener("load", (event) => {
        divElement = document.querySelector("#divscroll");

        createObserver();
      }, false);

      function createObserver() {
        let observer;

        let options = {
          root: null,
          rootMargin: "0px",
          threshold: 1
        };

        observer = new IntersectionObserver(handleIntersect, options);
        observer.observe(divElement);
      }

      function handleIntersect(entries, observer) {
       //add function for loading next items
      }


text:
Q: Javascript Changing Class' Style I want to change the background color of a class named "Zones" to blue and i've tried:
document.getElementsByClassName("Zones").style.backgroundColor = "blue";

But it's for some reason not working...

A: If there is only one class, you can do this:
document.getElementsByClassName("Zones")[0].style.backgroundColor = "blue";

If there is more than 1 class, you can do this:
var zonesLength = document.getElementsByClassName.length;

for(i = 0; zonesLength < i; i++) {
    document.getElementsByClassName("Zones")[i].style.backgroundColor = "blue";
}


text:
Q: How do I avoid a redundant trailing newline when concatenating two files? I want to merge two files into one file and when I do it at the end of the my merged file there is an extra blank line, How can I delete it?
file1 contains:
1  2  3

and file2 contains:
4  5  6

the the merged file is like
1  2  3
4  5  6
<------cursor is here

here is my code:
ifstream read1("1.txt");
ifstream read2("2.txt");

ofstream write ("3.txt");

string line;
string line2;

while ( getline ( read1, line, '\n' ) )
{
 if (!line.empty())
  write << line << endl;
}

while ( getline ( read2, line2, '\n' ) )
{
 if (!line2.empty())
  write << line2 << endl;
}

read1.close();
read2.close();
write.close();

A: Using the streambuf overload for operator<< we can do:
#include <fstream>

int main()
{
    std::ifstream read1("1.txt");
    std::ifstream read2("2.txt");
    std::ofstream write("3.txt");
    write << read1.rdbuf() << '\n' << read2.rdbuf();
}

A: Before the second while read the first line, write it to the file and then
use the while as you do but enter a new line first.
Something like this:
getline(read2 , line2, '\n');
if (!line2.empty())
   write << line2;

while ( getline ( read2, line2, '\n' ) )
{
 if (!line2.empty())
  write << endl <<line2;
}

This is not exactly what you ask but it should do the trick.

A: Test for end of input file and don't put additional newline at the end.
Change
write << line2 << endl;

to
{
    write << line2;
    if (!read2.eof()) {write << "\n";}
}

EDIT: I have added curly braces to compensate for your single line IF's. Please try to avoid it in your code. See how George easily fell into that trap.

A: << endl will flush the buffer and add a '\n'
You can think of it was being equivalent to adding a '\n' at the end, for added simplicity.
If you want to never add a newline just write the code as:
    ifstream read1("1.txt");
    ifstream read2("2.txt");
ofstream write ("3.txt");

string line;
string line2;

while ( getline ( read1, line, '\n' ) )
{
 if (!line.empty())
  write << line;
}

while ( getline ( read2, line2, '\n' ) )
{
 if (!line2.empty())
  write << line2;
}

read1.close();
read2.close();
write.close();

If you wish to write a newline after every line in the fact except the last line of the last file than buffer the thing into a string and write that to the file... not the most efficient option maybe, but good enough:
ifstream read1("1.txt");
ifstream read2("2.txt");

ofstream write ("3.txt");

string line;
string line2;
string buffer
while ( getline ( read1, line, '\n' ) )
{
 if (!line.empty())
  buffer += line;
  buffer += "\n";
}

while ( getline ( read2, line2, '\n' ) )
{
 if (!line2.empty())
        buffer += line2;
        buffer += "\n";
}

//Remove the last char from buffer (the '\n' bothering you)
buffer.substr(0, myString.size()-1)
write << buffer;

read1.close();
read2.close();
write.close();

Marek Vitek's answer is actually better than mine:
ofstream write ("3.txt");

string line;
string line2;

while ( getline ( read1, line, '\n' ) )
{
 if (!line.empty())
  write << line << endl;
}

while ( getline ( read2, line2, '\n' ) )
{
 if (!line2.empty()) {
  write << line2
 }
 if(!line2.empty() && !read2.eof() {
  write << line2 << endl;
 }
}

read1.close();
read2.close();
write.close();

A: How about raw copy:
std::ifstream read1{path1};
read1.unsetf(std::ios_base::skipws);
std::ifstream read2{path2};
read2.unsetf(std::ios_base::skipws);
std::ofstream write{path3};

std::copy(std::istream_iterator<char>(read1),
          std::istream_iterator<char>(),
          std::ostream_iterator<char> (write));

write << '\n'; // extra EOL between file

std::copy(std::istream_iterator<char>(read2),
          std::istream_iterator<char>(),
          std::ostream_iterator<char> (write));

A: Another short solution (though I don't know what should be wrong with the final newline in the merged result):
ifstream read1("1.txt");
ifstream read2("2.txt");

ofstream write ("3.txt");

string line;
string line2;

do {
    if (!line.empty())
       write << line << '\n';
} while( getline ( read1, line, '\n' ) )
write.flush();

do {
    if(!line2.empty())
        write << line2;
} while( getline ( read2, line2, '\n' ) && write << `\n`);

read1.close();
read2.close();
write.close();

A: merge two file that has extra newline
std::ifstream ifs_1( "file1" );
std::ifstream ifs_2( "file2" );

std::ofstream ofs( "file3" );

for( std::string line; std::getline( ifs_1, line ); ){
    if( line != "" ){
        ofs << line << '\n';
    }
}
for( std::string line; std::getline( ifs_2, line ); ){
    if( line != "" ){
        ofs << line << '\n';
    }
}

ifs_1.close();
ifs_2.close();

ofs.close();

test:
cat file1
one
two
--> empty
--> empty

and file2:
cat file2:
three
four
--> empty
--> empty

the output:
cat file3
one
two
three
four


text:
Q: Why am I getting no output? I have a pretty simple question really - why am I getting no output? This is the site: https://riven.market/list/PC/Veiled. I thought the problem was the spaces in class name but turns out its natural and shouldnt cause any problems. If you have any questions let me know in the comments
import requests
from bs4 import BeautifulSoup

r = requests.get("https://riven.market/list/PC/Veiled")

c = r.content

soup = BeautifulSoup(c, "html.parser")
all = soup.find_all("div", {"class":"riven-list" })
for item in all:
    print("Name" + item.find("div", {"class": "attribute weapon"}).text.replace("\n", "").replace(" ", ""))

A: Here is my workaround way, which is to find the actual URL the query is sending the request to. You can find it by rightclick-> inspect element -> network -> Find the get request

import requests
from bs4 import BeautifulSoup

# instead of sending to this
main = requests.get("https://riven.market/list/PC/Veiled")

ajax_url = "https://riven.market/_modules/riven/showrivens.php?baseurl=Lw==&platform=PC&limit=25&recency=-1&veiled=true&onlinefirst=true&polarity=all&rank=all&mastery=16&weapon=Any&stats=Any&neg=all&price=99999&rerolls=-1&sort=time&direction=ASC&page=1&time=1565851905857"
re = requests.get(ajax_url)
c = re.content

soup = BeautifulSoup(c, "html.parser")
all_divs = soup.find_all("div", class_ ="attribute weapon" )
for item in all_divs:
        print(item.text)

Outputs

        Pistol Riven Mod
        new

        Pistol Riven Mod
        > 1 day

        Pistol Riven Mod
        > 1 day

        Pistol Riven Mod
        new

        Pistol Riven Mod
        new

        Pistol Riven Mod
        > 1 day

        Pistol Riven Mod
        > 1 day

        Pistol Riven Mod
        > 1 day

        Melee Riven Mod
        > 1 day

        Shotgun Riven Mod
        > 1 day

        Pistol Riven Mod
        > 1 day

        Pistol Riven Mod
        > 1 day

        Pistol Riven Mod
        > 1 week

        Melee Riven Mod
        > 1 week

        Rifle Riven Mod
        > 1 week

        Shotgun Riven Mod
        > 1 week

        Pistol Riven Mod
        > 1 week

        Pistol Riven Mod
        > 1 week

        Pistol Riven Mod
        > 1 week

        Pistol Riven Mod
        > 1 week

        Rifle Riven Mod
        > 1 week

        Rifle Riven Mod
        > 1 week

        Melee Riven Mod
        > 1 week

        Shotgun Riven Mod
        > 1 week

        Rifle Riven Mod
        > 1 week

A: Not sure what you want exactly as your output, but you need to make a few modifications to the request url and add the query parameters:
import requests
from bs4 import BeautifulSoup

url = 'https://riven.market/_modules/riven/showrivens.php'

payload = {
'baseurl': 'Lw==',
'platform': 'PC',
'limit': '25',
'recency': '-1',
'veiled': 'true',
'onlinefirst': 'true',
'polarity': 'all',
'rank': 'all',
'mastery': '16',
'weapon': 'Any',
'stats': 'Any',
'neg': 'all',
'price': '99999',
'rerolls': '-1',
'sort': 'time',
'direction': 'ASC',
'page': '1',
'time': '1565851478713'}

r = requests.get(url, params=payload)

c = r.content

soup = BeautifulSoup(c, "html.parser")
all_divs = soup.find_all("div", {"class":"riven " })
for item in all_divs:
    print("Name" + item.find("div", {"class": "attribute weapon"}).text.replace("\n", "").replace(" ", ""))

Output:
newtolRivenMod
>1daylRivenMod
>1daylRivenMod
newtolRivenMod
newtolRivenMod
>1daylRivenMod
>1daylRivenMod
>1daylRivenMod
>1dayRivenMod
>1dayunRivenMod
>1daylRivenMod
>1daylRivenMod
>1weekRivenMod
>1weekivenMod
>1weekivenMod
>1weeknRivenMod
>1weekRivenMod
>1weekRivenMod
>1weekRivenMod
>1weekRivenMod
>1weekivenMod
>1weekivenMod
>1weekivenMod
>1weeknRivenMod
>1weekivenMod


text:
Q: Typescript types for Firebase I want to be able to reference the  interface for IdTokenResult so I can use like in the below code.
export interface AppContextProps {
  token: firebase.auth.IdTokenResult | undefined,
  updateAppContext(newContext: any): void | undefined,
}

If I import firebase like this as pretty much all online documentation recommends
import firebase from "firebase/app"
import "firebase/auth"
import "firebase/database"
import "firebase/firestore"
import "firebase/firebase-storage"

I can't figure out how to access that interface since firebase.auth.IdTokenResult doesn't seem to exist. However if I import firebase like this...
import firebase from "firebase"

I am able to access the interface I desire but I get warnings in the browser about running firebase in dev mode. How can I do what I want correctly?

A: It seems like every file I want to use firebase stuff in I need to do...
import firebase from "firbase/app"
import "firebase/<whatever>"

To avoid doing this everywhere I was doing something like this...
import firebase from "firbase/app"
import "firebase/auth"
import "firebase/database"
import "firebase/firestore"
import "firebase/firebase-storage"

const auth: firebase.auth.Auth = firebase.auth()
const storage: firebase.storage.Storage = firebase.storage()
const app: firebase.app.App = firebase.app()
export {auth, storage, app}

Then I was trying to just import the auth object where ever I wanted but it seems like firebase sdk objects to this pattern because it thinks I'm importing more than I need. IDK maybe this can still work but as soon as I just went straight to importing on a per file basis the warning message went away.


text:
Q: OpenCV C# don't show video camera I have this:
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using OpenCvSharp;

namespace camara_opencv
{
    public partial class Form1 : Form
    {
        string rtspUrl = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov";
        VideoCapture video = new VideoCapture();
        public Form1()
        {
            InitializeComponent();
            pictureBoxImage.SizeMode = PictureBoxSizeMode.StretchImage;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            video.Open(rtspUrl);

            using (Mat image = new Mat())
            {
                while (true)
                {
                    if (!video.Read(image))
                    {
                        Cv2.WaitKey();
                    }
                    if (!image.Empty())
                    {
                        Bitmap bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(image);
                        pictureBoxImage.Image = bmp;
                    }
                    if (Cv2.WaitKey(1) >= 0)
                        break;
                }
            }
            video = null;
        }
    }
}

in windows form I added PictureBox and Button, I clicked on start, It runs without error, but it don't show nothing, what I'm doing wrong?
I'm Learning about opencv, I have a camera public, It's in rtsp, so I just capture video and show It in form picturebox


text:
Q: Adding output parameter to Python script tool? How do you add an output parameter in a python script in a toolbox?

A: This was a simple question that had found difficult to answer.  I searched through the Esri documentation, which is usually very thorough, but just overlooked it.  I wanted to share my answer here in a concise manner.

*

*In the Parameters dialog, set up a parameter, and set its direction to "output".  Set the type to "Derivative" if applicable.

*In the script, use the following command to pass the the feature set/value as output ("1" here is the index for the parameter):

*arcpy.SetParameter(1, OutFeatureSet)
(Thanks to Mark's question on the Esri Forums for pointing me to the correct answer! https://geonet.esri.com/thread/57822)

A: If your input will be the same as your output then you don't need to add a parameter in your code; just create a parameter in your tool and set as you referenced.  The obtained from property of the output should be set to your input parameter.  This will create an output result to use add an input in model builder.  Also, in your code, set your environment for overwrite to true.
https://gisnuts.com/terra/blog/2012/09/05/5-tips-for-writing-python-script-tools-applied-to-an-autonumber-tool


text:
Q: meaning of ''he took on targets once seen as all but untouchable'' It's an article in Reuters I can't get the meaning of bold part

In three hours of blazing exchanges with his rivals, he took on
  targets once seen as all but untouchable, including the judicial
  establishment and the Revolutionary Guards, the elite military force
  that controls much of Iran's economy.

would you give me the meaning of that part word by word?

A: he took on - he engaged or focused on
targets - things
once seen as - formerly understood to be
all but untouchable - effectively unreachable

A: Without the full context I can't be sure, but I assume the he in this sentence was exchanging words with other people, perhaps politicians or leaders in a court or some sort of forum.
To say he took on targets means that he levelled some criticism at and/or insulted some groups (such as the judicial establishment and the Revolutionary Guards). To say that these targets were once seen as all but untouchable it means that the targets were so revered, respected, feared etc. that to challenge them or speak ill of them was something that wasn't even considered before this person came along. That other people thought they were too big or too important or too scary to say anything bad about or question.
With further context I can be more specific; there isn't enough context supplied to be exact.


text:
Q: Filling in select field form with mechanize I'm trying to fill out 3 select fields in a form like so.
br.select_form(name='frmentermemorableinformation1')
br['frmentermemorableinformation1:strEnterMemorableInformation_memInfo1'] = ['g']
When running the program I get the following error.
ItemNotFoundError: insufficient items with name 'g'
This is the start of the relevant form and the first of 3 select inputs.
<form id="frmentermemorableinformation1" name="frmentermemorableinformation1" method="post" action="/personal/a/logon/entermemorableinformation.jsp" class="validationName:(frmentermemorableinformation1) validate:()" autocomplete="off" enctype="application/x-www-form-urlencoded">
<fieldset class="memInfoSelect clearfix">

Character 5  <select id="frmentermemorableinformation1:strEnterMemorableInformation_memInfo1" name="frmentermemorableinformation1:strEnterMemorableInformation_memInfo1"><option value="-">Select</option><option value="&nbsp;a"> a</option><option value="&nbsp;b"> b</option><option value="&nbsp;c"> c</option><option value="&nbsp;d"> d</option><option value="&nbsp;e"> e</option><option value="&nbsp;f"> f</option><option value="&nbsp;g"> g</option><option value="&nbsp;h"> h</option><option value="&nbsp;i"> i</option><option value="&nbsp;j"> j</option><option value="&nbsp;k"> k</option><option value="&nbsp;l"> l</option><option value="&nbsp;m"> m</option><option value="&nbsp;n"> n</option><option value="&nbsp;o"> o</option><option value="&nbsp;p"> p</option><option value="&nbsp;q"> q</option><option value="&nbsp;r"> r</option><option value="&nbsp;s"> s</option><option value="&nbsp;t"> t</option><option value="&nbsp;u"> u</option><option value="&nbsp;v"> v</option><option value="&nbsp;w"> w</option><option value="&nbsp;x"> x</option><option value="&nbsp;y"> y</option><option value="&nbsp;z"> z</option><option value="&nbsp;0"> 0</option><option value="&nbsp;1"> 1</option><option value="&nbsp;2"> 2</option><option value="&nbsp;3"> 3</option><option value="&nbsp;4"> 4</option><option value="&nbsp;5"> 5</option><option value="&nbsp;6"> 6</option><option value="&nbsp;7"> 7</option><option value="&nbsp;8"> 8</option><option value="&nbsp;9"> 9</option></select>

What exactly am I doing wrong, I tried adding &nbsp; to the start of g incase that was the issue but i just get the same error with '&nbsp;g' replacing 'g'. Thanks.

A: Try '& g'..................
This works for me: ' g'  (inside the list)
I don't think there was an easy way to figure out exactly what the correct value was to use in your python code.  You don't normally see values like that.  I just used mechanize to print out what it thinks the values are:
import mechanize

br = mechanize.Browser()
br.open("http://localhost:8080/1.htm")
br.select_form(name='frmentermemorableinformation1')

select = br.form.find_control("frmentermemorableinformation1:strEnterMemorableInformation_memInfo1",
                     type='select')

for item in select.items:
    print item.attrs['value']

--output:--
-
 a
 b
 c
 d
 e
 f
 g
...
...

I guess I should look up some html to understand why it wanted me to
  enter the string rather than the value and what   does and
  why amp isnt present in the string version.

There are certain characters that are illegal inside html.  For instance, one of them is '<' because it looks like the start of a tag.  But what if you want to display 'x < 3'  on your html page?  Html provides a syntax that lets you include illegal characters inside html using what are called 'html entities'.  To include a '<' character on your page, you use the html entity < ("less than").  Html entities start with an '&', are followed by some numbers or some characters which represent the illegal character, and end with a semi-colon.
Because html entities start with an '&', that means you can't write '&' in your html when you want to display the '&' character on your page--because html will think the '&' is the start of an html entity.  So you have to use an html entity for '&', which happens to be &  ("ampersand").
There is an html entity   ("non-breaking space"), which creates a space in html.  Generally, html collapses all white space, so   is used to create spaces that won't collapse.  However, note that in the value attributes of the options, it is written 'nbsp;', which is not an html entity because it doesn't start with '&', so it is just a series of characters that is part of the value.  So each option's value is a combination of:
&  (represented by an html entity as required)

and the characters:
nbsp;g

Those are really strange values.


text:
Q: Issue with CountIFS trying to use a range as criteria I have a dataset with two columns, with each entry listing both a caseworker and a company. So far, I have set things up so that I can see a count of how many times each caseworker works on each company. I've done this by using a =COUNTIF function, as shown in the screenshot below.

My question is this: how do I count the number of times a given caseworker has worked with a given group of companies? I tried to do it with the following formula, but it simply returns 0 when I reference the grouped range in J2:J4:
=CountIFS('All Report'!$B$1:$B, $A2, 'All Report'!$A$1:$A, $J$2:$J$4)

Here's a link to a copy of my Google Sheet:
Link

A: Answer
One immediate issue is that the company groups listed on your Main sheet are comprised of TestGroupA through TestGroupF, whereas the companies in your All Report sheet are GroupTestA through GroupTestF (the words are reversed).
Once that is corrected, the following formula should produce the desired behaviour when placed into cell G2 and autofilled into the cells below it.
=SUM(COUNTIFS('All Report'!$B$1:$B, $A2,'All Report'!$A$1:$A,$J$2),COUNTIFS('All Report'!$B$1:$B, $A2,'All Report'!$A$1:$A,$J$3),COUNTIFS('All Report'!$B$1:$B, $A2,'All Report'!$A$1:$A,$J$4))

Alternatively, you could use the =QUERY function if you wanted something more scalable to large groups of companies.
=QUERY({'All Report'!$A$1:A,'All Report'!$B$1:$B},"select count(Col1) where (Col1 matches '"&JOIN("|",{$J$2:$J$4})&"') and Col2='"&$A3&"' label count(Col1) ''")

Explanation
The way you currently have your =COUNTIFS function set up, it is attempting to compare each cell of column A of your All Report sheet to an array. Therefore, you never get a match because no individual cell will match the full J2:J4 array.
The first solution I provide simply completes three =COUNTIFS—one on each company in the group—and sums their results together.
The second solution uses the =QUERY function to get a count of the number of rows that match certain criteria. The first of those criteria uses a regex search to check if any of the companies in the group are present in column A. The second criteria checks if the specified caseworker is in the same row but in column B. Together, this means that the query will count each time a specified caseworker appears with any of the specified companies.
Functions used:

*

*SUM

*COUNTIFS

*QUERY

*JOIN


text:
Q: Variance of a Straight line model [time series with deterministic mean] I have been given the question -
Consider the linear trend model:  = 0 + 1 +  + 0.5−1. You can assume 0=10, 1=0.2 and ^2=1. Find Var().
I tried solving this question by doing this -
var() = var(0 + 1 +  + 0.5−1)
var() = var(0) + var(1) + var() + var(0.5−1)
var() = 0 + (1^2).var() + ^2 + (0.25).^2
var() = (0.04).var() + 1 + 0.25
var() = (0.04).var() + 1.25
I am not sure if this is the right approach. And if it is what exactly is the value of var()?
Any help in guiding towards the solution would be appreciated.


text:
Q: bluez rfcomm connect fail I am trying connect Ubuntu pc with device. While command entered, it returns various error including rfcomm connect address already in use 、 host is down 、 rfcomm connect now in progress.
Device environment and procedure as below
Device environment

*

*Linux 3.4

*Bluez 5.19

*bt addr xx:xx:xx:xx:38:A4

PC environment

*

*Ubuntu 14.04

*bluez 4

*bt addr xx:xx:xx:xx:CF:F0

steps
device

*

*insmod rfcomm.ko  rtk_btusb.ko

*dbus-daemon --config-file=/etc/dbus-1/system.conf

*bluetoothd -C &

*hciconfig hci0 up

*hciconfig hci0 piscan

*sdptool add SP

*bluetoothctl scan on

*bluetoothctl agent on

*bluetoothctl default-agent

*bluetoothctl trust xx:xx:xx:xx:CF:F0

*bluetoothctl pair xx:xx:xx:xx:CF:F0

*rfcomm bind 0 xx:xx:xx:xx:CF:F0 1

*chmod 666 /dev/rfcomm0

*rfcomm connect 0 xx:xx:xx:xx:CF:F0 1

PC

*

*sdptool add SP

*rfcomm bind 0 xx:xx:xx:xx:38:A4 1

*chmod 666 /dev/rfcomm0

*rfcomm watch 0 1

Device show Can't connect RFCOMM socket: Host is down
hciconfig -a output
hci0:   Type: BR/EDR  Bus: USB
        BD Address: 5C:F3:70:1B:38:A4  ACL MTU: 820:8  SCO MTU: 255:16
        UP RUNNING PSCAN ISCAN
        RX bytes:6888 acl:88 sco:0 events:230 errors:0
        TX bytes:4341 acl:84 sco:0 commands:87 errors:0
        Features: 0xff 0xff 0xff 0xfe 0xdb 0xff 0x7b 0x87
        Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3
        Link policy: RSWITCH HOLD SNIFF PARK
        Link mode: SLAVE ACCEPT
        Name: 'BlueZ 5.19'
        Class: 0x000000
        Service Classes: Unspecified
        Device Class: Miscellaneous,
        HCI Version: 4.0 (0x6)  Revision: 0xe2f
        LMP Version: 4.0 (0x6)  Subversion: 0x9f73
        Manufacturer: Realtek Semiconductor Corporation (93)

Is any step missed in my procedure?

A: below steps works for me.
PC side

*

*sdptool add SP

*rfcomm -i hci0 watch 0 1 ./picocom /dev/rfcomm0

Device side

*

*sdptool add SP

*rfcomm connect 0 xx:xx:xx:xx:xx:F0 1 &

*picocom /dev/rfcomm0

reference


text:
Q: Minimizing a function with vectors This is a part of a problem that I'm having, and I'm unclear how to do this particular step. I'm dealing with a ridged regression and I need to minimize the equation
$$\sum (Y_i - \beta^Tx_i)^2 + \lambda\sum\beta_j^2$$
The question says I need to find $\beta$ that minimizes this and I'm not sure how to do that because I have a vector.
How do I do this?

A: Lets us define
$$ E = \sum (Y_i -\beta^T x_i)^2+ \lambda \sum \beta_j^2$$
And we want to find optimal values for $\beta$. Thus we take the derivative of $E$ with respect to $\beta$ (Note that $x_{ij}$ means component $j$ of vector $x_i$).
\begin{align}
\nabla_\beta E &= \begin{pmatrix} \frac{\partial}{\partial \beta_1}\\ ..\\ \frac{\partial}{\partial \beta_n}\end{pmatrix}E \\
&= \begin{pmatrix} \frac{\partial}{\partial \beta_1}(\sum (Y_i -\beta^T x_i)^2+ \lambda \sum \beta_j^2)\\ ..\\ \frac{\partial}{\partial \beta_n}(\sum (Y_i -\beta^T x_i)^2+ \lambda \sum \beta_j^2) \end{pmatrix} \\
&= \begin{pmatrix} \sum -2x_{i1}(Y_i -\beta^T x_i)+ 2\lambda \beta_1\\ ..\\ \sum -2x_{in}(Y_i -\beta^T x_i)+ 2\lambda \beta_n \end{pmatrix} \\
&= \begin{pmatrix} \sum -2x_{i1}Y_i +\sum 2x_{i1} \beta^T x_i+ 2\lambda \beta_1\\ ..\\ \sum -2x_{in}Y_i +\sum 2x_{in} \beta^T x_i+ 2\lambda \beta_n\end{pmatrix} \\
&= \begin{pmatrix} \sum -2x_{i1}Y_i +2\sum \beta_j \sum x_{i1}  x_{ij}+ 2\lambda \beta_1\\ ..\\ \sum -2x_{in}Y_i +2\sum \beta_j \sum x_{in}  x_{ij}+ 2\lambda \beta_n\end{pmatrix} \\
&= A\beta +r
\end{align}
Where
\begin{align}
A = 2\begin{pmatrix}
\lambda +\sum x_{i1}x_{i1} & \sum x_{i1}x_{i2} &  \sum x_{i1}x_{i3} & ... & \sum x_{i1}x_{in} \\
\sum x_{i2}x_{i1}
 & \lambda + \sum x_{i2}x_{i2} & \sum x_{i2}x_{i3} & ... & \sum x_{i2}x_{in} \\
... & ... & ... & ... & ... & \\
\sum x_{in}x_{i1}
 &  \sum x_{in}x_{i2} & \sum x_{in}x_{i3} & ... &\lambda+ \sum x_{in}x_{in}
\end{pmatrix}
\end{align}
And
\begin{align}
r = -2\begin{pmatrix}\sum x_{i1}Y_i \\ ..\\\sum x_{in}Y_i \end{pmatrix}
\end{align}
To obtain a minima, we need to solve $A\beta+r=0$. This gives you $\beta$.
I really encourage you, to check my indices and sums, as I did this rather quick.