text:
Q: IIS 8.5 Win 8.1 pro localHost not working I have researched for days and not found an answer.  I have used both google and Stack and MDSN so I finally thought it is time to ask the question.  I am a new developer I completed my first assignment and my computer died.  I got Win 8.1 pro and IIS 8.5 and now I am tasked with making that work with SQL 2012.  I have it so I can load up the localhost to the first page of the app which is a login and then when I am debuging using Visual Studio after I start to log in
the first call to the db this comes up
An exception of type 'System.ServiceModel.ProtocolException' occurred in mscorlib.dll but was not handled in user code
Additional information: The remote server returned an unexpected response: (405) Method Not Allowed.
Then I get the same message again and then it sends me to the error page.
I am an IIS newbie, but I have ensured IUSER has the correct authorization and I have checked all of the web.configs, as well as the applicationHost file.  This has to be a IIS problem is what I have come up but I would gladly be wrong if someone told me I was wrong and corrected.  Thanks for the help.
Code Example
The first call to db where the first error pops up
MYapp.GlobalDataService.GlobalDataServiceClient gdc = new Myapp.Proxy.GlobalDataService.GlobalDataServiceClient();
ReadLogosResult result = gdc.GetLogos(_customerId, region_id, branch_id);
    if (result != null)
    {
        logoContent = result.Logo;
    }

This is after clicking login
        public static int GetUserId(IIdentity contextIdentity)
        {
            FormsIdentity identity = contextIdentity as FormsIdentity;
        if (identity == null)
        {
            throw new ApplicationException("cannot cast context identity to FormsIdentity type");
        }

        return Convert.ToInt32(identity.Ticket.UserData.Split(';')[0]);
    }

Then this
            for (int i = 0; i < ContextKeys.Length; i++)
            {
                string ContextKey = ContextKeys[i];
                if (ContextKey == "appErr")
                {
                    obj = (Exception)HttpContext.Current.Application["appErr"];
                    HttpContext.Current.Application.Remove("appErr");
                }
                if (ContextKey == "userId")
                {
                    user = (int)HttpContext.Current.Application["userId"];
                    HttpContext.Current.Application.Remove("userId");
                }
            }
errors out Object reference not set to an instance of an object
then goes to our customer error page

A: I got it figured out. I needed to install HTTPActivation in WCF.


text:
Q: codeigniter login with facebook getUser() return 0 Well I'm trying to implement login with facebook using codeigniter I always have 0 when I call getUser() function , I tried all the possible solution but none of them works for me I don't know why , here is my facebook library class :
<?php

include(APPPATH.'libraries/facebook/facebook.php');

class Fbconnect extends Facebook {

    public $user = NULL;
    public $user_id = FALSE;
    public $fb = FALSE;
    public $fbSession = FALSE;
    public $appkey = 0;

    public function Fbconnect(){

        $ci =& get_instance();
        $ci->config->load('facebook', TRUE);
        $config = $ci->config->item('facebook');
        parent::__construct($config);
        parse_str( $_SERVER['QUERY_STRING'], $_REQUEST );

        $this->user_id = $this->getUser();
        $me = null;
        if($this->user_id){
            try{
                $me = $this->api('/me');
                $this->user = $me;
            } catch(FacebookApiException $e){
                error_log($e);
            }
        }

    }

}

and here my main controller :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Main extends CI_Controller {

    public function index()
    {

            $this->load->view('index');
    }

        public function fb_request()
        {
            $this->load->library('fbconnect');
            $data = array(
                'redirect_uri' => site_url('main/handle_facebook_login'),
                'scope' => array('email','user_birthday')
            );
            redirect($this->fbconnect->getLoginUrl($data));
        }

        public function handle_facebook_login()
        {
            $this->load->library('fbconnect');
            $user = $this->fbconnect->user;
            echo "
";
                print_r($user);
                echo "
";
            if($user)
            {
                echo "
";
                print_r($user);
                echo "
";
            }
            else
            {
                echo "Could not login ... ";
            }
        }

}

A: This same problem gave me serious migraine..lol but what solved the problem was to include index.php both in the fb login redirect url and also in your Facebook app site url. I was using htaccess with codeigniter so didnt use the index.php in my URLs even though its being called on every page request. Maybe you should try that.

A: Make sure you AppId and secret key are correct as per your application.some time application may take some time to get activated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: set imageBounds for country map based on png in leaflet.js I need to show an offline map of Country and show some markers. Since there is no Internet connection, I ended up using leaflet.js library and set an image as map.
Clients enter real long and lat of different places and I should show on the map.
I found below solution, but the problem is, markers are not in correct lat/long.

//var map = L.map('map').setView([51.505, -0.09], 13);
var map;
var popup;

function startMap() {
    map = L.map('map', { maxZoom: 18, minZoom: 1 }).setView([   36.844461, 50.273438], 7);
    /* Instead of a tile layer, use a bitmap image */
    var imageUrl = 'https://i.stack.imgur.com/NAbRl.jpg';
    var imageBounds = [
        [39.214320871294035, 44.02656201615383], [33.44879623488771, 60.90156137670981]];
    L.imageOverlay(imageUrl, imageBounds).addTo(map);
    L.marker([36.844461, 50.273438 ]).addTo(map)

    popup = L.popup();

    map.on('click', onMapClick);
    map.setMaxBounds(imageBounds);
}

function onMapClick(e) {
    L.marker([e.latlng.lat, e.latlng.lng]).addTo(map)

    popup
        .setLatLng(e.latlng)
        .setContent("You clicked the map at " + e.latlng.toString())
        .openOn(map);

    console.log(e);
}

startMap();

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
      <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
    integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
    crossorigin=""/>

<input type="text" id="markerText">

I am new to leaflet.js library, I just want to show markers on correct position on map.


text:
Q: Convert different string date, into one single date format In mysql I have an column create_date in my sql table, datatype is varchar(225). My problem is, in that column values are in different date formats Please check the attached Image

I want to create another column with constant_date_format using create _date column, is there way?
I have tried with mysql str_to_date function:
STR_TO_DATE(create_date, '%m/%d/%Y')

it is working if create_date column have same date format.

A: You can case when with regular expression
SELECT
 CASE WHEN create_date REGEXP [0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9] THEN STR_TO_DATE(create_date, '%m-%d-%Y')
   WHEN create_date REGEXP Format THEN STR_TO_DATE(create_date, '%m/%d/%Y')
 ELSE create_date
 END AS create_date
FROM TABLE_NAME
https://www.guru99.com/regular-expressions.html

A: If your data is like the one in the example, it's impossible to do that. Consider if you have a row in create_date with value 8.1.2017: what's constant_date_format for that? It's 1/8/2017 or 8/1/2017?
You have, at least, define a fixed day/month order in create_date. Then you can use REPLACE on create_date to make sure you always use slahses or dots, and finally STR_TO_DATE to convert to date. For example, if you decide that create_date have month before day, you can do:
STR_TO_DATE(REPLACE(create_date, '.', '/'), '%m/%d/%Y')


text:
Q: Realm Object Server (ROS) on AWS: how to make a valid Websocket request? Setup:
I am using iOS 11 and Xcode 9
Testing Realm for the first time and considering as an alternative to Firebase. Got a test server up and running in AWS EC based on the Tokyo public AMI provided. Dashboard works, adding users from Swift code works, even realms are created.
Problem:
Can not write, getting either
"Connection[1]: SSL handshake failed: Premature end of input" when I use "realms://" or "Connection[1]: Writing failed: End of input" when using "realm://" as a sync server URL. Tried googling the SSL error and did not find any matches.
From the time the tutorials on Realm website were made lots of the code has changed so I have had to improvise, perhaps there is some really clear mistake or perhaps it's my server config?
Here's my code.
var realm: Realm?
    if let serverURL = URL(string: "http://13.112.252.130:9080"){
        let usernameCredentials = SyncCredentials.usernamePassword(username: "raul", password: "abc123", register: false)
        SyncUser.logIn(with: usernameCredentials,
                       server: serverURL) { user, error in
                        if let user = user {
                            print("User \(user) is admin: \(user.isAdmin)")
                            if let syncServerURL = URL(string: "realms://13.112.252.130:9080/~/addressBook") {
                                let config = Realm.Configuration(syncConfiguration: SyncConfiguration(user: user, realmURL: syncServerURL))
                                realm = try? Realm(configuration: config)
                                print("Successfully connected to realm!")
                                let contact = Contact()
                                contact.name = "John Doe"
                                contact.phone = "123456789"
                                contact.email = "john.doe@gmail.com"
                                if let realm = realm {
                                    self.contactResults = realm.objects(Contact.self).sorted(byKeyPath: "name", ascending: true)
                                    try? realm.write {
                                    realm.add(contact)
                                    print("wrote to realm!")
                                }
                                }

                            } else if let error = error {
                                print("Error: \(error.localizedDescription)")
                            }
                        }
        }
    }

Here's the error log with "realsms://" and this goes into a infinite loop:
2017-09-02 07:37:18.223475+0700 RealmAdressbook[7253:3703339] refreshPreferences: HangTracerEnabled: 1
2017-09-02 07:37:18.223532+0700 RealmAdressbook[7253:3703339] refreshPreferences: HangTracerDuration: 500
2017-09-02 07:37:18.223551+0700 RealmAdressbook[7253:3703339] refreshPreferences: ActivationLoggingEnabled: 0 ActivationLoggingTaskedOffByDA:0
User is admin: false
Successfully connected to realm!
2017-09-02 07:37:19.319628+0700 RealmAdressbook[7253:3703453] Sync: Opening Realm file: /var/mobile/Containers/Data/Application/2A52579D-4863-4FC3-88DA-31F2EC2549E5/Documents/realm-object-server/64e042b0-d753-4ebf-b5a4-de8f8f56142f/realms%3A%2F%2F13.112.252.130%3A9080%2F%7E%2FaddressBook
2017-09-02 07:37:19.320459+0700 RealmAdressbook[7253:3703453] Sync: Connection[1]: Session[1]: Starting session for '/var/mobile/Containers/Data/Application/2A52579D-4863-4FC3-88DA-31F2EC2549E5/Documents/realm-object-server/64e042b0-d753-4ebf-b5a4-de8f8f56142f/realms%3A%2F%2F13.112.252.130%3A9080%2F%7E%2FaddressBook'
2017-09-02 07:37:19.320591+0700 RealmAdressbook[7253:3703453] Sync: Connection[1]: Resolving '13.112.252.130:9080'
2017-09-02 07:37:19.322722+0700 RealmAdressbook[7253:3703453] Sync: Connection[1]: Connecting to endpoint '13.112.252.130:9080' (1/1)
2017-09-02 07:37:19.458271+0700 RealmAdressbook[7253:3703453] Sync: Connection[1]: Connected to endpoint '13.112.252.130:9080' (from xxxxxxxxxxxxx)
2017-09-02 07:37:19.597335+0700 RealmAdressbook[7253:3703453] Sync: Connection[1]: SSL handshake failed: Premature end of input
2017-09-02 07:37:19.597609+0700 RealmAdressbook[7253:3703453] Sync: Connection[1]: Connection closed due to error

And this is the log when I use "realm://", goes into loop as well:
2017-09-02 07:41:00.362705+0700 RealmAdressbook[7263:3705293] refreshPreferences: HangTracerEnabled: 1
2017-09-02 07:41:00.362762+0700 RealmAdressbook[7263:3705293] refreshPreferences: HangTracerDuration: 500
2017-09-02 07:41:00.362782+0700 RealmAdressbook[7263:3705293] refreshPreferences: ActivationLoggingEnabled: 0 ActivationLoggingTaskedOffByDA:0
User is admin: false
Successfully connected to realm!
wrote to realm!
2017-09-02 07:41:01.524168+0700 RealmAdressbook[7263:3705496] Sync: Opening Realm file: /var/mobile/Containers/Data/Application/36B5D609-1E8B-48FD-B20A-F5DF4EB21384/Documents/realm-object-server/64e042b0-d753-4ebf-b5a4-de8f8f56142f/realm%3A%2F%2F13.112.252.130%3A9080%2F%7E%2FaddressBook
2017-09-02 07:41:01.525491+0700 RealmAdressbook[7263:3705496] Sync: Connection[1]: Session[1]: Starting session for '/var/mobile/Containers/Data/Application/36B5D609-1E8B-48FD-B20A-F5DF4EB21384/Documents/realm-object-server/64e042b0-d753-4ebf-b5a4-de8f8f56142f/realm%3A%2F%2F13.112.252.130%3A9080%2F%7E%2FaddressBook'
2017-09-02 07:41:01.526011+0700 RealmAdressbook[7263:3705496] Sync: Connection[1]: Resolving '13.112.252.130:9080'
2017-09-02 07:41:01.527816+0700 RealmAdressbook[7263:3705496] Sync: Connection[1]: Connecting to endpoint '13.112.252.130:9080' (1/1)
2017-09-02 07:41:01.663245+0700 RealmAdressbook[7263:3705496] Sync: Connection[1]: Connected to endpoint '13.112.252.130:9080' (from '192.168.1.4:59862')
2017-09-02 07:41:01.819181+0700 RealmAdressbook[7263:3705496] Sync: Connection[1]: Writing failed: End of input
2017-09-02 07:41:01.819320+0700 RealmAdressbook[7263:3705496] Sync: Connection[1]: Connection closed due to
error

Logs from the server it seems that something is wrong with my request headers, how to fix this?
proxy: [syncProxy] internal error: Error: socket hang up at createHangUpError (httpclient.js:253:15) at Socket.socketOnEnd (httpclient.js:345:23) at emitNone (events.js:91:20) at Socket.emit (events.js:185:7) at endReadableNT (streamreadable.js:974:12) at combinedTickCallback (internal/process/nexttick.js:80:11) at process.tickCallback (internal/process/nexttick.js:104:9).
1:51:33 AMinfo
sync: HTTP Connection[714]: Connection closed due to error
1:51:33 AMerror
sync: HTTP Connection[714]: Check the proxy configuration and make sure that the HTTP request is a valid Websocket request. The header values are case sensitive
1:51:33 AMerror
sync: HTTP Connection[714]: The HTTP request with the error is: GET /realm-object-server HTTP/1.1
connection: Upgrade
host: 13.112.252.130
sec-websocket-key: 7FDPgyFxq/GT1tKfIMJNcg==
sec-websocket-protocol: io.realm.sync.19
sec-websocket-version: 13
upgrade: websocket
x-realm-access-token: eyJhY2Nlc3MiOlsiZG93bmxvYWQiLCJ1cGxvYWQiLCJtYW5hZ2UiXSwiYXBwX2lkIjoiY29tLmJhbWJhbWxhYnMuUmVhbG1BZHJlc3Nib29rIiwiZXhwaXJlcyI6MTUwNDM3ODg4NiwiaWQiOiJlMjI0YTM5NmU4YTI0OWU1ODlhNWQ4OWM0ODczOTMzOCIsImlkZW50aXR5IjoiNjE1ZWUxMjU0MDA4ZDA5MWJiYTc1MjU4YTAyZWViZjYiLCJwYXRoIjoiLzYxNWVlMTI1NDAwOGQwOTFiYmE3NTI1OGEwMmVlYmY2L215UmVhbG0ifQ==:hyX8GtVHMIBho3Zw6pZfp9Gnl6O0C0Rl73V0EdX/a4ZWXMxcySFZmWbs0CxmjnpZUDNnFDK3PpXspN1YnGu2c5ByuRIpgpT7hkzwAil2EQzFeKFycYXwTbsp3a6X9npHETjxUfe9QWIIA5drz3VRPUI+0Tj+qspjbyPBcMhL6ZH3A8ubZHOIpjJpxRWGZbghdznf0g71Ta0SDyCYT4GB+fHuddzUH7RZgLkzBfoyIdJyfGccwVi1Qe/c0GTPzkH12TSyzHSwx9PnGadl1vBRuPci6fs+TE03rx6Gy7v73I37JpVVsiPm1omMG7FBdi60iQYQvItiycnle/rvb6+u3w==
x-realm-path: /615ee1254008d091bba75258a02eebf6/myRealm

1:51:33 AMerror
sync: HTTP Connection[714]: There must be a header of the form 'Sec-WebSocket-Protocol: io.realm.protocol'
1:51:33 AMinfo
sync: HTTP Connection[714]: Received: Sync HTTP request(protocol_version=-1)

A: The reason for the failure in the SSL case and in the non-SSL case are probably different.
For the SSL case, are you sure that you want to use port 9080?
Usually Realm uses 9443.
For the non-SSL case, the problem is that the headers apparently have been rewritten by an intermediate proxy. The request received by the server is different from expected. We can fix this at Realm. The only thing you can do right now is to change proxy. Thanks for reporting this.
Edited answer: For the non-SSL case, the reason that the headers are not recognized by the server is that you use an older version of the server.
It seems that you have upgraded the client without upgrading the server.
Try using the latest version of the server.


text:
Q: Custom GestureRecognizer Creation I want to create custom Gesture Recognizer.
For Example:
if user pan the screen from top to bottom some distance from there if the finger move left direction some distance, i need to invoke some method from view. same if the finger move right direction means some other function should get invoke.
For this functionality
1. can i use UIPanGestureRecognizer and detect the user interaction throw the translation position,
2.There is any way to implement my own custom GestureRecognizer
(like: UIPanLeftLGestureRecognizer for user drag the finger from top to bottom some distance and moved left from there, UIPanRightLGestureRecognizer for user drag the finger from top to bottom some distance and moved right from there.)
Which is the best way to achieve the solution for this problem. kindly guide me.
Thanks in advance.

A: I would use two UISwipeGestureRecognizers with different directions like this:
UISwipeGestureRecognizer *swipeDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipedDown:)];
swipeDown.direction = UISwipeGestureRecognizerDirectionDown;

UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipedRight:)];
    swipeRight.direction = UISwipeGestureRecognizerDirectionRight;

And don't forget to add these gesture recognizers to appropriate view


text:
Q: Disable cache control in nginx ingress controler for certain response I have this ingress configuration but all html and json reponse pages dont contain the added header:
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: {{ $app }}-ingress
  labels:
    app: {{ $app }}
    chart: chart-{{ $app }}
    app.kubernetes.io/managed-by: Helm
  annotations:
    meta.helm.sh/release-name: {{ $app }}
    meta.helm.sh/release-namespace: {{ .Release.Namespace }}
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/proxy-body-size: "{{ $proxy_body_size }}"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "{{ $proxy_read_timeout }}"
    nginx.ingress.kubernetes.io/proxy-connect-timeout: "{{ $proxy_connect_timeout }}"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "{{ $proxy_send_timeout }}"
    nginx.ingress.kubernetes.io/proxy-buffer-size: "{{ $proxy_buffer_size }}"
    nginx.ingress.kubernetes.io/rewrite-target: /$1
    nginx.ingress.kubernetes.io/configuration-snippet : |
        if ($request_uri ~* \.(html|json)) {
           add_header Cache-Control "no-cache,no-store";
        }
spec:
  tls:
    - hosts:
        - {{ $alias }}
  rules:
    - host: {{ $alias }}
      http:
        paths:
          - path: /(.*)
            backend:
              serviceName: {{ $app }}-service
              servicePort: http-back

I want to disable cache control only for html and json content response. When I remove the if ($request_uri ~* .(html|json)) condition, all responses have the added header. So this means that the condition in the configuration-snippet is not correct.
Can you help please?

A: I faced the same problem and smth like this worked for me:
      if ($request_uri ~* \.(?:html|json)$) {
        add_header Cache-Control "no-store,no-cache";
        add_header Pragma "no-cache";
      }


text:
Q: Sphinx indexer slows down the database: How to give it low priority? All my tables use InnoDB, and I have set sphinx sql_range_step to the minimum, which is 128. This improved the performance a lot, but it is still very slow if you make a request right after a new step begins.
I'm sure it would work just fine if I could reduce the range step to 10 or something, but someone found that the min value is hardcoded and there is no way to change it (other than editing the source).
So I was wondering if there was a way to deal with this directly from MySQL. When I am indexing a database, the other databases aren't affected, so it's not the whole server which has been slowed down, but only the database I am indexing.
Is there a way to give less priority to a user or query, or something?

A: Take a look at this similar post from StackOverflow. You may be able to use those strategies to give sphinx a lower priority.

A: Have a look at this
The idea is to insert some code in your query that is throttling down query execution.
For a quickest approach you can use a query like this:
select <your stuff> from <your table where <your condition> and (sleep (0.1) or 1)

That will make sphinx query to wait for 0.1 seconds before finishing.


text:
Q: ItemsControl with multiple ItemTemplateSelector I have this ScrollViewer:
<ScrollViewer x:Name="myScrollViewer">
  <ItemsControl x:Name="myItemsControl" ItemTemplateSelector="{DynamicResource myItemtemplateSelector}" ItemsPanel="{StaticResource myItemsPanel}" />
</ScrollViewer>

I fill the ItemsControl with a class that has one boolean parameter. When it's true I want to call one ItemTemplateSelector; and another one in the false case.
I'm trying something like that:
<ItemsControl x:Name="myItemsControl" ItemsPanel="{StaticResource myItemsPanel}">
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <ContentControl>
        <ContentControl.Style>
          <Style TargetType="{x:Type ContentControl}">
            <Style.Triggers>
              <DataTrigger Binding="{Binding Path=myBoolean}" Value="False">
                <Setter Property="ContentTemplate" Value="{DynamicResource SubdisciplineDataTemplateSelector}" />
              </DataTrigger>
              <DataTrigger Binding="{Binding Path=myBoolean}" Value="True">
                <Setter Property="ContentTemplate" Value="{DynamicResource SubdisciplineDataTemplateSelector2}" />
              </DataTrigger>
            </Style.Triggers>
          </Style>
        </ContentControl.Style>
      </ContentControl>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>

Is this the right way?

A: Well, no, this line is wrong:
<Setter Property="ContentTemplate" Value="{DynamicResource SubdisciplineDataTemplateSelector}" />

You're trying to assign a DataTemplateSelector to a DataTemplate property.
Now, there can be many ways to achieve what you want. I would create a third TemplateSelector, embedding the first two as private properties.
Pretend that your class is something like this:
public class MyClass { public bool MyBoolean { get; set; } }

The TemplateSelector would be like this:
public class ThirdSelector : DataTemplateSelector
{
    private DataTemplateSelector _selector1 = new SubdisciplineDataTemplateSelector();
    private DataTemplateSelector _selector2 = new SubdisciplineDataTemplateSelector2();

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        var obj = item as MyClass;

        if (obj == null)
            return null;

        if (obj.MyBoolean)
            return _selector1.SelectTemplate(item, container);
        else
            return _selector2.SelectTemplate(item, container);
    }
}

This in case you want/must preserve the first two selectors. If you can get rid of them, delete them and bring all the logic to the new one.
This is a general solution, maybe if you share more of your code and domain objects, there can be an even more suitable one for your case.


text:
Q: Multiple page plugin settings I am building a plugin and I have made a single setting page that is working without any issue. Since it is becoming very long, and that it is made of 3 distinct sections, I wanted to split it in 3 subpages.
So far I managed to have the 3 pages, and to load the fields in their right page. there are some thing that I can't fix and I can't find an answer for on the codex.
I have a main page and 3 subpages, but currently the main link has it's own empty page. I would like that the clck on the main page goes to the first of the subpages, like the default behaviour of wordpress menu.
I have made 3 different settings_fields for the 3 submenu, but now when I save one, the other two sections are wiped.
I want that each field keep his values unless is being changed.

A: WordPress always saves all options in one group at the same time. So if you have a page with only a part of the options in the group, the rest will be saved as 'unset'.
There are two possible paths to a solution. The easy one is to include all options in every page and use css to hide some of them. They will then be saved unchanged. The other one is splitting the option group into three groups.
Considering the menus: if you set the first page as both the main menu entry and the first submenu entry, you're done.


text:
Q: How to add .org files under org-directory to agenda I am facing the following problem: Org mode has the customizable variable org-agenda-files. The files listed by absolute path under this variable are used for building the org agenda window. If an element in the list is a directory, then all .org files matching the org-agenda-regex are processed to build the agenda view. On the other hand there is also another customizable variable: org-directory. Shockingly though, if org-agenda-files is undefined, the agenda view does not try to use the matching .org files under  org-directory. Also, listing the paths of the agenda files relative to org-directory in org-agenda-files is not accepted, as it complains that the files are not found.
My question is, is there an reasonably elegant way to make use of the org-directory in the lookup of agenda files, either by using it as the default to look for all .org files, or to describe the agenda files list with relative paths to org-directory?

A: Actually just managed to get it working the way I wanted. So this is how the relevant config code should look like:
(custom-set-variables
 '(org-directory "~/Documents/org")
 '(org-agenda-files (list org-directory)))

This way the agenda reads from all .org files under the org-directory, and when org-directory changes it follows it. Just what I was looking for ;)


text:
Q: Why am I getting the error "button.addEventListener is not a function" Can somebody tell me why I am receiving the above error message with the following code?
It works fine on jsfiddle, though doesn't seem to want to run in the browser.

var bladeRunnerButton = document.querySelector("ul.bladeRunner").innerHTML;
var bladeRunnerContent = document.querySelector("div.bladeRunner").innerHTML;

var detroitButton = document.querySelector("ul.detroit").innerHTML;
var detroitContent = document.querySelector("div.detroit").innerHTML;

var mammejongButton = document.querySelector("ul.mammejong").innerHTML;
var mammejongContent = document.querySelector("div.mammejong").innerHTML;

var buttonArray = [bladeRunnerButton, detroitButton, mammejongButton];
var articleArray = [bladeRunnerContent, detroitContent, mammejongContent];

function createfunc(i) {
    return function() { document.getElementById("fillPane").innerHTML = articleArray[i];};
}

for (let i=0; i < articleArray.length; i++) {
let button = buttonArray[i];
button.addEventListener("click", createfunc(i));
}
#content {
  display: none;
}

Blade Runner 2049

Detroit

Mammejong

A: You should target the Element not the innerHTML to attach the event. So remove innerHTML from the following:
var bladeRunnerButton = document.querySelector("ul.bladeRunner");
var detroitButton = document.querySelector("ul.detroit");
var mammejongButton = document.querySelector("ul.mammejong");

Working Code Example with few modifications in the code:

var bladeRunnerButton = document.querySelector("ul.bladeRunner");
var bladeRunnerContent = document.querySelector("div.bladeRunner").innerHTML;

var detroitButton = document.querySelector("ul.detroit");
var detroitContent = document.querySelector("div.detroit").innerHTML;

var mammejongButton = document.querySelector("ul.mammejong");
var mammejongContent = document.querySelector("div.mammejong").innerHTML;

var buttonArray = [bladeRunnerButton, detroitButton, mammejongButton];
var articleArray = [bladeRunnerContent, detroitContent, mammejongContent];

function createfunc(i) {
  document.getElementById("fillPane").innerHTML = articleArray[i];
}

for (let i=0; i < articleArray.length; i++) {
  let button = buttonArray[i];
  button.addEventListener("click", function(){createfunc(i)});
}
.contentPanel {
  display: none;
}

Blade Runner 2049

Detroit

Mammejong

Blade Runner

Detroit

Mammejong


text:
Q: Upper bound on the condition number of the product of a random sparse matrix and a semi-orthogonal matrix Let $G \in \mathbb{R}^{n \times m}$ (m > n, m = O(n)) whose all entries are i.i.d. distributed as $\mathcal{N}(0, 1) * \text{Ber}(p)$. Let $V \in \mathbb{R}^{m \times n}$ be a fixed semi-orthogonal matrix i.e. the columns of $V$ are orthonormal vectors. Define $A=GV$, then what is the smallest value of $p$ so that we can give a polynomial upper bound with probablity $1-o(1)$ on the condition number of $A$ i.e. $\kappa(A) \leq \text{poly}(n)$?
Interesting subcase/related problems:

*

*Let $V$ be defined as $V_{i, j} = 1$ if $i = j$ and $V_{i, j} = 0$ otherwise. Let $G = [g_1, g_2, \ldots, g_m]$, in this case $A = GV = [g_1, g_2, \ldots, g_n]$. Hence in this case $A$ has the same distribution as $G$ except $m = n$. This was studied by  Basak and Rudelson  who proved that $\kappa(A) \leq \text{poly}(n)$ for $p  = \Omega(\log n)/n$.

*For $p = 1$, $G$ is just a random Gaussian matrix and $A = GV$ can also be seen to be random gaussian matrix are gaussian vectors are isotropic. This is just a subcase of 1.

*For $m = n$, $V$ is just an orthonormal matrix hence $\kappa(V) = 1$ and from 1. we have $\kappa(G) \leq \text{poly}(n)$ if $p  = \Omega(\log n)/n$. Hence we get $\kappa(A) \leq \kappa(G)*\kappa(V) \leq \text{poly}(n)$.


text:
Q: C# creating a form for given size I want to draw a rectangle on the screen. I guess the most appropriate way is use a form without boarder.
Form frm = new Form();
frm.StartPosition = FormStartPosition.Manual;
frm.Location = new Point(GlobalPosX, GlobalPosY);
frm.Size = new Size(101, 30);
frm.BackColor = System.Drawing.Color.Yellow;
frm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
frm.Show();

The created from is not as the given size. It's size is similar to the window having boarder. The displayed window is bit larger as I given and the position is also moved little bit upper and left.
Is there another way to achieve my goal?

A: Use the ClientSize property instead of Size:
frm.ClientSize = new Size(101,30);

A: If you want to draw rectangle on the screen, you can draw it directly: http://bytes.com/topic/c-sharp/answers/263740-draw-directly-screen

A: Drawing C# graphics without using Windows Forms
That like talks about making a border-less window.  From there, just use the Graphics object to draw whatever you'd like


text:
Q: Checkbox disable when amount in textbox exceed I have this code and working properly however when i clear the text field the checkbox remain checked what should i do ?
   <form name="form1">

        <input type="checkbox" name="others" onclick="enable_text(this.checked)" class="medium" disabled='disabled'/>

    <input type="checkbox" name="others" onclick="enable_text(this.checked)" class="medium" disabled='disabled'/>

        $('input[name=other_name]').keyup(function(){
            if (this.value.length > 0) {
               $('input[name="others"]').prop('disabled', false)
            } else {
               $('input[name="others"]').prop('disabled', true)
            }
        })

http://jsfiddle.net/H8VPY/47/

A: Change your script as follows. It simply unchecks before disabling the control.
$('input[name=other_name]').keyup(function(){
    if (this.value.length > 0) {
       $('input[name="others"]').prop('disabled', false)
    } else {
       $('input[name="others"]').attr('checked', false);
       $('input[name="others"]').prop('disabled', true)
    }
})

A: Add the change event as well for mouse base edits such as right-click>cut etc.
Note:  Uncheck before disabling checkboxes.

$('input[name=other_name]').bind('keyup change', function() {
  if (this.value.length > 0) {
    $('input[name="others"]').prop('disabled', false)
  } else {
    $('input[name="others"]').attr('checked', false);
    $('input[name="others"]').prop('disabled', true)
  }
})

<form name="form1">

    <input type="checkbox" name="others" onclick="enable_text(this.checked)" class="medium" disabled='disabled' />

    Name on credit card if different from above
    <input type="text" name="other_name" class="medium" />

</form>


text:
Q: Is this a linear differential equation $\left(y^2-3x^2\right)\;dy +\left(2xy\right)\;dx=0$ I'm confused as to how I get started with this $\left(y^2-3x^2\right)\;dy +\left(2xy\right)\;dx=0$
Is it a linear differential equation?  Appreciate any hints that you can provide.

A: No it's not a Linear ODE.
Linear ODE is of the Form below:
$$\sum_{i=1}^n P_i(x)y^{(n)}(x)+P_0(x)y+q(x)=0$$
where $y^{(n)}(x)$ is the n'th derivative of y with respect to x.
But there appear the term $y^2$ which is not linear.
this equation is Homogeneous Differential Equation of the first order.
differential equation of first order of the form $M(x,y)dx+n(x,y)dy=0$ is called complete if $$\frac{\partial M}{\partial x}=\frac{\partial N}{\partial x}$$ but here it's not the case.
However we can make some equation of this form complete with a coefficient called Integral Factor.
The Mechanism is like Below:
$$\mu(x,y)M(x,y)dx+\mu(x,y)n(x,y)dy=0$$
now if we have
$$\frac{\partial (\mu M)}{\partial x}=\frac{\partial (\mu N)}{\partial x}$$
then we can solve it. now finding this so called $\mu$.
well solving it using integral factor is almost impossible because Integral Factor is'nt a function of just one of variable $x$ or $y$, thus finding it is as hard as solving the main equation. instead consider this inventive way:
$$y'=\frac{2xy}{3x^2-y^2}$$
after some easy manipulation we get above equation. now we can write:
$$y'=\frac{2\frac{y}{x}}{3-(\frac{y}{x})^2}$$
now we introduce this new variable $\frac{y}{x}=h \Rightarrow y'=h'x+h$ so now we get this:
$$h'x+h=\frac{2h}{3-h^2} \Rightarrow h'x=\frac{h(h+1)(h-1)}{3-h^2}$$
then we can solve it easily cause now the variables are separable. then with Partial Fraction Expansion and Integrating we get:
$$dh \times (\frac{-3}{h}+\frac{1}{h+1}+\frac{1}{h+1})=\frac{dx}{x}$$
$\Rightarrow $ln$(h-1)-3$ln$(h)+$ln$(h+1)=$ln$x+c \Rightarrow \frac{h^2-1}{h^3}=Cx \Rightarrow Cxh^3-h^2+1=0$
this is a cubic equation and has three solution. but unfortunately solving this equation to get solutions with Cardano's formula is quite complicated. but on bright side we still have the implicit formula for $y(x)$:
$$Cx(\frac{y}{x})^3-(\frac{y}{x})^2+1=0$$


text:
Q: Spring Boot - Why is MyFilter called many times in a single request when using Tiles+JSP? Given this filter:
public class MyFilter implements Filter{

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("FILTERING!!!!!!!!!!!!!!!!!!!"+((HttpServletRequest)request).getRequestURI());
        chain.doFilter(request, response);
    }

I've seen that is is called many times in the same request
Spring Boot App:
@SpringBootApplication(scanBasePackageClasses={MySpringBootDemoApplication .class, TilesConfiguration.class})
public class MySpringBootDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(MySpringBootDemoApplication .class, args);
    }

    @Bean
    public Filter myFilter(){
        return new MyFilter();
    }
}

TilesConfiguration:
@Configuration
public class TilesConfiguration {

     @Bean
     public TilesConfigurer tilesConfigurer() {
         final TilesConfigurer configurer = new TilesConfigurer();
         configurer.setDefinitions(new String[] { "WEB-INF/**/tiles.xml" });
         configurer.setCheckRefresh(true);
         return configurer;
     }

     @Bean
     public TilesViewResolver tilesViewResolver() {
         final TilesViewResolver resolver = new TilesViewResolver();
         resolver.setViewClass(TilesView.class);
         return resolver;
     }

}

This is what I see in the logs:
FILTERING!!!!!!!!!!!!!!!!!!!/spring-boot-demo/home
FILTERING!!!!!!!!!!!!!!!!!!!/spring-boot-demo/WEB-INF/layouts/standard.jsp
FILTERING!!!!!!!!!!!!!!!!!!!/spring-boot-demo/WEB-INF/layouts/standard.jsp
FILTERING!!!!!!!!!!!!!!!!!!!/spring-boot-demo/WEB-INF/layouts/standard.jsp

The only real request made by the browser is:
FILTERING!!!!!!!!!!!!!!!!!!!/spring-boot-demo/home

Where do the tiles related (/standard.jsp) come from? In traditional Spring MVC applications they never showed up.
I know that MyFilter could extend OncePerRequestFilter but I can't modify the real filters I have to use, they come from legacy libraries.

A: I just realized that since MyFilter is mapped against /* it'll also be called on container forwards (hence Tile's standard.jsp...). I changed the DispatcherServlet to match /action/*, and so did with the filter:
@Bean
public FilterRegistrationBean myFilter(){
    FilterRegistrationBean frb = new FilterRegistrationBean();
    frb.setFilter(new MyFilter());
    frb.setUrlPatterns(Arrays.asList(new String[]{"/action/*"}));
    return frb;

@Bean
public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
    ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet);
    registration.addUrlMappings("/action/*");
    return registration;
}


text:
Q: Firebase Auth (javascript): 'TypeError: user.delete is not a function' when linking accounts I am trying to link an anonymous firebase account with a provider account, and I'm using the following javascript code which I've copied from the documentation here: https://firebase.google.com/docs/auth/web/account-linking
This is the exact code I'm using:
function mergeAccounts(credential){

    console.log("merging guest account with provider account");

    var auth = firebase.auth();

    // Get reference to the currently signed-in user
    var prevUser = auth.currentUser;
    // Sign in user with another account
    auth.signInAndRetrieveDataWithCredential(credential).then(function(user) {
      console.log("Sign In Success", user);
      var currentUser = user;
      // Merge prevUser and currentUser data stored in Firebase.
      // Note: How you handle this is specific to your application

      // After data is migrated delete the duplicate user
      return user.delete().then(function() {
        // Link the OAuth Credential to original account
        return prevUser.linkAndRetrieveDataWithCredential(credential);
      }).then(function() {
        // Sign in with the newly linked credential
        return auth.signInAndRetrieveDataWithCredential(credential);
      });
    }).catch(function(error) {
      console.log("Sign In Error", error);
    });
}

When I am logged into firebase as an anonymous user, and then attempt to log in using my google account, the above code succeeds in logging me with google (the line console.log("Sign In Success", user); works as expected and shows me the user details in the console.  But I then get an error which says Sign In Error TypeError: user.delete is not a function at 16login.js:212which refers to the line which has return user.delete().then(function() {
The documentation and the code snippet I used seem to suggest that delete() is a function of user, so I'm a bit stumped as to why it's throwing this error.
Any help much appreciated - thanks.

A: You are using the signInAndRetrieveDataWithCredential method, not signInWithCredential, so the return value is a UserCredential object. You need to access the user through the user property of the returned property of your callback function :
    auth.signInAndRetrieveDataWithCredential(credential).then(function(userCredential) {
          const user = userCredential.user; // HERE
          console.log("Sign In Success", user);
          var currentUser = user;
          // Merge prevUser and currentUser data stored in Firebase.
          // Note: How you handle this is specific to your application

          // After data is migrated delete the duplicate user
          return user.delete().then(function() {
            // Link the OAuth Credential to original account
            return prevUser.linkAndRetrieveDataWithCredential(credential);
          }).then(function() {
            // Sign in with the newly linked credential
            return auth.signInAndRetrieveDataWithCredential(credential);
          });
        }).catch(function(error) {
          console.log("Sign In Error", error);
        });


text:
Q: How to run long running service in android in all devices greater than api level 16 not from alarm manager How to run long running service in android in all devices greater than api level 16. I have written below code for the service but somehow not working for api 17 - 19. and its working for all devices above 19 api level. Please have a look and suggest me how to do it. I am new android and writing service for the first time.
below is code
public class MyService extends Service {
    public int counter = 0;

    public ViksitService(Context applicationContext) {
        super();
        Log.i("HERE", "here I am!");
    }

    public MyService() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        startTimer();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("EXIT", "ondestroy!");
        Intent broadcastIntent = new Intent("MyService_RESTART_SERVICE");
        sendBroadcast(broadcastIntent);
        stoptimertask();
    }

    private Timer timer;
    private TimerTask timerTask;
    long oldTime = 0;

    public void startTimer() {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer, to wake up every 1 second
        timer.schedule(timerTask, 1000, 1000); //
    }

    /**
     * it sets the timer to print the counter every x seconds
     */
    public void initializeTimerTask() {
        timerTask = new TimerTask() {
            public void run() {
                Log.i("in timer", "in timer ++++  " + (counter++));
            }
        };
    }

    /**
     * not needed
     */
    public void stoptimertask() {
        //stop the timer, if it's not already null
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

below is broadcast reciever :
public class ServiceRestarterBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(ServiceRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
        context.startService(new Intent(context, MyService.class));;
    }
}

below is manifest :
<service
    android:name=".services.MyService"
    android:enabled="true"
    android:exported="true">

</service>
<receiver
    android:name=".services.ServiceRestarterBroadcastReceiver"
    android:enabled="true"
    android:exported="true">
        <intent-filter>
            <action android:name="MyService_RESTART_SERVICE"/>
        </intent-filter>
</receiver>


text:
Q: Can I use Azure Active Directory B2C to authenticate with both SQL Database user table and ADFS via SAML? The company I work for have a requirement where a client would like to login to our .Net Core 3.1 azure based web app with their on premise active directory (ADFS) via SAML. After taking a look at various options online, I found that Azure Active Directory B2C seemed to fit the bill.
However, the app also needs to authenticate against an Azure SQL Database User table. After looking through various articles and sample applications, it doesn't seem that Azure AD B2C can support authentication against a custom DB. Can anyone confirm that I am right in thinking this?
If B2C cannot support this, can anyone suggest a workaround using B2C instead? If not, would Azure AD fit the bill better, or maybe an alternative like IdentityServer? The only reason I didn't go ahead with IdentityServer initially was because we already have an Azure subscription and IdentityServer's support for version 4 ends in Novemeber 2022 when it becomes a fully commercial product - and I believe it only supports SAML with the help of a paid plugin. If this is our only option we will of course have to bite the bullet but it would be good if we could work around this issue using Azure.

A: B2C will indeed allow you to define custom authentication policies and integrate with the customers ADFS, but it will not allow you to delegate their authentication token to a SQL backend which relies on your own Azure Active Directory.
https://learn.microsoft.com/en-us/azure/active-directory-b2c/identity-provider-adfs?tabs=windows&pivots=b2c-user-flow
I appreciate your approach to implementing best practices with data access controls, but I think in this case you're going to need to implement authorisation controls in your application, rather than at the SQL level.  Your best bet is to use a service principal for the app, and grant this principal all the necessary access to the database that it would possibly need.
More on token delegation to SQL can be found in this great blog post by Tomas Restrepo:
https://winterdom.com/2017/08/31/token-delegation-azure-sql
Unless you are willing to invite the customer's users to be guests in your Azure AD (B2B), you're out of luck.

A:
it doesn't seem that Azure AD B2C can support authentication against a custom DB. Can anyone confirm that I am right in thinking this?

A while back I planned out a migration from a bespoke/back-end auth solution (where username & (hashed) password were stored in an on-prem Oracle an DB) to Azure AD B2C.
We implemented a JIT migration to B2C and orchestrated this in IEF (Identity Experience Framework), which is an XML-based DSL for B2C. We got it all working, but it was a bit of a painful experience. We needed an on-prem APIs to support the JIT migration and the team found IEF a bit tricky to work with. Unfortunately the project got squashed (for unrelated/unforeseen reasons) during delivery, but I can say that it should be possible to do what you want.


text:
Q: Search string for set of characters So for some background: I've been going through learning python the hard way and have taken a little break to try doing a few fun things, I came across on a suggestion on daniweb, to try create a program in which you enter in a list of characters and it will then print out any word that contain all those characters.
I've figured out how to do it manually, here's the below code:
string = raw_input("Please enter the scrable letters you have: ")
for line in open('/usr/share/dict/words', 'r').readlines():
    if string[0] in line and string[1] in line and string[2] in line:
        print line,

But I somehow cannot figure out how to get it to work by using loops (that way the user can enter in a list of characters of any length. I figured something like the below would work, but it doesn't appear to do so:
while i < len(string)-1:
   if string[i] in line: tally = tally + 1
   i = i + 1
if tally == len(string)-1: print line
else: i = 0

Any help in the right direction would be much appreciated, thanks.

A: I would use all with a comprehension for this ... and the comprehension is a loop
user_string = raw_input("Please enter the scrable letters you have: ")
for line in open('/usr/share/dict/words', 'r').readlines():
    if all(c in line for c in user_string):
        print line,

A: Set operations can come in handy here:
inp = set(raw_input("Please enter the scrable letters you have: "))
with open('/usr/share/dict/words', 'r') as words:
    for word in words:
        if inp <= set(word):
            print word,


text:
Q: Should I use uniform variable to reduce the amount of matrix multiplication? I just wrote a program to rotate an object. it just updates a variable theta using the idle function. That variable is used to create a rotation matrix ..then I do this..
gl_Position = rx * ry * rz * vPosition;

rx, ry and rz (matrices) are same for every point during the same frame....but it is being multiplied for every single point in the object....should I just use a uniform variable mat4 which stores the multiplied value of rx* ry * rz and pass it to the shader?...or let the shader handle the multiplication for every single point?.....which is faster?....

A: While profiling is essential to measure how your application responds to optimizations, in general, passing a concatenated matrix to the vertex shader is desirable. This is for two reasons:

*

*The amount of data passed from CPU to GPU is reduced. If rx, ry and rz are all 4x4 matrices, and the product of them (say rx_ry_rz = rx * ry * rz), is also a 4x4 matrix, then you will be transferring 2 less 4x4 matrices (128 bytes) as uniforms each update. If you use this shader to render 1000 objects per frame at 60hz, and the uniform updates with each object, that's 7MB+ per second of saved bandwidth. Maybe not extremely significant, but every bit helps, especially if bandwidth is your bottleneck.

*The amount of work the vertex stage must do is reduced (assuming a non-trivial number of vertices). Generally the vertex stage is not a bottleneck, however, many drivers implement load balancing in their shader core allocation between stages, so reducing work in the vertex stage could give benefits in the pixel stage (for example). Again, profiling will give you a better idea of if/how this benefits performance.
The drawback is added CPU time taken to multiply the matrices. If your application's bottleneck is CPU execution, doing this could potentially slow down your application, as it will require the CPU to do more work than it did before.

A: I wouldn't count on this repeated multiplication being optimized out, unless you convinced yourself that it is indeed happening on all platforms you care about. To do that:

*

*One option is benchmarking, but it will probably be difficult to isolate this operation well enough to measure a possible difference reliably.

*I believe some vendors provide development tools that let you see assembly code for the compiled shader. I think that's the only reliable way for you to see what exactly happens with your GLSL code in this case.

This is a very typical example for a much larger theme. At least in my personal opinion, what you have is an example of code that uses OpenGL inefficiently. Making calculations that are the same for each vertex in the vertex shader, which at least conceptually is executed for each vertex, is not something you should do.
In reality, driver optimizations to work around inefficient use of the API are done based on the benefit they offer. If a high profile app/game uses certain bad patterns (and many of them do!), and they are identified as having a negative effect on performance, drivers are optimized to work around them, and still provide the best possible performance. This is particularly true if the app/game is commonly used for benchmarks. Ironically, those optimizations may hurt the performance of well written software that is considered less important.
So if there ever was an important app/game that did the same thing you're doing, which seems quite likely in this case, chances are that many drivers will contain optimizations to deal with it efficiently.
Still, I wouldn't rely on it. The reasons are philosophical as well as practical:

*

*If I work on an app, I feel that it's my job to write efficient code. I don't want to write poor code, and hope that somebody else happened to optimize their code to compensate for it.

*You can't count on all of the platforms the app will ever run on to contain these types of optimizations. Particularly since app code can have a long lifetime, and those platforms might not even exist yet.

*Even if the optimizations are in place, they will most likely not be free. You might trigger driver code that ends up consuming more resources than it would take for your code to provide the combined matrix yourself.


text:
Q: Rotate a page with pdf-lib and javascript I am making a website that can modify pdf files , and I was trying to be able to rotate a page or multiple pages but couldn't find how to do that in their docs .

 const pdfDoc = await loadSingleFile(inputFiles[0]) // An input pdf file

 const rotatedPdf = await PDFDocument.create();  // Intitialize the rotated pdf file

 const pageToRotate = pdfDoc.getPages()[pageIndex]

  // Not sure what to write here

 const pdfDataString = await rotatedPdf.saveAsBase64({ dataUri: true }); // here generate string for further use


text:
Q: check for uniqueness of employee id number Cant seem to figure out how to check for a unique Employee id Number. I know the validation has to go in the form load, just not sure how to go about it.
Public Class Form1
  Dim filename As String
  Dim dataFile As System.IO.File
  Dim dataWrite As System.IO.StreamWriter

  ''LOADING AND WRITE TO TEXT DOCUMENT
  Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    'asks user for file name
    filename = InputBox("Enter output file name")
    If IO.File.Exists(filename) Then
      dataWrite = IO.File.AppendText(filename)
    Else
      MessageBox.Show("filename does not exist")
      filename = InputBox("Enter output file name")
      dataWrite = IO.File.CreateText(filename)
    End If
    cboDepart.Items.Add("Accounting")
    cboDepart.Items.Add("Administration")
    cboDepart.Items.Add("Marketing")
    cboDepart.Items.Add("MIS")
    cboDepart.Items.Add("Sales")
  End Sub
  '------

  Public EMPLOYEEIDS As String
  Dim employeeID1 As ServerData()
  Dim employeeID2 As ServerData()
  Dim reader As String = My.Computer.FileSystem.ReadAllText("servers.lst")
  Dim s() As String
  Dim Totalemployeeids As String = CStr(reader.Length)
  Dim x As Integer = 0
  Dim myArray As String() = reader.Split("|"c)
  For x = 1 To Totalemployeeids
    employeeID1(x).ServerName = myArray(0)
    employeeID2(x).IDname = myarray(0)

    Form1_load.ListBox1.Items.Add(Servers(x).ServerName)
    x += 1
  Next

  Structure ServerData
  End Structure
End Class

A: You usually do not insert a unique ID from the client side. Instead, it is inserted automatically by the database server. There is a way to retrieve an inserted ID back, if you need it for display (can also act as a confirmation that a record was successfully inserted):
SELECT SCOPE_IDENTITY()

An example is shown in this answer:

*

*How to get last inserted id? (C#)
On the client side, you need to implement insertion of everything but the ID, in this case you don't need to check for uniqueness. There may be other validation issues upon commit though (unique key violation, data type mismatch) - make sure you catch exceptions and display them to the user as appropriate.


text:
Q: Implementing AWS(Amazon Web Services) in Android Application I have a task to implement in my Android Application. I have a .xls sheet which I have to access in my Android Application using AWS. I am totally new to AWS.
Can any body tell me from where I can start. Where I have to store this .xls file. Definitely I can't store in local Memory. I have to store it on cloud.
But I am not getting the idea for achieving my requirement. Is there anyone who implemented it before who can give me a direction.
Waiting for responses.
Thanks in Advance.

A: Look into using the Java AWS SDK
http://aws.amazon.com/sdk-for-java/
For simple storage you probably what to check out the S3 file system
http://aws.amazon.com/s3/

A: There is also an Android AWS SDK if you do not want to implement a server.  http://aws.amazon.com/mobile/sdk/ .  I'd suggest looking into using the TransferManager (available for both Java and Android depending on what you end up going with).  For Android there is a specific guide on uploading files to S3 http://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/s3transfermanager.html


text:
Q: Import error in android studio design and v7 - Android Studio - I am new to java and Android studio, but I tried to create an app
Here is the code -
MainActivity.java

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

In this code, the design word shows - cannot resolve symbol 'design'
and, the v7 word shows - cannot resolve symbol 'v7'
build.gradle(Module:app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.example.pop"
        minSdkVersion 15
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'

}

If, I ran this program which shows compiler error
error: package android.support.design.widget does not exist
error: package android.support.design.widget does not exist
error: package android.support.v7.widget does not exist

How to resolve this error, thanks

A: If you are using androidx implementations, you should use
import androidx.appcompat.widget.Toolbar;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

But if you want to run with your imports,
compile this dependencies in your build.gradle:
dependencies {
   ...
   implementation 'com.android.support:design:25.3.1'
}

A: The reason is rather simple. You are using different import libraries than the one you currently have in you project dependencies.
In your case you are importing android.support Support Library but your gradle dependencies shows you have included the following libraries instead

*

*androidx ( AndroidX )

*com.google.android.material ( Material Components for Android )

AndroidX is the newer, better and preferred version of the previous support library since the release of Android Pie (API 28). Material Components for Android are google's official implementation of there material design widgets including FloatingActionButton , BottomAppBar etc.
Since you are new I'm assuming it doesn't matter whether you use androidx or android.support. For now just use AndroidX. So just import the correct libraries as follows
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.widget.Toolbar

A: It seems like you have migrated to AndroidX. Remove those three imports
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;

and add this
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.widget.Toolbar;

A: You use androidx which is part of android jetpack So that it's not support support design import You can solve this problem simply just change the import to
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.appcompat.widget.Toolbar;

Hope it's work nicely.
Also you can learn about jetpack androidx from here

A: This will cause for you have use androidx For development so design library is deprecated use..

implementation 'com.google.android.material:material:1.2.0-alpha04'

this material library created by google for all View and widgets..
hope it will help you..


text:
Q: GAE error (: SystemId Failed Any idea why I will receive this error from GAE?  And how to fix it?
: SystemId Unknown; Line #57; Column #31; Failed calling setMethod method

A: Problem cause by reflection call by Xalan.
Fix:
http://code.google.com/p/googleappengine/issues/detail?id=1367
https://github.com/www-eee/xalan-j/commits/xalan-gae-2_7_1-1


text:
Q: Why iterators are incompatible? I have following class:
class Manifest {
public:
    Manifest(void);
    ~Manifest(void);

    std::vector<ManifestDirectory> get_directories() const { return directories_; }
    void set_directories(std::vector<ManifestDirectory> dirs) { directories_ = dirs; }
    int ReadManifest(Manifest &manifest);

private:
    std::vector<ManifestDirectory> directories_;
};

and following simplified usage:
Manifest manifest;
manifest.ReadManifest(manifest);

for (std::vector<ManifestDirectory>::iterator it = manifest.get_directories().begin(); it != manifest.get_directories().end(); ++it) {
    // Do something
}

how to modify get_directories(), so it will not copy entire directories_ and it in for loop will point the same directories_.begin()?
Right now iterator is incompatible is being thrown.

A: If you don't want the directories modified outside of get_directories(), return a const ref:
const std::vector<ManifestDirectory>& get_directories() const { return directories_; }

But make sure you create const iterators.


text:
Q: StackLayout not obeying VerticalOptions property in Xamarin.Forms I am trying to create a simple stacklayout UI.
Here is the XAML.
    <ContentView>
        <StackLayout
            BackgroundColor="Green"
            HeightRequest="500"
            VerticalOptions="End">
            <StackLayout
                BackgroundColor="LightSkyBlue"
                HeightRequest="100"
                VerticalOptions="End">
                <!--  // ADD CONTROLS HERE[!  -->
            </StackLayout>
        </StackLayout>
    </ContentView>

Ideally it is expected that the 'blue' stacklayout should align itself at the bottom on the green one But, it just doesn't moves and stays on the top.
What am i doing wrong?
Please point me in the right direction
Attaching the image for better clarity.

A: You just need to replace your code by below code:
<StackLayout
        BackgroundColor="Green"
        HeightRequest="500"
        VerticalOptions="End">
        <StackLayout
            BackgroundColor="LightSkyBlue"
            HeightRequest="100"
            VerticalOptions="EndAndExpand">
            <!--  // ADD CONTROLS HERE[!  -->
        </StackLayout>
    </StackLayout>

Hope it will help you
Thank you

A: In my experience, a StackLayout will never obey Vertical or Horizontal options. It will only use as much space as it needs. You can place a transparent BoxView in the StackLayout and set its VerticalOptions to FillAndExpand. That will force the StackLayout to use all the space.
I normally use a Grid instead and use <RowDefinition Height="*"/> to force it to use all the space.

A: You need to set blue Stack Layout's Vertical Option to EndAndExpand. Because stack layout children doesn't fill automatically. You need to force it if you want. You can look at this answer here for detailed explanation.


text:
Q: division-by-zero error? I've tried running this code:
int x = 0;
double y = 1/2;
if (y <= x || y/x < 1)
y++;
printf("%.2f", y);

The output is 1.00, which is kinda surprising to me. I thought the first expression (y <= x) is false and since this is the || operator, C also have to evaluate the second expression (y/x < 1), which involves a division by zero. But why doesn't any error show up?

A: y is actually 0:
double y = 1/2;

The above does integer division, so the result is 0. What you want is:
double y = 1.0/2.0;

A: The assignment double y = 1/2; yields 0 for y. So the || is shortcut (that means the second part of the or is not evaluated).
If you intend y to be 0.5, then write:
double y = 1/2.0;

A: First, as everyone else pointed out, you assign zero to y because 1/2 is a division by 2 integers.
In your - wrong - example where 1 and 2 are integers and y gets assigned 0 your assumption "the first expression (y <= x) is false" is obviously incorrect as y and x are both zero and hence equal. The expression is short circuited and the second part is never evaluated (no division by zero).
Even if you divide by zero it's not guaranteed that you'll get an error. IEEE 754 for example states that a divison by zero yields infinty.

A: Firstly Thank u. That the Question is Very Essential but i have not Face Yet.
Firstly, the line "y=1/2" yields "y=0",  Secondly, the line in "if Condition y/x" is mean 0/0 "Result is Undefined". But in "||" if the Left side Argument is True, than it don't need to test the rest Argument(condition). So it jumps to "y++" & as a result We see the Result is 1.00.
But if we Write
if(y/x<1 || y<=x)
than it give "Abnormal Program Termination"


text:
Q: Is WP Query skipping to check next post when an argument is not met? If a post fails to meet the first argument (publish), does wp query still do the meta comparison or is it skipping to check the next post immediately?
The question is NOT about the output, but rather how wp query works before the output. For an example if you have a database with thousands of posts and only five is published. My concern is the query is getting slow if it does the meta comparison on all posts.
Example code:
$args = array(
    'post_status'  => 'publish',
    'meta_key'     => 'expiredate',
    'meta_value'   => date( 'Ymd' ),
    'meta_compare' => '<'
);
$my_query = new WP_Query($args);

A:
does wp query still do the meta comparison

WP Query doesn't do comparisons, it asks the database to do them in an SQL query. MySQL/MariaDB does the comparison.
You would need to test this yourself by running the raw SQL through an EXPLAIN query to see how your specific database install plans the query. Different database versions and configurations may behave differently.

If your suspicion is correct, there will be very little that can be done about it from the WordPress side. But this is a red herring, a wild goose chase. This is not a problem you can fix and everything will be super fast, because this query will always be fundamentally slow.
Keep in mind that because it's the post meta table, and that table isn't designed for these kinds of queries to be performant, the number of posts requested per page is 10 by default, and it needs to figure out the number of pages, so a full table scan is unavoidable with the code in your question. Otherwise how would it know there are only 5?
This query will be slow but it'll be slow because you asked it to filter post IDs by their meta values, and that table is not designed for those kinds of queries, this is why dedicate tables were created for categories and tags instead of just storing them in post meta. meta_query and the associated meta_value parameters do not scale as it involves a full table scan. As your site grows in scale, the query will get progressively slower and more expensive. Having a numeric value for your post meta will help mitigate this, and there are far worse post meta queries you could have asked WP_Query to create.
Your ideal situation is likely one where posts have an expired tag of some kind that gets automatically added via a regular cron job, but that's another topic that requires another question.


text:
Q: What is the best CSS Framework and why?
Possible Duplicate:
What is the best CSS Framework and are they worth the effort?

What is the best CSS Framework and why ?
How can i get started with css frameworks ? Are there any good tutorials ?

A: using html5 I would say the css section of html5 boilerplate even if it's not a framework, but a reset stylesheet

A: I like to start with a reset.css file to knock all browsers down to a blank slate, then I start writing my own CSS from there.
No more margin:0;padding:0; on every class you make.

A: in my opinion there is no best (suited) CSS framework in my work.
use CSS framework just load unnecessary script...
i suggest you only use reset CSS, to make you easly develop website look same in every browser. you can search it in google.


text:
Q: Payment request button via Stripe does not work when add shipping address I am using stripe to add the Payment request button(Apple, Google, Pay Now) by following the documentation https://stripe.com/docs/stripe-js/elements/payment-request-button
which is working fine but I need to add the shipping address and when I add

requestShipping: true,

It shows up the shipping address dialogue but keeps processing...
and never complete the payment but if I remove

requestShipping: true,

Then works fine

Here is my full source code

JS Code

<script src="https://js.stripe.com/v3/"></script>
{{-- //stripe pay button --}}
<script type="text/javascript">

    var clientSecret = "{{ $payment_intent_client_secret }}";
    var total_amount = parseFloat({
    {
        $total
    }
});

var stripe = Stripe("{{ env('STRIPE_KEY') }}", {
    apiVersion: "2020-08-27",
});

var paymentRequest = stripe.paymentRequest({
    country: 'US',
    currency: 'usd',
    total: {
        label: 'Total',
        amount: total_amount,
    },
    requestPayerName: true,
    requestPayerEmail: true,
    requestShipping: true,
});

var elements = stripe.elements();
var prButton = elements.create('paymentRequestButton', {
    paymentRequest: paymentRequest,
});

// Check the availability of the Payment Request API first.
paymentRequest.canMakePayment().then(function(result) {
    if (result) {
        prButton.mount('#payment-request-button');
    } else {
        // document.getElementById('payment-request-button').style.display = 'none';
    }
});

paymentRequest.on('paymentmethod', function(ev) {
    // Confirm the PaymentIntent without handling potential next actions (yet).
    stripe.confirmCardPayment(
        clientSecret, {
            payment_method: ev.paymentMethod.id
        }, {
            handleActions: false
        }
    ).then(function(confirmResult) {

        if (confirmResult.error) {
            ev.complete('fail');
        } else {

            // Report to the browser that the confirmation was successful
            ev.complete('success');

            if (confirmResult.paymentIntent.status === "requires_action") {

                stripe.confirmCardPayment(clientSecret).then(function(result) {

                    if (result.error) {
                        alert('payment failed, try again');

                    } else {
                        // The payment has succeeded.
                        window.location.href = "{{ route('checkout.thankyou') }}";
                    }
                });
            } else {
                // The payment has succeeded.
                window.location.href = "{{ route('checkout.thankyou') }}";
            }
        }
    });

});

//shippingaddresschange event
paymentRequest.on('shippingaddresschange', function(ev) {
  if (ev.shippingAddress.country !== 'US') {
    ev.updateWith({status: 'invalid_shipping_address'});
  } else {
    // Perform server-side request to fetch shipping options
    fetch('/calculateShipping', {
      data: JSON.stringify({
        shippingAddress: ev.shippingAddress
      })
    }).then(function(response) {
      return response.json();
    }).then(function(result) {
      ev.updateWith({
        status: 'success',
        shippingOptions: result.supportedShippingOptions,
      });
    });
  }
});

</script>

PHP Code which Return clientSecret

\Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
$payment_intent = \Stripe\PaymentIntent::create([
  'amount' => 1 * 100,
  'currency' => 'usd'
]);
$payment_intent_client_secret=$payment_intent->client_secret;

shipping address code

 //shipping address sample
 $data=['shippingAddress'=>'shipping address here'];
 return json_encode($data);

Thanks for helping.

A: You are fetching calculateShipping from your backend and expecting supportedShippingOptions in its response. However you only return a simple hashmap: ['shippingAddress'=>'shipping address here'].
    fetch('/calculateShipping', {
      data: JSON.stringify({
        shippingAddress: ev.shippingAddress
      })
    }).then(function(response) {
      return response.json();
    }).then(function(result) {
      ev.updateWith({
        status: 'success',
        shippingOptions: result.supportedShippingOptions,
      })

    //shipping address sample
    $data=['shippingAddress'=>'shipping address here'];
    return json_encode($data);

It's most likely your js is errored processing this response. But the best way to diagnose is confirm on browser console.


text:
Q: Changing culture on Telerik datepicker for asp.net MVC Right now i have this datepicker in a asp.net mvc project

Start date:

        <input id="start" style="width: 100%;" value="10/10/2015" data-role="datepicker" type="text" class="k-input" role="combobox" aria-expanded="false" aria-owns="start_dateview" aria-disabled="false" aria-readonly="false">select

End date:

        <input id="end" style="width: 100%;" value="10/10/2015" data-role="datepicker" type="text" class="k-input" role="combobox" aria-expanded="false" aria-owns="end_dateview" aria-disabled="false" aria-readonly="false">select

    @*
Maximum duration from start to end date is 5 days
*@

it works ok , but the problem is that the date format is in american (Month/Day/Year)
and i want to change it to (Day/Month/Year)
is there any option to change that ? haven't found it on api documentation.

A: Add to your kendoDatePicker method a culture and format, like:
.kendoDatePicker({
        change: startChange,
        culture:"nl-NL",
        format:"d-M-yyyy",
});


text:
Q: Read data from CSV into a single array or a single json I am using jQuery autocomplete function. For it to work I need the json in this format ["Alaska","Alabama","Arkansas"] . Currently I am reading the data from a CSV file. This is my code.
$f = fopen($filename, "r");
    while ($row = fgetcsv($f)) {
            $out = $row[2];
            print_r (explode(" , ",$out));
        }

Now I get the output as
Array
(
    [0] => Alaska
)
Array
(
    [0] => Alabama
)
Array
(
    [0] => Arkansas
)

And my Json as
["Alaska"]["Romeo"]["Arkansas"]

How do I convert the array into a simple array like
Array
(
    [0] => Alaska
    [1] => Alabama
    [2] => Arkansas
)

If not into a json like this
["Alaska","Alabama","Arkansas"]

A: You build an array of values and then put them in json_encode() function.
$data = [];
$f = fopen($filename, "r");
    while ($row = fgetcsv($f)) {
            $out = $row[2];
            $data = array_merge($data, explode(" , ",$out)));
        }

echo json_encode($data);

A: Might be easier to read the file into an arary, map to a function that explodes, then encode and display:
echo json_encode(
    array_map(function($v) { return explode(" , ", $v)[2]; }, file($filename))
);


text:
Q: wp_mail() headers multipart/alternative I am trying to send email via wp_mail() containing both plain text, as well as HTML body.
When I am setting up headers like this:
  $headers = "MIME-Version: 1.0 \r\n";
  //$headers .= "From: Dawid Adach\r\n";
  $headers .= "Reply-To: d.adach@mdbootstrap.com \r\n";
  $headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";

  //$headers .= "To: ".$email."\r\n";
  $headers .= "Content-Type: multipart/alternative;boundary=" . $boundary . "\r\n";

and later on content:
  //Plain text body
  $message .= "Hello,\nThis is a text email, the text/plain version.
  \n\nRegards,\nYour Name";
  $message .= "\r\n\r\n--" . $boundary . "\r\n";
  $message .= "Content-type: text/html;charset=utf-8\r\n\r\n";

  //Html body
  $message .= '
<!--my html comes here -->
    </div>
    ';
  $message .= "\r\n\r\n--" . $boundary . "--";

It doesn't work.
The entire body is treated like a plain HTML. When I check an original message I can see that new line chars aren't interpreted correctly.
Reply-To: d.adach@mdbootstrap.com X-Mailer:PHP/7.0.8Content-Type:
 multipart/alternative@720plan.ovh.net; ,
 boundary=np57c40a2fee02f@720plan.ovh.net

Second thing is that when I try to set header "From: " wp_mail returns 0 and doesn't send anything.
I was going trough Sending multipart (text/html) emails via wp_mail() will likely get your domain banned , however I cannot overwrite wp_mail function so I have to use original one.


text:
Q: how to use train_image_classifier.py train both gender and age Recently I was working on a face recognition project,I use train_image_classifier.py to classify age and gender,but this py is only train for one feature,how to train for much features

A: You should know that this is a multitask classification problem, the features are the images of faces (since this is a face recognition project) and the scopes will be the age and the gender.
For multitask classification, there will be 2 trainings running in parallel for each task (gender classification and age classification).
Basically you have to define 2 classifiers at the output of your CNN feature extractor.
I suggest you to read this article. This is what you are looking for.
Hope it helps!


text:
Q: Constructing idempotent matrices Is there a general method for constructing an idempotent matrix if we are given the values of the diagonal entries?

A: The following should work "generically" (given a list of diagonal elements $d_i, i=1\ldots n$ where $\sum_{i=1}^n d_i = r$ is an integer, $1 \le r \le n-1$).  Start with a diagonal matrix with $r$ $1$'s and $n-r$ $0$'s on the diagonal.  First conjugate with a random matrix.
Then for $k$ from 1 to $n-1$, conjugate with a matrix that differs from the identity only in position $(k,k+1)$, chosen to make the $(k,k)$ element $d_k$.
For example, suppose we want a $3 \times 3$ idempotent matrix with diagonal elements $2,1,-1$.  Start with $\left(\matrix{1 & 0 & 0\cr 0 & 1 & 0\cr 0 & 0 & 0\cr}\right)$ and conjugate with $\left(\matrix{12 & -2 & 6\cr 15 & -7 & 3\cr 3 & 1 & -3\cr}\right)$ to get $M_0 = \left(\matrix {2/3 & -1/9 & 1/3\cr -1/2 & 5/6 & 1/2\cr 1/2 & 1/6 & 1/2\cr}\right)$.  The conjugate of $M_0$ by $\left(\matrix{1 & b & 0\cr 0 & 1 & 0\cr 0 & 0 & 1\cr}\right)$ has $(1,1)$ element $2/3 + b/2$, which is $2$ for $b = 8/3$.  Using this, we get $M_1 = \left(\matrix{2 & 3 & -1\cr
-1/2 & -1/2 & 1/2 \cr 1/2 & 3/2 & 1/2\cr}\right)$.  The conjugate of $M_1$ by $\left(\matrix{1 & 0 & 0\cr 0 & 1 & b\cr 0 & 0 & 1\cr}\right)$ has $(2,2)$ element $-1/2 - 3b/2$, which is $1$ for $b = -1$.  Using this, we obtain
$M_2 = \left( \matrix{2 & 3 & -4\cr 0 & 1 & 0\cr 1/2 & 3/2 & -1\cr} \right)$, which satisfies the requirements.

A: If $X$ is idempotent, $X^2=X$, and so by the Cayley-Hamilton theorem, the only eigenvalues are $0$ and $1$.   Therefore, if you are looking at diagonal or upper triangular matrices, there are severe restrictions on what is possible.
Furthermore, if one puts an idempotent matrix in Jordan normal form, the Jordan blocks must all be of size $1$, and so $X$ must be diagonalizable.  This allows a classification of idempotent matrices up to conjugation.  You can thus generate idempotents by starting from a diagonal matrix with $0$'s and $1$'s and conjugating.
I am unaware of any good way to build a matrix with specified diagonal entries and eigenvalues if it is not either upper or lower triangular.  However, there are definitely restrictions that can be placed on the diagonal entries.  For example, because trace is conjugation invariant, we must have that if $X$ is an $n\times n$ matrix, then $0\leq \operatorname{tr} X\leq n$, and $\operatorname{tr} X \in \mathbb{N}$.  The trace must also be equal to the rank of $X$.
For an invertible matrix to be idempotent, it must be conjugate to the identity matrix, and thus itself must be the identity matrix.  In the $2\times 2$ case, if $X$ is idempotent but not the identity matrix or the zero matrix, then it has eigenvalues $0$ and $1$, each with multiplicity $1$.  However, this condition alone ensures that the matrix can be diagonalized, and hence is idempotent.  Therefore, the matrix must be of the form
$$\pmatrix{a & b \\ \frac{a(1-a)}{b} & 1-a}$$.
Unfortunately, in more than $2$ dimensions, at least one of the eigenvalue multiplicities will be greater than $1$, and so the idempotentness cannot be checked by the characteristic equation alone, although it will follow from the spectral theorem if the matrix is real and symmetric.

A: For $n \times n$ matrices where $n$ is small (probably not much bigger than $4$), given diagonal elements whose sum is an integer from $1$ to $n-1$, I would try solving the system of equations for the matrix elements of $M^2 - M$ using Groebner basis techniques.


text:
Q: What's the difference between visibility: hidden and visibility: collapse in flexbox? In the CSS flexible box layout module, it says:

the collapsed flex item is removed from rendering entirely, but leaves behind a "strut"

Does that behave just like visibility: hidden? If the answer is yes, then why was visibility: collapse introduced?

A: Note on browser support: As of July 2017, Chrome (59) does not support visibility: collapse. The code samples below with collapse work in Firefox and Edge, but fail in Chrome (they behave just like hidden). UPDATE: As of July 2020, this is note is still valid. Chrome and Safari treat visibility: collapse like hidden. caniuse.com

Flex items are laid out in a row or column, depending on flex-direction.
Each row / column is considered a flex line.
In the examples below, a flex container has four flex items in row-direction. The fourth item wraps, creating a second flex line:

.container {
  display: flex;
  flex-wrap: wrap;
  width: 200px;
  border: 1px dashed black;
}
.box {
  height: 50px;
  flex: 0 0 50px;
  margin: 5px;
  background-color: lightgreen;
  display: flex;
  justify-content: center;
  align-items: center;
}

1

2

3

4

display: none
With display: none, a flex item isn't rendered by the browser.
If all items on the flex line have display: none, the line also collapses, which affects the rest of the layout. Surrounding elements may shift when a flex line collapses.
With display: none applied to the third item, the fourth item takes its place on the upper line, and the lower line collapses:

.container {
  display: flex;
  flex-wrap: wrap;
  width: 200px;
  border: 1px dashed black;
}
.box {
  height: 50px;
  flex: 0 0 50px;
  margin: 5px;
  background-color: lightgreen;
  display: flex;
  justify-content: center;
  align-items: center;
}
.box3 { display: none; }
display: none

1

2

3

4

visibility: hidden
With visibility: hidden, a flex item is rendered by the browser but is fully transparent. It's hidden from view but takes up the space it would normally use in the layout. Hence, surrounding elements see this item as fully intact.
In this example, when the last two boxes have visibility: hidden, the rest of the layout (including the second flex line) remains unchanged.

.container {
  display: flex;
  flex-wrap: wrap;
  width: 200px;
  border: 1px dashed black;
}
.box {
  height: 50px;
  flex: 0 0 50px;
  margin: 5px;
  background-color: lightgreen;
  display: flex;
  justify-content: center;
  align-items: center;
}
.box3 { visibility: hidden; }
.box4 { visibility: hidden; }
visibility: hidden

1

2

3

4

visibility: collapse
With visibility: collapse,  a flex item is not rendered (same as display: none), but the flex algorithm checks the cross size of the item and then uses that data to keep the flex line stable (i.e., what the cross size of the line would be if the flex item was visible).
The difference with display: none is that collapse allows one piece of the item – its cross size – to be preserved. This is referred to in the spec as the strut.
So if all flex items on the line have visibility: collapse, the cross size of the line (whether it be the width or height) does not collapse, and the rest of the layout isn't affected.
Note that although collapse guarantees the stability of the line's cross size, it provides no such assurance for the line's main size. This is a key difference between collapse and hidden.
Below are some examples. (As mentioned above, these won't work in Chrome. Test in FF or Edge.)
In this example, the first two items have visibility: collapse.

.container {
  display: flex;
  flex-wrap: wrap;
  width: 200px;
  border: 1px dashed black;
}
.box {
  height: 50px;
  flex: 0 0 50px;
  margin: 5px;
  background-color: lightgreen;
  display: flex;
  justify-content: center;
  align-items: center;
}
.box1, .box2 {
  visibility: collapse;
}
visibility: collapse

1

2

3

4

The layout renders like display: none. The second line collapses because the main size of the items is gone, allowing the last item to move up naturally.
In the following example, all items get visibility: collapse. Hence, the second line collapses because the items' main size is gone, but the cross size of the first line remains.

.container {
  display: flex;
  flex-wrap: wrap;
  width: 200px;
  border: 1px dashed black;
}
.box {
  height: 50px;
  flex: 0 0 50px;
  margin: 5px;
  background-color: lightgreen;
  display: flex;
  justify-content: center;
  align-items: center;
}
.box {
  visibility: collapse;
}
visibility: collapse

1

2

3

4

jsFiddle

A: It actually depends on the element. If used on a table sub-element, collapse will hide the element as well as the space it occupied.
collapse will behave like hidden if used on any element that is not a table sub-element


text:
Q: Check if route exists when Route::fallback present I am attempting to determine if a given route exists while inside of Laravel's Route::fallback. The following snippet should throw a NotFoundHttpException exception, however I suspect that it is not due to the presence of the fallback (ie, the route does exist as a fallback).
Route::fallback(function () use ($routes) {
    try {
        $next = Request::create('does-not-exist');
        Route::getRoutes()->match($next);
    } catch (NotFoundHttpException) {
        // Should end up here
    }
});

For some context: I'd like to be able to hit a route that does exist and then display the contents of another route. This second route may end up not actually existing and I'd like to be able to catch that.
TIA

A: The result of Route::getRoutes()->match($next); will be an Illuminate\Routing\Route object. You can check this object for the value of the isFallback property.
Route::fallback(function () use ($routes) {
    $next = Request::create('does-not-exist');
    $route = Route::getRoutes()->match($next);
    if ($route->isFallback) {
        // do your thing
    }
});


text:
Q: PHP Associative Arrays - Return all key value pairs where key is present in a validation list? For example:
$searchParameters = array(
    'parameter1' => 'value1',
    'parameter2' => 'value2',
    'parameter3' => 'value3',
);

$allowedParamters = array('parameter1','parameter2');

What's the best way to get $searchParameters containing only the allowed pairs?

A: foreach($searchParameters as $key => $value) {
    if(!array_key_exists($key, $allowedParamters)) {
        unset($searchParameters[$key];
    }
}

This will delete the not-allowed keys and their value.

A: Use array_intersect_key() :
$searchParameters = array(
    'parameter1' => 'value1',
    'parameter2' => 'value2',
    'parameter3' => 'value3',
);
$allowedParamters = array('parameter1','parameter2');

$result = array_intersect_key($searchParameters, array_flip($allowedParamters));

A: foreach($searchParameters as $key=>$value){
    if(in_array($key,$allowedParamters)){
        $trueResult[$key] = $value;
    }
}
print_r($trueResult);


text:
Q: JQuery: get object inside span I am very new to jQuery. Below is part of my code

    <input type='button' value='BUTTON1' id='button1'>

    <input type='button' value='BUTTON2' id='button2'>

Using jquery, I would like to print the id of the button clicked. I tried the following:
$(".buttons > span").click(function () {
    alert("YOU CLICKED" + this.id);
});

But I think this is referring to the span object. This is weird because how come the span object has a click event? Or all jquery objects have "click"?
How do I get the id of the button in the span?
Thank You.

A: What about this?
$(".buttons > span > input").click(function () {
    alert("YOU CLICKED" + this.id);
});

A: Here is another way to do that by capturing the event's target element:
$(".buttons > span").click(function (e) {
    alert("YOU CLICKED" + e.target.id);
});

A: $(".buttons > span").click(function () {
    alert("YOU CLICKED" + $('input[type=button]',this).prop('id'));
 });

or you could bind the event to the button itself
$(".buttons > span > input[type=button]").click(function () {
    alert("YOU CLICKED" + this.id);
 });


text:
Q: There are No resources that can be added or removed from the server I have created a Dynamic web project, but I am not able to deploy it into
 Apache Tomcat Server 6.0. I am getting this error when I try to deploy my project:

There are No resources that can be added or removed from the server.

A: The issue is incompatible web application version with the targeted server. So project facets needs to be changed. In most of the cases the "Dynamic Web Module" property. This should be the value of the servlet-api version supported by the  server.
In my case,
I tried changing the web_app value in web.xml. It did not worked.
I tried changing the project facet by right clicking on project properties(as mentioned above), did not work.
What worked is:
Changing  "version" value as in jst.web to right version from
org.eclipse.wst.common.project.facet.core.xml file. This file is present in the .setting folder under your project root directory.
You may also look at this

A: if your project maven based, you can also try updating your project maven config by selecting project. Right click project> Maven>Update Project option. it will update your project config.

A: I used mvn eclipse:eclipse -Dwtpversion=2.0 in command line in the folder where I had my pom.xml. Then I refreshed the project in eclipse IDE. After that I was able to add my project.

A: I didn't find the Dynamic Web Module option when I clicked on the link, then I have installed Maven(Java EE) Integration for Eclipse WTP from the Eclipse Marketplace.Then, the above steps worked.

A: I encountered this error even though the Project Facets were set appropriately. The problem was that the "Runtime Environment" property was not set on the server:

It simply needed to be set to the appropriate Runtime:

A: Check whether your Java version is compatible with the project. Right click the project>>Properties>>Project Facets>>Java check the version is compatible with your project.

A: For this you need to update your Project Facets setting.

Project (right click) ->  Properties -> Project Facets from left
  navigation.

If it is not open...click on the link, Check the Dynamic Web Module Check Box and select the respective version (Probably 2.4). Click on Apply Button and then Click on OK.

A: The only thing that worked for me was creating a

.java-version

file with "oracle64-1.8.0.112" as the only entry ( use something that is 1.6+ )
Make sure you have dynamic web module facet turned on.

A: Right click on the project, select properties and then select "Targeted Runtimes". Check if Tomcat is selected here.

A: The issue is it is missing Dynamic Web Module facet definition.
Run the following at command line
mvn eclipse:eclipse -Dwtpversion=2.0

After build is success, refresh the project and you will be add the web project to server.

A: First check Project Facets setting as most replies had been answered.
Then check the Runtime Server is also aligned with the appropriate JRE.
In my case, I updated project JRE System Library and JDK compiler to 1.8,
but original Tomcat server is setting up on JRE 1.7,after upgraded to 1.8,the issue is resolved.


text:
Q: Finding project that belongs to client-id We found a client_secrets.json in our repo and trying to find a way to see which project it belongs to. The email field is blank and the client_id is foo.apps.googleusercontent.com. Any ideas on the best way to find who it belongs to? We have hundreds of projects, so I'm hoping we can search at an organization level

A: If it is a Service Account it should have a filed with the project_id otherwise you can identify what kind of credential is this with the field type
On the other hand, you mentioned that the client_id is foo.apps.googleusercontent.com it looks like a sample key.
Like this example: fake_client.json

{
    "web": {
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "client_secret": "foo",
        "token_uri": "https://accounts.google.com/o/oauth2/token",
        "client_email": "foo@developer.gserviceaccount.com",
        "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/foo@developer.gserviceaccount.com",
        "client_id": "foo.apps.googleusercontent.com",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs"
    }
}


text:
Q: Understanding the RFC1918 IP address range Short version, what does it exactly mean, 192.168.1.0/24, or 192.168.0.0/16?
Long version, I want to restrict my Squid server's Web Access By IP Address, and the article shows two ways,
acl home_network src 192.168.1.0/24

or,
acl home_network src 192.168.1.0/255.255.255.0

what exactly does those IP address range mean?
and how about 192.168.0.0/16?
If my IP address is 192.168.2.xx, and my route is 192.168.2.0, can I use 192.168.0.0/16?
Thanks

A: There are three RFC 1918 networks:

*

*10.0.0.0/8

*172.16.0.0/12

*192.168.0.0/16
You can subnet within each one of those ranges. For instance, 192.168.1.0/24 is a subnet within the 192.168.0.0/16 network. So is what you say you use: 192.168.2.0/24.
It all boils down to binary math. The mask length, the number after/, is the number of bits in the 32-bit IP address which belong to the network/subnet. The remaining bits, 32 - <mask length> is the number of bits for the host addresses.

A: Short answer
Both /24 and 255.255.255.0 mean the same in terms of subnetting.
Longer answer
Basically the first one is the CIDR representation of the second. The /24 makes reference to the number of binary 1s in the second form. So if you have:
255.255.255.0

In binary that is:
11111111.11111111.11111111.0

You'll see there are 24 ones, which is represented by the /24 notation. There is a lot of documentation about subnetting, but if you're using the 192.168.2.X range, you'll want to use the mentioned /24 subnet mask as it will mean that only the last octet (the one I named X) will vary.
I recommend reading this for understand better the subnetting subject.


text:
Q: How do you deserialize your own serialized code? (CodeDomSerializer) I assume custom deserialization is needed. However, neither deserialization method in SerializableExpandoObjectCodeDomSerializer is run before this error occurs.
How do you deserialize your own serialized code?

I am serializing a property of a component which is a dynamic object. Properties and values can be added, removed and changed in the property grid at design time.
This class persists design-time changes perfectly:
class SerializableExpandoObjectCodeDomSerializer : CodeDomSerializer
{
    public override object Serialize(IDesignerSerializationManager manager, object value)
    {
        var expandoObject = (SerializableExpandoObject)value;
        var expandoObjectExpression = base.GetExpression(manager, value);

        return new CodeStatementCollection(
            expandoObject.GetDynamicMemberNames()
            .Select(name => new CodeAssignStatement(
                new CodePropertyReferenceExpression(expandoObjectExpression, name), base.SerializeToExpression(manager, (object)expandoObject[name])))
            .ToArray()
        );
    }

    public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
    {
        MessageBox.Show("Never runs.");
        return base.Deserialize(manager, codeObject);
    }

    protected override object DeserializeInstance(IDesignerSerializationManager manager, Type type, object[] parameters, string name, bool addToContainer)
    {
        MessageBox.Show("Never runs.");
        return base.DeserializeInstance(manager, type, parameters, name, addToContainer);
    }
}

Resulting in serialized designer code for the this.autoSerializer.Options object:
//
// autoSerializer
//
this.autoSerializer.Options.Test = "1";
this.autoSerializer.Options.AnotherSetting = "Chart";
this.autoSerializer.CalculateLayoutID += new System.EventHandler<Techsola.Controls.CalculateLayoutIDEventArgs>(this.autoSerializer1_CalculateLayoutID);
this.autoSerializer.ComponentLayoutLoaded += new System.EventHandler<Techsola.Controls.LayoutLoadedEventArgs>(this.autoSerializer_ComponentLayoutLoaded);

When the designer is closed and reopened, if there were any properties saved, this is displayed:

The designer cannot process the code at line 129:
  this.autoSerializer.Options.Test = "1"; The code within the method
  'InitializeComponent' is generated by the designer and should not be
  manually modified.  Please remove any changes and try opening the
  designer again.

How do you cause the designer to make use of your deserialization methods before it tries to parse it and gives up?