text:
Q: Get summary of all alerts from single SPUser I am trying a way to get all alerts from all sites from a SPUser in a summarized email.
Is there any way to achieve this or I have to fetch each SPSite individually?
Thank you very much

A: You need to simply go through site, iterate through each web within the web loop through each alert, then check to see if its the same user you only want, print to string or what ever you want :)
string myUserLogin = @"MyDomain\MyUser";

SPSite oSite = SPContext.Current.Site;
SPWebCollection collWebsites = oSite.AllWebs;
foreach (SPWeb oWebsite in collWebsites)
{
    SPAlertCollection collAlerts = oWebsite.Alerts;

    foreach (SPAlert oAlert in collAlerts)
    {
        if (oAlert.User.LoginName == myUserLogin)
        {
            //do your code here...... print to label ect...
            //display the title of each site
            string siteTitle = oWebsite.Title;
            //display name of the list and item to which each alert applies
            string listTitle = oAlert.Title;
        }
    }
}

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spalertcollection(v=office.12).aspx
to send an email create a seperate method that you call after the loop has finished using the SPUtility method:
How to send E-Mail using SPUtility.SendEmail
http://www.sharepointdiary.com/2012/01/how-to-send-e-mail-using.html
so it will look somthing similar to this:
protected override void createchildcontrols()
{
    StringBuilder strbuild = new StringBuilder();
    string listResults;
    string myUserLogin = @"MyDomain\MyUser";

    SPSite oSite = SPContext.Current.Site;
    SPWebCollection collWebsites = oSite.AllWebs;

    foreach (SPWeb oWebsite in collWebsites)
    {
        SPAlertCollection collAlerts = oWebsite.Alerts;

        foreach (SPAlert oAlert in collAlerts)
        {
            if (oAlert.User.LoginName == myUserLogin)
            {
                //do your code here...... print to label ect...
                //display the title of each site
                string siteTitle = oWebsite.Title;
                //display name of the list and item to which each alert applies
                string listTitle = oAlert.Title;
                strbuild.Append("Site Title" + siteTitle + " List Name:" + listTitle).AppendLine();
            }
        }
    }

    strbuild.Insert(0, "The User "+ myUserLogin+ " has alerts assigned to the following: ").AppendLine();

    listResults = strbuild.ToString();
    sendEmail(listResults)
}

private sendEmail(string List)
{
    using (SPSite oSPSite = new SPSite("https://sharepoint.com"))  //Site collection URL
    {
                using (SPWeb oSPWeb = oSPSite.OpenWeb("News"))  //Subsite URL
                {

                    StringDictionary headers = new StringDictionary();

                    headers.Add("from", "sender@domain.com");

                    headers.Add("to", "receiver@domain.com");

                    headers..add("bcc","SharePointAdmin@domain.com");

                    headers.Add("subject", List);

                    headers.Add("fAppendHtmlTag","True"); //To enable HTML format

                    System.Text.StringBuilder strMessage = new System.Text.StringBuilder();

                    strMessage.Append("Message from CEO:");

                    strMessage.Append("<span style='color:red;'> Make sure you have completed the survey! </span>");

                    SPUtility.SendEmail(oSPWeb, headers, strMessage.ToString());

                }
     }
}

im sure ive propbably missed somthing out or done somthing wrong as im doing it all from memory and cant test it what so ever so its a proof of consept ;) but im sure there are some ways of probably doing it better but thats the first thing that has come to my mind :)
EDIT
the method above is very slow as it has alot of looping todo and will depend on how your doing it, for me I created this on a application as I can just show on another thread a loading screen(form) whilst it loops through and finishes :)
but if you cant wait or dont want to do that or not in an app than i would recommend you call the database that holds the values! more specifically your looking for the table
schedSubscription
within that it will contain all the alerts, you can query it by using this:
select * from [Content_DB].[dbo].[SchedSubscriptions] (nolock) where [UserEmail] = 'User.email@domain.com'

have that in a stored procedure that you can call from a webpart or application or call directly (not recommended due to sql attacks), have a paramiter for user email to query against.
when you call the stored procedure pass the value of the user email to return the results for the user only!
from that you should get all the info you want from list name to site name and everything else :), you can then display it in a list or what ever you want!
This method is very very fast and a better option ;) ahh btw make sure the stored procedure only has read access and nothing more!
EDIT
USE [DBNameGoesHere]
GO
/****** Object:  StoredProcedure [dbo].[GetAlertsForUser]    Script Date: 01/18/2013 16:08:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <AlmostsharepointMaster>
-- Create date: <>
-- Description: <get all alerts assigned to user by email>
-- =============================================
Create PROCEDURE [dbo].[GetAlertsForUser]
    -- Add the parameters for the stored procedure here
    @Email varchar(256)

AS
select
    *
from
    WSS_Content.dbo.SchedSubscriptions
where
    UserEmail = @Email

open sql server manager and open your DB the personal one not sharepoint DB. goto programmability folder and then stored procedures. rightclick stored procedure folder and select "new stored procedure". copy paste code from above instead of the generic code.
ok there is only two places you need to change, at the start change [DBNameGoesHere] to the DB that you store your common stored procedures and tables NOT the sharepoint DB is stored!!!
now goto from and change WSS_Content to the DB name to whatever its call that contains the SchedSubscriptions table to query.
Once you have done that you can compile and execute the code, you should see the new stored procedure within the Programmability folder under stored procedures, refresh the folder if you cant!
last step isto give permissions to that stored procedure (read only).
You can now test the stored procedure by right clicking it and select "execute stored procedure", you should get a box with one input.... on the right hand side under "value" insert the email you want to query and click ok.
You should see a list of alerts to only that user!
call this stored procedure from whereever you feel like be it from webpart or application ;)!
if you dont want all columns returned and only the ones you want just change
Select *

to
Select columnName

so it will look like this
Select UserEmail, SiteUrl, WebUrl, ListTitle

that will only return thoes columns :)
to call a stored procedure follow:
https://stackoverflow.com/questions/10556354/call-stored-procedure-in-c-sharp
EDIT
You dont need to replicate the stored procedure on each DB for each web application, just ammend the current stored procedure to take in the new DB tables like so:
USE [DBNameGoesHere]
GO
/****** Object:  StoredProcedure [dbo].[GetAlertsForUser]    Script Date: 01/18/2013 16:08:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <AlmostsharepointMaster>
-- Create date: <>
-- Description: <get all alerts assigned to user by email>
-- =============================================
Create PROCEDURE [dbo].[GetAlertsForUser]
    -- Add the parameters for the stored procedure here
    @Email varchar(256)

AS
select
    *
from
    WSS_Content.dbo.SchedSubscriptions,
     WSS2_Content.dbo.SchedSubscriptions,
     WSS3_Content.dbo.SchedSubscriptions,
     WSS4_Content.dbo.SchedSubscriptions
where
    UserEmail = @Email

this is getting from 4 different content DB so shows all from all web applications. This is the only method that i know of that is very fast as DB calls are extreamly fast compared to sharepoint (looping through spsite and spweb), if you have a dataaccess layer to call the stored procedure than its even more secure to call the stored procedure :),
     WSS_Content.dbo.SchedSubscriptions,
     WSS2_Content.dbo.SchedSubscriptions,
     WSS3_Content.dbo.SchedSubscriptions,
     WSS4_Content.dbo.SchedSubscriptions

I dont currently know if that is possible to have a master alert that alerts the user from all spsites. I would presume that involves connecting splist to one master list that contains an alert but it would be difficult. The solution i propose it relativly easy, 1 stored procedure that is connected to by webpart or application or list or feature that returns the result ;), as you stated you want to email them, I would go for the webpart method but you can setup a custom list that gets populated by the stored procedure with those values. The list would be created in a webpart and populated through that. This would also mean its only visible to the current user so only them can see their own alerts (all of them).
hope it helps :)

A: You can also get User's alerts through Powershell :
try this :
 if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null)
    {
        Add-PSSnapin "Microsoft.SharePoint.PowerShell"
    }
 $weburl = "http://dhaval-pc:2011"
 $site = new-Object Microsoft.SharePoint.SPSite($weburl)
 $webs = get-spweb $weburl
 $UserLoginName = "i:0#.f|fbamembershipuser|jignesh"

 foreach($web in $site.AllWebs)
        {
            $SPuser = $web.EnsureUser($UserLoginName)
            if($SPuser -ne $null)
            {
                foreach ($SPAlert in $SPuser.Alerts)
                {
                    Write-Host Web : $web.Title and Alert Name : $SPAlert.Title -ForegroundColor Green
                }
            }

        }

also be recursively call subwebs using $web.Webs.
Hope it helps!!!


text:
Q: Unison sync getting copy of replaced files I'm facing very serious issue. I have configured unison for synchronising file among servers. It takes copy of a file from server-1 and replace or copy file to other servers. I have added a folder directly on server-2 and server-1(base server) had old copy files and folder. After synchronising all of my files to server-2 replaced by older files from server-1. Is there any way to recover files from server-2? Does unison itself maintains a version control or backup?

A: Unison does not maintain a backup of synced files by default. You have to add some backup settings to your unison profile to enable backups. Something like:
backuplocation = central
backupdir = /path/to/central/backups
backup = Name *
backupcurr = Name *
backupsuffix = .$VERSION

In this case you will have to use other data recovery techniques to try to restore your files.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sharing file descriptors between a parent and child after the child performs an exec call (UNIX/C) I have an assignment in my OS class.  I am supposed to write three programs, one program reads from a file and writes to a pipe, one program reads from a pipe and writes to a file, and the third program is the parent which creates the pipe and does two forks in order to spawn the child processes, which immediately do exec() calls.  What I'm currently doing to make use of the pipe, is to pass the file descriptor in the exec() call as part of argv[], it works but it seems like the wrong solution.
What I want to know is if there is a better way to do this.  It seems awkward to be passing file descriptors through arguments.

A: Child process after fork inherits parent's opened file descriptors. See man 2 fork.
Ok. My first advice for you is to compile with flags -Wall -Wextra -pedantic to get all warnings. Now my changes in your code:
/*removed char pipe_readend[12];*/
char * arg[2] = {"test2", NULL}; /*first argument of program should be always it's name*/
char message[3] = {'h', 'i', '\0'}; /*c-string should be always terminated by '\0'*/
/*...*/
 case 0:
        /* child actions */
            close(pfd[1]); /* close write end */
            close(STDIN_FILENO); /*close standard input descriptor*/
            dup(pfd[0]); /*now standard input will be pfd[0]*/
            execve("test2", arg, NULL); /* start new process */
            break;

and test2.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main (void){
    char msg[3];
    read(STDIN_FILENO, msg, 3); /*read from standard input*/
    printf("test2: %s\n", msg);
    return 0;
}

So to sum up: after forking you're closing standard input descriptor and duplicates pfd[0], which will become new standard input. Then call execve(), which uses pfd[0] as it's standard input. See more in man 2 of functions fork, execve, pipe.


text:
Q: asp.net session state During Session Start, one has access to the Request object.  How about Session End, does it still have access to the Request object ?  For example I want to count how many browsers are currently connected to my application.
Edit 1 : If Session End doesn't have access to Request Object, what info does it have access to ?  Session ID, etc ?
Edit 2 : If Session End cannot be used to track disconnections, how does one track disconnections in ASP.Net ?
Thanks

A: No, the Request object is not available in Session End.
Note too that Session End only fires when you call Session.Abandon() from code, not when a Session expires due to natural timeout or what-have-you. Consequently, it is not a reliable method to use for tracking disconnections.

A: Session_End will be fired if one is using InProc.
Session_End will be fired
1) after n minutes of inactivity (n = timeout value), or
2) if someone calls Session.Abandon()
Session_End doesn't get fired if one closes the browser.
Session_End requires session state to be set.
If one needs the original Request.Browser data, one should save it in Session State.
During Session_End, it has access to the Session State.

A: from the documentation

The Session_OnEnd event occurs when a
  session is abandoned or times out. Of
  the Server built-in objects, only the
  Application Object, Server Object, and
  Session Object objects are available.
Remarks
You cannot call the Server.MapPath
  method in the Session_OnEnd script. By
  default, Session_OnEnd runs as the
  Anonymous User, as defined for the
  application. In the event that there
  isn't an Anonymous user, or the Logon
  for the Anonymous user fails, the
  OnEnd function will not be called, and
  an event will be logged.


text:
Q: Android App Connecting to Node.js server using Socket.io I'm having trouble getting my Android app to connect to a socket.io chat server. I'm using socket.io-java-client created by Gottox which can be found here: https://github.com/Gottox/socket.io-java-client
The server runs locally over port 7000. I'm using the android emulator, so I'm using 10.0.2.2:7000 to access the server.
Any help would be appreciated, I don't have much experience at all with SSL. If I find a working solution I'll also post it.
Node.js Server
var express = require('express');
var app = express();
var server = require('http').createServer(app).listen(7000);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(client){
    client.on('message', function(err, msg){
        client.broadcast.emit('message', msg);
    });
 });

package.json
{
  "name": "simplechat",
  "version": "0.0.1",
  "main": "app.js",
  "dependencies": {
    "express" : "~4.0.0",
    "socket.io" : "~0.9.13"
  }
}

Android: SendMessageActivity
public class SendMessageActivity extends Activity {

    private static final String SERVER_ADDRESS = "https://10.0.2.2:7000";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_message);

        System.out.println("Sever: " + SERVER_ADDRESS);

        try {
            SocketIO socket = new SocketIO(new URL(SERVER_ADDRESS), new IOCallback() {
                @Override
                public void onDisconnect() {
                    System.out.println("disconnected");
                }

                @Override
                public void onConnect() {
                    System.out.println("connected");
                }

                @Override
                public void onMessage(String s, IOAcknowledge ioAcknowledge) {
                }

                @Override
                public void onMessage(JSONObject jsonObject, IOAcknowledge ioAcknowledge) {
                }

                @Override
                public void on(String event, IOAcknowledge ioAcknowledge, Object... objects) {
                }

                @Override
                public void onError(SocketIOException e) {
                    e.printStackTrace();
                }
            });

        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
    }

Android Permissions
<uses-permission
    android:name="android.permission.INTERNET">
</uses-permission>

Error Code
08-09 16:07:28.224    8411-8441/com.example.puma.chatexample W/System.err﹕ io.socket.SocketIOException: Error while handshaking
08-09 16:07:28.225    8411-8441/com.example.puma.chatexample W/System.err﹕ at io.socket.IOConnection.handshake(IOConnection.java:322)
08-09 16:07:28.225    8411-8441/com.example.puma.chatexample W/System.err﹕ at io.socket.IOConnection.access$600(IOConnection.java:39)
08-09 16:07:28.225    8411-8441/com.example.puma.chatexample W/System.err﹕ at io.socket.IOConnection$ConnectThread.run(IOConnection.java:199)
08-09 16:07:28.226    8411-8441/com.example.puma.chatexample W/System.err﹕ Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'javax.net.ssl.SSLSocketFactory javax.net.ssl.SSLContext.getSocketFactory()' on a null object reference
08-09 16:07:28.226    8411-8441/com.example.puma.chatexample W/System.err﹕ at io.socket.IOConnection.handshake(IOConnection.java:302)
08-09 16:07:28.227    8411-8441/com.example.puma.chatexample W/System.err﹕ ... 2 more

A: I know this not really answers to the OP's posts, but for those who may be interested, this is a tutorial I made to make communicate your Android with a Node.js server -without any additional library- :
https://causeyourestuck.io/2016/04/27/node-js-android-tcpip/
This is a foretaste of how it looks like at the end:
Client socket = new Client("192.168.0.8", 1234);
socket.setOnEventOccurred(new Client.OnEventOccurred() {
    @Override
    public void onMessage(String message) {
    }

    @Override
    public void onConnected(Socket socket) {
        socket.send("Hello World!");
        socket.disconnect();
    }

    @Override
    public void onDisconnected(Socket socket, String message) {
    }
});

socket.connect();

A: Puma has already answered on how you can implement a socket connection using SocketIO. This has nothing new to contribute. Yet, it is an attempt to help fellow newbies, as also introduce the implementation of Socket.io's java library.
Socket.IO has its own java implementation on Github, which you can follow along to create a socket application for Android/Java.
Android side:
Include this in  your build gradle
compile ('io.socket:socket.io-client:0.8.3') {
    // excluding org.json which is provided by Android
    exclude group: 'org.json', module: 'json'
}

Provide Permission in your app:

<uses-permission android:name="android.permission.INTERNET" />

Android Code:
The structure of code is similar to how you would code in Node. The message in socket.on is similar to node's socket.on('message', ...)

import io.socket.client.Socket;
import io.socket.client.IO;
import io.socket.emitter.Emitter;

final Socket socket;
try{
socket = IO.socket("http://192.168.1.1:8080");

socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

    @Override
    public void call(Object... args) {
        socket.emit("message", "hi");
        socket.disconnect();
    }

}).on("message", new Emitter.Listener() {
        //message is the keyword for communication exchanges
    @Override
    public void call(Object... args) {
        socket.emit("message", "hi");
    }

}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

    @Override
    public void call(Object... args) {}

});
    socket.connect();

}
catch(Exception e){

}

Node.js side
Create normal sockets using socket.io

A: I actually solved the problem. I used my PC's local IP http://192.168.0.xxx:7000 and the app was able to connect to the chat server from the emulator. I don't know why this works, but it might help out someone in the future :)
Update:
This is how I ended up structuring the project. I created a singleton class to handle socket connections Android side (you could also do it as a service). When receiving a message, the singleton class broadcasts an intent to the rest of the app. The intent is then picked up by a broadcast receiver in the relevant activity.
Android Side (singleton):
public class SocketSingleton {

    private static SocketSingleton instance;
    private static final String SERVER_ADDRESS = "http://1.2.3.4:1234";
    private SocketIO socket;
    private Context context;

    public static SocketSingleton get(Context context){
        if(instance == null){
            instance = getSync(context);
        }
        instance.context = context;
        return instance;
    }

    public static synchronized SocketSingleton getSync(Context context){
        if (instance == null) {
            instance = new SocketSingleton(context);
        }
        return instance;
    }

    public SocketIO getSocket(){
        return this.socket;
    }

    private SocketSingleton(Context context){
        this.context = context;
        this.socket = getChatServerSocket();
        this.friends = new ArrayList<Friend>();
    }

    private SocketIO getChatServerSocket(){
        try {
            SocketIO socket = new SocketIO(new URL(SERVER_ADDRESS), new IOCallback() {
                @Override
                public void onDisconnect() {
                    System.out.println("disconnected");
                }

                @Override
                public void onConnect() {
                    System.out.println("connected");
                }

                @Override
                public void on(String event, IOAcknowledge ioAcknowledge, Object... objects) {
                    if (event.equals("chatMessage")) {
                        JSONObject json = (JSONObject) objects[0];
                        ChatMessage chatMessage = new ChatMessage(json);

                        Intent intent = new Intent();
                        intent.setAction("newChatMessage");
                        intent.putExtra("chatMessage", chatMessage);
                        context.sendBroadcast(intent);
                    }
                }
                @Override
                public void onError(SocketIOException e) {
                    e.printStackTrace();
                }
            });
            return socket;
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
        return null;
    }
}

Android Side (activity):
public class ChatActivity extends Activity {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat);
    IntentFilter newChatMessageFilter = new IntentFilter("newChatMessage");
    this.registerReceiver(new MessageReceiver(), newChatMessageFilter);

    ...

    public class MessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent){
            final ChatMessage chatMessage =(ChatMessage) intent.getExtras().get("chatMessage");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mAdapter.add(chatMessage);
                    mAdapter.notifyDataSetChanged();
                }
            });
        }
    }
}

Server Side:
var express = require('express');
var app = express();
var server = require('http').createServer(app).listen(1234);
var io = require('socket.io').listen(server);

io.sockets.on('connection', function(client){

    console.log("client connected: " + client.id);

    client.on("sendTo", function(chatMessage){
        console.log("Message From: " + chatMessage.fromName);
        console.log("Message To: " + chatMessage.toName);

        io.sockets.socket(chatMessage.toClientID).emit("chatMessage", {"fromName" : chatMessage.fromName,
                                                                    "toName" : chatMessage.toName,
                                                                    "toClientID" : chatMessage.toClientID,
                                                                    "msg" : chatMessage.msg});

    });
});

A: You're emulator network is different from your PC's as I have heard. So if you could by change try this on an actual phone that is connected to the same network as your PC.
You probably wont be able to ping 10.0.2.2 from your emulator or the other way around from your pc to emulator.


text:
Q: Concave collision detection in Bullet I am a Bullet rookie, so I apologise in advance if my questions sound trivial to you.
I need to load a set of concave triangle meshes from .stl files and perform collision detection. Objects can be moved by the user. From the user manual, I read:
"CONCAVE TRIANGLE MESHES:
For static world environment, a very efficient way to represent static triangle meshes is to use a btBvhTriangleMeshShape."
Hence, my questions are:
- can Bullet detect collisions between concave mesh objects modelled using the BvhTriangleMeshShape?
- what is the real difference between contactTest and CollisionWorld::PerformDiscreteCollisionDetection()
- do I need to specify a different collision algorithm for concave collision detection?
I am working with BulletSharp a maintained C# wrapper of Bullet. what I did, was set up my bullet environment:
CollisionConfiguration bt_collision_configuration;
CollisionDispatcher bt_dispatcher;
BroadphaseInterface bt_broadphase;
CollisionWorld bt_collision_world;

double scene_size = 500;
uint max_objects = 16000;

bt_collision_configuration = new DefaultCollisionConfiguration();
bt_dispatcher = new CollisionDispatcher(bt_collision_configuration);

float sscene_size = (float)scene_size;
Vector3 worldAabbMin = new Vector3(-sscene_size, -sscene_size, -sscene_size);
Vector3 worldAabbMax = new Vector3(sscene_size, sscene_size, sscene_size);
bt_broadphase = new AxisSweep3_32Bit(worldAabbMin, worldAabbMax, max_objects);
bt_collision_world = new CollisionWorld(bt_dispatcher, bt_broadphase, bt_collision_configuration);    [/code]

And load my CollisionObjects as BvhTriangleMeshShape.
To detect collisions, I used:
contactTest(object, callback)

The result with this code is that the ContactResultCallback::NeedsCollision function is called every time two bounding boxes intercept, but no manifolds are found if 2 meshes intersect.
And secondly:
    bt_collision_world.PerformDiscreteCollisionDetection();
    int numManifolds = bt_collision_world.Dispatcher.NumManifolds;

Using this secondary code, no manifolds are found at all.

A: As you've already read in manual, btBvhTriangleMeshShape can be used for static objects only. This means that there is no collision algorithm for two objects of this type (because if all of them are static, they cannot collide). As you tried, you can test the intersection of their bounding boxes, but no collision manifold will be ever created.
If you wonder what is the use of btBvhTriangleMeshShape, it is meant for detecting precise collision between convex dynamic objects and static concave environment.
The official solution suggested by Bullet is to perform convex decomposition of every concave model that is used for moving objects. The preferred method for convex decomposition is HACD (Hierarchical Approximate Convex Decomposition). An example can be found in Bullet Examples.
Another algorithm worth trying is V-HACD (Volumetric Hierarchical Approximate Convex Decomposition), which produces shapes with better topology than the previous one but convex hull is less precise - the result collision shape is bigger then the original mesh. The error rate can be controlled by the resolution but it slows down the process.


text:
Q: Visual Studio 2017: Can't open Solution directly Yesterday I uninstalled Visual Studio 2015 and then installed Visual Studio 2017 Enterprise. Now I have the following problem when I try to open a solution (existings and also if I create a completely new one):
When I open "MySolution.sln" directly per double click or pinned from Taskbar, then the solution opens very shortly but then immediately closes again and I am at the plain Visual Studio start screen.
But when I open the solution from Visual Studio via "Open Solution" dialog, everything works as expected.
Has anybody an idea why this could happen? What is the difference between these 2 opening ways?
EDIT: The problem only occurs, when the solution is in a TFS source controlled folder.


text:
Q: TypeError: unorderable types: tuple() < int() in Python 3 The below code is ordering poker hands. It works well in Python 2.7 but it does not work in Python 3. What are the changes that have been made causing it to give an TypeError: unorderable types: tuple() < int()?
def poker(hands):
    scores = [(i, score(hand.split())) for i, hand in enumerate(hands)]
    winner = sorted(scores , key=lambda x:x[1])[-1][0]
    return hands[winner]

def score(hand):
    ranks = '23456789TJQKA'
    rcounts = {ranks.find(r): ''.join(hand).count(r) for r, _ in hand}.items()
    score, ranks = zip(*sorted((cnt, rank) for rank, cnt in rcounts)[::-1])
    if len(score) == 5:
        if ranks[0:2] == (12, 3): #adjust if 5 high straight
            ranks = (3, 2, 1, 0, -1)
        straight = ranks[0] - ranks[4] == 4
        flush = len({suit for _, suit in hand}) == 1
        '''no pair, straight, flush, or straight flush'''
        score = ([1, (3,1,1,1)], [(3,1,1,2), (5,)])[flush][straight]
    return score, ranks

 >>> poker(['8C TS KC 9H 4S', '7D 2S 5D 3S AC', '8C AD 8D AC 9C', '7C 5H 8D TD KS'])
 '8C AD 8D AC 9C'

A: It is happening because you are comparing int and a tuple. In python2x, default cmp operation was defined for different inbuilt objects, which has been removed in python3.

Python 3 ignores the cmp() method. In addition to this, the cmp() function is gone! This typically results in your converted code raising a TypeError: unorderable types error. So you need to replace the cmp() method with rich comparison methods instead. To support sorting you only need to implement lt(), the method used for the "less then" operator, <.

Official documentation
So, in python2, we can do something like this
(2, 3) > 2

but it raises TypeError in python3. If this code was working in python2, then most probably it was bug that was implicitly being handled by default comparison behaviour.
Now in your example:-
#value of scores that are being compared for sorting
scores = [(0, (1, (11, 8, 7, 6, 2))), (1, (1, (12, 5, 3, 1, 0))), (2, ((2, 2, 1), (12, 6, 7))), (3, (1, (11, 8, 6, 5, 3)))]

print(type(scores[1][1][0])) # <class 'int'>
print(type(scores[2][1][0])) # <class 'tuple'>

which as I have explained does not work in python3. What is the criteria you are assuming for comparing a tuple and an int.
If you really want to compare different type of objects, then you need to roll out your own version of tuple, and use that object in your scores instead.
class MyTuple(tuple):

     def __lt__(self, other):
        pass

Default tuple comparison python 2
Note:- I don't recommend using this approach. It was just for instructional purposes.

A: The solution:
Convert the integer into a tuple:
score = ([(1, ), (3,1,1,1)], [(3,1,1,2), (5,)])[flush][straight]


text:
Q: Greasemonkey unsafeWindow Vk I'm coding greacemonkey userscript for Vk comment automation.
And can't understand why I cant access to object.
Vk window obj have two different Composer and composer objects (the same words, but first capital lower). From unsafeWindow Composer is accessable, but lowercapital object composer return undefined.
(function (window, undefined) {
    .....
    some code
    finding post, openning comment form, pasting text
    need to call:
    unsafeWindow.composer.addMedia.checkMessageURLs("Comment text
http://example.com",true);
    .....
    console.log(unsafeWindow.Composer); // return object
    console.log(unsafeWindow.composer); // return undefined
}

if run
composer.addMedia.checkMessageURLs("Comment text
http://example.com",true);

directly in browser console - all ok.
Any ideas?

A: composer (lowercase) is created on demand, long after the Greasemonkey script runs.
To access it from the script, you need to wait for it. Something like:
var composerChkTmr  = setInterval (doStuffWith_composer, 222);

function doStuffWith_composer () {
    if (typeof unsafeWindow.composer === "undefined")
        return;

    clearInterval (composerChkTmr);

    // DO WHATEVER, WITH unsafeWindow.composer HERE.
}


text:
Q: How to add old data and events in a table on an existing webpage using greasemonkey? I made a greasemonkey script that tracks the user infos and populates them on the database with timestamps. So whenever I check on the webpage with below infos, the script fetches it and updates it on the database with the current timestamp. For instance:
Name : XYZ
Id : 123123
Age : 24
Salary : 25000
Current Whereabouts : Florida
Current Work : XXX
Allowance Generated today: 150

So I want to make a table below this info page showing the last 30 days activity.
Something like this below those existing infos in the webpage:


text:
Q: Secure flow from Client to OAuth2 to Server to Client again I'm not sure if this is specific to the discord OAuth2 flow but I'll mention that I'm currently trying to get a user's discord id for use later.
My current flow is as follows:

*

*User clicks on button on client which redirects to discord auth link

*Discord sends code callback to firebase function

*Firebase sends for Token+Refresh from auth server

*Firebase stores user id and such(iffy here)

*Firebase sends confirmation back to the Client

I need the UID of the person calling this function in order to store the data into the correct document on firestore. I was originally going to consider going with:

*

*User clicks on button on client which redirects to discord auth link

*Discord sends code callback to client

*Client sends code to Firestore Function

*Firebase sends for Token+Refresh from auth server

*Firebase stores user id

*Firebase sends confirmation back to the Client

but I'm worried about the insecurity mentioned here: https://discordjs.guide/oauth2/#oauth2-flow

A: I finally decided that it doesn't matter if the client (or anyone for that matter) has access to the code callback since I'm using it to fetch for the actual token+refresh anyways. The code is useless without the app_id and app_secret anyways.


text:
Q: Digital Pen for Dell Laptop I have Dell Inspiron laptop and I have just started using Photoshop. It is quite hard to draw using mouse so I was thinking of buying a digital pen. Do I need a special laptop with touch screen to draw or how can I make it work?

A: You cannot draw on the screen itself if it didn't come as a touchscreen. The only dell models which are touchscreens are a few of the Studio laptops (not most of them) and the Latitude XT.
One alternate option is to get a digitizer tablet, which is an external tablet without a display that you can write on. It's less intuitive than drawing straight on the screen, but gives you much more precision than a mouse or touchpad.

Wacom is one of the main manufacturers for them, though there are others as well. Do some looking around to find what might work for you, and if you can, try one out in person before buying. A quick google product search might get you looking in the right direction.


text:
Q: Are there shopkeepers in DoomRL? I started playing DoomRL today, and have already maxed out my inventory with a bunch of duplicates of weapons I already have, mostly pistols. Is there any way for me sell these, or should I just use up what ammo they have in them and then drop them?

A: Woah, I never expected such a question :D.
No, there are no shopkeepers in DoomRL, nor will there ever be. Duplicate guns are useless, unless:

*

*you want to quickly swap between them (using Prepared slot)

*you want to mod some of them later

*a second pistol might be useful if you want to go for Dualgunner

*BFG's are nice to carry cells (they carry 100, while a cell stack is 50)

Also, note that using "U" you can unload a weapon on the ground or in the inventory.

A: There are no shopkeepers in the current version of the game. Scavenge the ammo and ditch the guns.


text:
Q: Toggle React checkboxes without state I have some checkboxes that I'm just using as filters for data that need to run a function on click. Usually, and all tutorials ive read, have suggested to handle checkbox checked attribute using state. Is it possible to do this without using state? I don't really want to declare all the different checkboxes in my state just to toggle them on and off. I was hoping I could do something like this
<input type="checkbox" checked={true} onChange={(e) => e.target.checked = false } />

A: Sure you can, using uncontrolled components, then using refs to get the values. It's considered "quick and dirty", but you can do it no problem. See this article for more detailed information: https://reactjs.org/docs/uncontrolled-components.html.


text:
Q: Control becomes visible in Outlook addin with WindowsAPI I'm finishing up an outlook add-in and i'm running into a weird issue. I am using the windows api (user32.dll) to disable a control on the Outlook New Message Window or a Message Compose window.
This works fine. However if the user adds/removes the BCC field the Window redraws or something and the disabled button becomes visible again. This also happens if the user is responding to a message that isn't the latest in the 'conversation' and outlook will animate the window with the latest message error. The user32.dll function i'm using is ShowWindow(hwnd, WindowShowStyle.Hide)
tl;dr: Disabled/Hidden Control becomes visible again on redraw.
Any thoughts on this?


text:
Q: Create self-signed terminal services certificate and install it The server RDP certificate expires every 6 months and is automatically recreated, meaning I need to re-install the new certificate on the client machines to allow users to save password.
Is there a straightforward way to create a self-signed certificate with a longer expiry?
I have 5 servers to configure.
Also, how do I install the certificate such that terminal services uses it?
Note: Servers are not on a domain and I'm pretty sure we're not using a gateway server.

A: You can create a self-signed certificate with many different tools.  Makecert is one such tool:
http://msdn.microsoft.com/en-us/library/bfsktky3(v=vs.110).aspx
The OID for 'Server Authentication' is 1.3.6.1.5.5.7.3.1, so the argument -eku 1.3.6.1.5.5.7.3.1 will be in there somewhere.
makecert -r -pe -n CN="MyServer" -eku 1.3.6.1.5.5.7.3.1 -ss my -sr localmachine -b 01/01/2000 -e 01/01/2036

That should get you a self signed certificate in your computer's personal store that expires in 2036.

A: If you have a large domain, the best result would be to setup an enterprise Certificate Authority.  Then just setup policies so that your system automatically acquire a valid certificate from the CA.
Also setup policies so that any certificates issued from that CA will be automatically trusted.

A: Completing Ryan Ries' answer above (as I've just worked out)

*

*Execute the makecert command suggested

makecert -r -pe -n CN="MyServer" -eku 1.3.6.1.5.5.7.3.1 -ss my -sr localmachine -b 01/01/2000 -e 01/01/2036

*Manage Computer Certificates - you'll find the created certificate in Personal Certificates

*Export the certificate (right click -> all tasks -> export -> include private key -> give it a secure password)

*On the TS server, open RD Gateway Manager

*Right click on the TS Server -> Properties -> SSL Certificate tab

*Import the certificate

...you should be good to go.


text:
Q: The pgAdmin 4 server could not be contacted Hola formatee el Windows para 64 bits  a la hora de ejecutar el pgAmin 4 me sale ese error.
Espero que me puedan ayudar a solucionarlo
Error:

pgAdmin Runtime Environment
-------------------------------------------------------- Python Path: "C:\Program Files\PostgreSQL\13\pgAdmin 4\python\python.exe" Runtime
Config File:
"C:\Users\Duster\AppData\Roaming\pgadmin\runtime_config.json" pgAdmin
Config File: "C:\Program Files\PostgreSQL\13\pgAdmin 4\web\config.py"
Webapp Path: "C:\Program Files\PostgreSQL\13\pgAdmin
4\web\pgAdmin4.py" pgAdmin Command: "C:\Program
Files\PostgreSQL\13\pgAdmin 4\python\python.exe -s C:\Program
Files\PostgreSQL\13\pgAdmin 4\web\pgAdmin4.py" Environment:

*

*ALLUSERSPROFILE: C:\ProgramData

*APPDATA: C:\Users\Duster\AppData\Roaming

*CHROME_CRASHPAD_PIPE_NAME: \.\pipe\crashpad_4860_YOLTTCBOTIVCNFTV

*CHROME_RESTART: NW.js|¡Vaya! Se ha producido un fallo en NW.js. ¿Quieres reiniciar el navegador ahora?|LEFT_TO_RIGHT

*CommonProgramFiles: C:\Program Files\Common Files

*CommonProgramFiles(x86): C:\Program Files (x86)\Common Files

*CommonProgramW6432: C:\Program Files\Common Files

*COMPUTERNAME: DUSTER-PC

*ComSpec: C:\Windows\system32\cmd.exe

*FP_NO_HOST_CHECK: NO

*HOMEDRIVE: C:

*HOMEPATH: \Users\Duster

*LOCALAPPDATA: C:\Users\Duster\AppData\Local

*LOGONSERVER: \DUSTER-PC

*NUMBER_OF_PROCESSORS: 2

*OS: Windows_NT

*Path: C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Program
Files\Git\cmd;C:\Program Files\Common Files\Microsoft Shared\Windows
Live

*PATHEXT: .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC

*PGADMIN_INT_KEY: bf0f0bf7-a0b2-44d3-906f-1b56cc803359

*PGADMIN_INT_PORT: 62609

*PGADMIN_SERVER_MODE: OFF

*PROCESSOR_ARCHITECTURE: AMD64

*PROCESSOR_IDENTIFIER: Intel64 Family 6 Model 42 Stepping 7, GenuineIntel

*PROCESSOR_LEVEL: 6

*PROCESSOR_REVISION: 2a07

*ProgramData: C:\ProgramData

*ProgramFiles: C:\Program Files

*ProgramFiles(x86): C:\Program Files (x86)

*ProgramW6432: C:\Program Files

*PSModulePath: C:\Windows\system32\WindowsPowerShell\v1.0\Modules\

*PUBLIC: C:\Users\Public

*SESSIONNAME: Console

*SystemDrive: C:

*SystemRoot: C:\Windows

*TEMP: C:\Users\Duster\AppData\Local\Temp

*TMP: C:\Users\Duster\AppData\Local\Temp

*USERDOMAIN: Duster-PC

*USERNAME: Duster

*USERPROFILE: C:\Users\Duster

*windir: C:\Windows

*windows_tracing_flags: 3

*windows_tracing_logfile: C:\BVTBin\Tests\installpackage\csilogfile.log

Traceback (most recent call last):   File "C:\Program
Files\PostgreSQL\13\pgAdmin 4\web\pgAdmin4.py", line 16, in
from cheroot.wsgi import Server as CherootServer   File "C:\Program Files\PostgreSQL\13\pgAdmin
4\python\lib\site-packages\cheroot\wsgi.py", line 36, in
from . import server   File "C:\Program Files\PostgreSQL\13\pgAdmin
4\python\lib\site-packages\cheroot\server.py", line 70, in
import email.utils   File "", line 259, in load_module   File "email\utils.py", line 29, in    File
"", line 259, in load_module   File "socket.py",
line 49, in  ImportError: DLL load failed while importing
_socket: El par�metro no es correcto.


text:
Q: Get parent(key) from value (an element stored in a list) I am stuck in a problem wherein I have to find the common 'parent' of items in a list.
Here's the problem-
I have a reference file - hierarchy.json, and this file is loaded as a dictionary in my super class.
{
    "DATE": ["ISO", "SYSTEM", "HTTP"],
    "IP": ["IPv4", "IPv6"],
    "PATH": ["UNIX", "WINDOWS"]
}

As an input, I get a list of values and I expect to get a set of elements, which belong to the same parent (referring to the hierarchy.json file) as an output. Even better, if I could get the parent name, that would be great.
input_list = ["ISO", "UNIX", "HTTP"]

result = do_something(input_list)

print('RESULT:\t', result)

>>> RESULT:    set("ISO","HTTP")

Essentially, I want to make sets of the elements which belong to different "parents" in the element.
I know this can be done O(n^3) by looping through each element of the list. This is obviously not the best way to achieve the result.
Here's what I have tried -
def do_something(input_list: list, reference_dir: dict) -> list:
    result_list = []
    for lists in reference_dir.values():
        results = []
        for i in input_list:
            for j in input_list:
                if i != j:
                    if set([i,j]).issubset(set(lists)):
                        results.extend(set([i,j]))
        result_list.append(set(results))
    return result_list

input_list = ["ISO", "UNIX", "HTTP", "SYSTEM","WINDOWS"]
reference_dir = {"DATE": ["ISO", "SYSTEM", "HTTP"],"IP": ["IPv4", "IPv6"],"PATH":["UNIX", "WINDOWS"]}

result = do_something(input_list, reference_dir)
print('RESULT:\t', (result))

>>> RESULT:  [{'SYSTEM', 'HTTP', 'ISO'}, set(), {'UNIX', 'WINDOWS'}]

Is there a way to optimize this/implement this in a better way?
Edited (Added) ->
ALSO,
if there's a way I could get the name of the 'parent' as the output, that would be AWESOME.
>>> RESULT:  [DATE, PATH]

Thanks.

A: def do_something(input_list: list, reference_dir: dict) -> list:
    sets_1 = {k: set() for k in reference_dir.keys()}
    sets_2 = {item: sets_1[k] for k, list in reference_dir.items() for item in list}
    for input in input_list:
        sets_2[input].add(input)
    return sets_1

reference_dir = {
    "DATE": ["ISO", "SYSTEM", "HTTP"],
    "IP": ["IPv4", "IPv6"],
    "PATH": ["UNIX", "WINDOWS"]
}

input_list = ["ISO", "UNIX", "HTTP"]

print(do_something(input_list, reference_dir))

Prints:
{'DATE': {'HTTP', 'ISO'}, 'IP': set(), 'PATH': {'UNIX'}}

What do_something does:

*

*sets_1 = {k: set() for k in reference_dir.keys()} This line creates a dictionary where each key is a key form reference_dir and the value is an empty set.

*sets_2 = {item: sets_1[k] for k, list in reference_dir.items() for item in list} This line creates another dictionary. The keys are the elements of the lists which are the values of the reference_dir dictionary and the value for each key is the corresponding empty set created in step 1 associated with the lists owning key.

*for input in input_list: sets_2[input].add(input) Each element of input_list is added to appropriate set using the dictionary created in step 2 to select the correct set.

*return sets_1 This returns a dictionary whose keys are all the keys in reference_dir and whose values are now the filled in sets (some of which might be empty). The keys are the "names" of the sets you were looking for.

See Demo


text:
Q: YYYY-MM-DDTHH:mm not getting am/pm momentjs I know this type of question is not really apropiated, but I'm stuck on it and some help would be apreciated it. I have the following date:
2018-04-26T08:19:30+02:00

But when I try to get the Hours and Minutes, the result I get is:
20:19 p

What I'm doing is the following:
let momentDay = (moment(el.time,'HH:mm a').format('HH:mm a'));

I don't know how I could get the real time, the one should give me: 08:19 instead of 20:19
Thanks

A: You should use hh for twelve hour time, rather than HH, which is for 24 hour time.
Also, if el.time is a datetime object, or a recognizable unambiguous date format (as yours is), then you don't need to specify a format in the constructor:
let momentDay = moment(el.time).format('hh:mm aa');


text:
Q: Grouping list by object except one field I have to group list items if the items fields are the same. Above in my code, it works what I want if every id is the same. But product ids are unique. For that reason, I cant make the right grouping.
Here I wrote an example product model but original product model has 20+ fields and some of them are object list. Product model is came from api.
I want to make grouping by item except for id.
    data class Product(
    val id: Int,
    val name: String,
    val price: Int,
    val quantity: Int,
    val subModels: List<SubModel>,
    val values: List<String>
)

data class SubModel(
    val name: String,
    val value: String
)

data class GroupedProduct(
    val product: Product,
    val count: Int,
    val totalQuantity: Int,
    val isGroup: Boolean
)

var products = listOf(
    Product(1, "p1", 10, 2, listOf(SubModel("a", "1")), listOf("a")),
    Product(1, "p1", 10, 2, listOf(SubModel("a", "1")), listOf("a")),
    Product(1, "p1", 10, 2, listOf(SubModel("b", "2")), listOf("a")),
    Product(1, "p2", 12, 1, listOf(SubModel("a", "1")), listOf("a")),
    Product(1, "p3", 12, 1, listOf(SubModel("a", "1")), listOf("a")),
)

var groupedPersons: MutableList<GroupedProduct> = mutableListOf()

products.groupBy { it }.forEach {
    if (it.value.size > 1)
        groupedPersons.add(GroupedProduct(it.key, it.value.size, it.value.getTotalQuantity(), true))
    else
        groupedPersons.add(GroupedProduct(it.key, it.value.size, it.value.size, false))
}

fun List<Product>.getTotalQuantity(): Int {
    var totalQuantity = 0
    forEach {
        totalQuantity += it.quantity
    }
    return totalQuantity
}

groupedPersons.forEach {
        println(it)
    }

Prints:
GroupedProduct(product=Product(id=1, name=p1, price=10, quantity=2, subModels=[SubModel(name=a, value=1)], values=[a]), count=2, totalQuantity=4, isGroup=true)
GroupedProduct(product=Product(id=1, name=p1, price=10, quantity=2, subModels=[SubModel(name=b, value=2)], values=[a]), count=1, totalQuantity=1, isGroup=false)
GroupedProduct(product=Product(id=1, name=p2, price=12, quantity=1, subModels=[SubModel(name=a, value=1)], values=[a]), count=1, totalQuantity=1, isGroup=false)
GroupedProduct(product=Product(id=1, name=p3, price=12, quantity=1, subModels=[SubModel(name=a, value=1)], values=[a]), count=1, totalQuantity=1, isGroup=false)

When item ids are different grouping results be like that obviously.
GroupedProduct(product=Product(id=1, name=p1, price=10, quantity=2, subModels=[SubModel(name=a, value=1)], values=[a]), count=1, totalQuantity=1, isGroup=false)
GroupedProduct(product=Product(id=2, name=p1, price=10, quantity=2, subModels=[SubModel(name=a, value=1)], values=[a]), count=1, totalQuantity=1, isGroup=false)
GroupedProduct(product=Product(id=3, name=p1, price=10, quantity=2, subModels=[SubModel(name=b, value=2)], values=[a]), count=1, totalQuantity=1, isGroup=false)
GroupedProduct(product=Product(id=4, name=p2, price=12, quantity=1, subModels=[SubModel(name=a, value=1)], values=[a]), count=1, totalQuantity=1, isGroup=false)
GroupedProduct(product=Product(id=5, name=p3, price=12, quantity=1, subModels=[SubModel(name=a, value=1)], values=[a]), count=1, totalQuantity=1, isGroup=false)

A: You must replace the id with a meaningless id (like -1 in my example):
data class Product(
  val id: Int,
  val name: String,
  val price: Int,
  val quantity: Int
)

data class GroupedProduct(
  val product: Product,
  val count: Int,
  val totalQuantity: Int,
  val isGroup: Boolean
)

var products = listOf(
  Product(1, "p1", 10, 2),
  Product(2, "p1", 10, 2),
  Product(3, "p1", 10, 2),
  Product(4, "p2", 12, 1),
  Product(5, "p3", 12, 1),
)

val result = products
  .groupBy { it.copy(id = -1) }
  .map { (_, values) ->
    val product = values.first().copy(id = -1, quantity = values.sumOf { it.quantity })
    GroupedProduct(product, values.count(), values.sumOf { it.quantity }, values.count() > 1)
  }

result.forEach(::println)

Output:
GroupedProduct(product=Product(id=-1, name=p1, price=10, quantity=6), count=3, totalQuantity=6, isGroup=true)
GroupedProduct(product=Product(id=-1, name=p2, price=12, quantity=1), count=1, totalQuantity=1, isGroup=false)
GroupedProduct(product=Product(id=-1, name=p3, price=12, quantity=1), count=1, totalQuantity=1, isGroup=false)

A: Change the grouping to
products.groupBy { Triple(it.name, it.price, it.quantity) }.forEach {
    if (it.value.size > 1)
        groupedPersons.add(GroupedProduct(it.value.first(), it.value.size, it.value.getTotalQuantity(), true))
    else
        groupedPersons.add(GroupedProduct(it.value.first(), it.value.size, it.value.size, false))
}


text:
Q: Restlet - trouble attaching Resource class with Router Prototyping with Restlet 2.1.0, Java SE version, I am having trouble mapping ServerResource classes to urls.  I've tried quite a few variations using the Router.attach method, but nothing has worked.
My current code looks like this:
/**
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    final Router router = new Router();
    router.attach("/hello", FirstServerResource.class);
    router.attach("/json", Json.class);

    Application myApp = new Application() {
        @Override
        public org.restlet.Restlet createInboundRoot() {
            router.setContext(getContext());
            return router;
        };
    };

    new Server(Protocol.HTTP, 8182, myApp).start();
}

When I browse to http://localhost:8182/hello it doesn't do the template match correctly.  Debugging through the source code, I see what happens is that the match logic sees the requested resource as http://localhost:8182/hello instead of just /hello.  The Restlet code where this happens is here:
// HttpInboundRequest.java
// Set the resource reference
if (resourceUri != null) {
    setResourceRef(new Reference(getHostRef(), resourceUri));

    if (getResourceRef().isRelative()) {
        // Take care of the "/" between the host part and the segments.
        if (!resourceUri.startsWith("/")) {
            setResourceRef(new Reference(getHostRef().toString() + "/"
                    + resourceUri));
        } else {
            setResourceRef(new Reference(getHostRef().toString()
                    + resourceUri));
        }
    }

    setOriginalRef(getResourceRef().getTargetRef());
}

In the code above, it sees the Resource as relative, and therefore changes the requested resource from /hello to the full url.  I'm missing something obvious here, but I'm totally stumped.

A: Finally found the solution by turning on the logging (FINE). I saw this log message:

By default, an application should be attached to a parent component in
  order to let application's outbound root handle calls properly.

I don't totally understand what it meant (maybe I have to read docs start to finish?).  Attaching the application to a VirtualHost fixed the problem:
public static void main(String[] args) throws Exception {
    final Router router = new Router();
    router.attach("/hello", FirstServerResource.class);
    router.attach("/json", Json.class);
    router.attachDefault(Default.class);

    Application myApp = new Application() {
        @Override
        public org.restlet.Restlet createInboundRoot() {
            router.setContext(getContext());
            return router;
        };
    };

    Component component = new Component();
    component.getDefaultHost().attach("/test", myApp);

    new Server(Protocol.HTTP, 8182, component).start();
}


text:
Q: java.util.logging, ResourceBundles, SAAJ: exception on loading Glassfish OSGi webapp bundle I'm being driven out of my mind by the following exception:
java.lang.IllegalArgumentException:
com.sun.xml.messaging.saaj.soap.LocalStrings != com.sun.xml.internal.messaging.saaj.soap.LocalStrings
    at java.util.logging.Logger.getLogger(Logger.java:357)
    at com.sun.xml.internal.messaging.saaj.soap.SAAJMetaFactoryImpl.<clinit>(SAAJMetaFactoryImpl.java:41)

It's occurring when I try to deploy a WAB (web application OSGi bundle) to Glassfish (3.1.1).
I'm trying to use an up-to-date version of SAAJ (com.sun.xml.messaging.saaj...) rather than the old JDK one (which is the com.sun.xml.internal.saaj... one), by putting the string com.sun.xml.messaging.saaj.soap.ver1_1.SOAPMessageFactory1_1Impl in the file META-INF/services/javax.xml.soap.MessageFactory.
It appears there is some logging going on before the OSGi classloading kicks in, and therefore the 'wrong' ResourceBundle is being returned during initialization of the static log field of com.sun.xml.messaging.saaj.soap.MessageFactoryImpl (SAAJ's implementation of javax.xml.soap.MessageFactory).
Anyone seen this / any workarounds on offer?

A: Never got to the bottom of this, but manifest voodoo eventually made it go away (with all of the javax.xml.ws / javax.ws.rs packages in Import-Package rather than on the bundle classpath WEB-INF/lib).
It was also possible to work around it by using
-Djavax.xml.soap.MessageFactory=com.sun.xml.messaging.saaj.soap.ver1_1.SOAPMessageFactory1_1Impl

on Glassfish startup, though obviously this forces that implementation on all users of MessageFactory.

A: See: JDK-6741342 : Logger.getLogger() throws java.lang.IllegalArgumentException on saaj classes.

Instead, it's related to the introduction of saaj into JDK 6.....and the workaround involved re-ordering jars.


text:
Q: Buck regulator frequency I am trying to use a buck regulator. Usually I make it use at its Max frequency and then just use it. But now, we want to go for Emi and emc certification. I am hence told that this switching (a few hundreds of kHz) can generate noise in the system. So what is the optimal frequency to prevent rfi or noise ?

A: Keep in mind that I'm a neophyte on EMI (and didn't [have to] get any products through certifications), but I've managed to find something in a digikey article narrowly but somewhat vaguely addressing your question:

Another benefit of switching at a frequency as high as 4 MHz is that it enables designers to avoid critical noise-sensitive frequency bands, such as AM radio. However, there is a trade-off. For example, electromagnetic interference (EMI) can be problematic when operating at high-switching frequencies. EMI from a switching regulator is proportional to the square of the switching frequency – in other words, if the switching frequency doubles, the EMI can increase fourfold.

Hope this helps.
Also keep in mind that what continent[s] you want this certified on matters. From Maniktala's A-Z book, which I warmly recommend on practical issues like this:

The FCC spectrum for digital equipment (currently) begins at 450 kHz, while the equivalent CISPR/EN regulations start at 150 kHz. So, FCC compliance can be
  achieved with a relatively small and inexpensive filter. CISPR/EN Class A compliance often requires a filter with at least twice the volume of
  the FCC-level unit. This filter can therefore be up to 50% more expensive. CISPR/EN Class B compliance can require a filter with 3-10 times the volume of the FCC unit, and could cost up to four times more.

A: Hundreds of khz is not your biggest problem. You should worry about hundreds of mhz that are involved in switch rise time, boost capacitor charging, etc. It all, by the way, starts with good layout, which if you don't have, is the reason for EMI problems.
There are several simple rules to follow, i hope not to miss something.

*

*Keep magnetic flux as constant as you can: try making inductor current flow almost same way when the switch is on and off.

*Where you have pulsed current, make sure return parh is right near the line. Of course, the both paths must be very short. Consider ferrite for boost cap to limit bandwidth.

*Prevent capacitive coupling with switching node by removing plane underneath.

2 is most tricky, so pay close attention to whe pulsed currents flow. Use capacitors to provide the pulses, where needed, mostly on switch input.
By the way, you should also use a nice common mode filter on your input to prevent conductive emission.
Good luck!


text:
Q: Why Are Zero Length VLAs UB? The 2011 standard explicitly states...

6.7.6.2 Array declarators

*If the size is an expression that is not an integer constant expression: if it occurs in a
  declaration at function prototype scope, it is treated as if it were replaced by
  *; otherwise,
  each time it is evaluated it shall have a value greater than zero.  The size of each instance
  of a variable length array type does not change during its lifetime.   Where a size expression is part of the operand of a sizeof operator and changing the value of the size expression would not affect the result of the operator, it is unspecified whether or not
  the size expression is evaluated.

It's contrived, but the following code seems reasonable.
size_t vla(const size_t x) {

  size_t a[x];
  size_t y = 0;

  for (size_t i = 0; i < x; i++)
    a[x] = i;

  for (size_t i = 0; i < x; i++)
    y += a[i % 2];

  return y;
}

Clang seems to generate reasonable x64 assembly for it (without optimizations).  Obviously indexing a zero length VLA doesn't make sense, but accessing beyond bounds invokes undefined behavior.
Why are zero length arrays undefined?

A: int i = 0;
int a[i], b[i];

Is a == b? It shouldn't be - they're different objects - but avoiding it is problematic. If you leave a gap between a and b unconditionally, you're wasting space in the i > 0 case. If you check whether i == 0 and only leave a gap then, you're wasting time in the i > 0 case.
It gets worse with multidimensional arrays:
int i = 0;
int a[2][i];

You can pad between two variables, but where could you pad here? There's no way to do it without breaking the invariant that sizeof (int[2][i]) == 2 * i * sizeof (int). If you don't pad, then a[0] and a[1] have the same address, and you're breaking a different important invariant.
It's a headache that isn't worth defining.

A: Although we can see that gcc supports zero length arrays an extension, so clearly they are useful. From a standard perspective it would seem to create some issues since as it stands now each object should have a unique address. We can see this from the draft C99 and C11 standard section 6.5.9 Equality operators which says:

Two pointers compare equal if and only if both are null pointers, both are pointers to the
  same object (including a pointer to an object and a subobject at its beginning) or function,
  both are pointers to one past the last element of the same array object, or one is a pointer
  to one past the end of one array object and the other is a pointer to the start of a different
  array object that happens to immediately follow the first array object in the address
  space.94)

So this would require a bit of special casing and most of the usefulness such as flexibile arrays can be provided using alternative methods.
It would also likely require changes in other places as well, as M.M. points out array to pointer decay in section 6.3.2.1 Lvalues, arrays, and function designators:

[...]an expression that has
  type ''array of type'' is converted to an expression with type ''pointer to type'' that points
  to the initial element of the array object and is not an lvalue[...]

This seems like it would require several non-trivial changes for minimal added benefit.

A: Looking at C standard:
C11- 6.7.6.2 Array declarators (p1):

[...] If the expression is a constant expression, it shall have a value greater than zero. [...]

(p5):

If the size is an expression that is not an integer constant expression: if it occurs in a declaration at function prototype scope, it is treated as if it were replaced by *; otherwise, each time it is evaluated it shall have a value greater than zero. [...]

4. Conformance:

If a "shall" or "shall not" requirement that appears outside of a constraint or runtime- constraint is violated, the behavior is undefined. Undefined behavior is otherwise indicated in this International Standard by the words "undefined behavior" or by the omission of any explicit definition of behavior. There is no difference in emphasis among these three; they all describe "behavior that is undefined".

Therefore, declaring a zero size array leads to undefined behavior of  the program.


text:
Q: Realm upgrade to 0.89.0 breaks RecyclerView I have started using Realm for one of my projects a while ago and when trying to upgrade realm to version 0.89.0 or higher, my RecyclerView behavior completely falls apart. I tried to isolate the issue and came down to this sample : https://bitbucket.org/pr-shadoko/realmrecyclerviewtest
Here are the main classes:
The activity:
public class MainActivity extends AppCompatActivity {
    ItemTouchHelper itemTouchHelper;
    RecyclerView recyclerView;
    TagsAdapter adapter;
    Realm realm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RealmConfiguration config = new RealmConfiguration.Builder(this).build();
        Realm.setDefaultConfiguration(config);
        realm = Realm.getDefaultInstance();

        adapter = new TagsAdapter(realm, new OnDragStartListener() {
            @Override
            public void onDragStart(RecyclerView.ViewHolder viewHolder) {
                itemTouchHelper.startDrag(viewHolder);
            }
        });
        itemTouchHelper = new ItemTouchHelper(new TagTouchHelperCallback(adapter));
        recyclerView = (RecyclerView) findViewById(R.id.rv);
        recyclerView.setAdapter(adapter);
        itemTouchHelper.attachToRecyclerView(recyclerView);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.action_add:
                Tag tag = new Tag();
                tag.setTag("#tag" + tag.getTagId());
                realm.beginTransaction();
                realm.copyToRealmOrUpdate(tag);
                realm.commitTransaction();
                adapter.notifyItemInserted(1);
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

The RecyclerView Adapter:
public class TagsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements ItemTouchHelperAdapter {
    private static final int TYPE_TAG = 0;
    private static final int TYPE_HEADER = 1;

    private Realm realm;
    private RealmResults<Tag> tags;
    private OnDragStartListener dragStartListener;

    public TagsAdapter(Realm realm, OnDragStartListener dragStartListener) {
        this.realm = realm;
        this.tags = realm.where(Tag.class).findAllSorted("order", Sort.DESCENDING);
        this.dragStartListener = dragStartListener;

        setHasStableIds(true);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch(viewType) {
            case TYPE_TAG:
                View taskView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
                return new TagViewHolder(taskView);
            case TYPE_HEADER:
                View headerView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
                return new HeaderViewHolder(headerView);
            default:
                return null;
        }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int adapterPosition) {
        switch(holder.getItemViewType()) {
            case TYPE_TAG:
                onBindViewHolderTag((TagViewHolder) holder, adapterPosition);
                break;
            case TYPE_HEADER:
                onBindViewHolderHeader((HeaderViewHolder) holder, adapterPosition);
                break;
            default:
        }
    }

    private void onBindViewHolderTag(final TagViewHolder holder, final int adapterPosition) {
        final Tag tag = tags.get(getDataSetPosition(adapterPosition));
        holder.title.setText(tag.getTag());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("TAGS", "item clicked: id=" + tag.getTagId() + " ; adapterPosition=" + adapterPosition + " ; datasetPosition=" + getDataSetPosition(adapterPosition));
            }
        });
        holder.itemView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
                    dragStartListener.onDragStart(holder);
                }
                return false;
            }
        });
    }

    private void onBindViewHolderHeader(HeaderViewHolder holder, int adapterPosition) {
        holder.header.setText("TITLE");
    }

    private int getDataSetPosition(int adapterPosition) {
        switch(getItemViewType(adapterPosition)) {
            case TYPE_TAG:
                return adapterPosition - 1;
            case TYPE_HEADER:
            default:
                return RecyclerView.NO_POSITION;
        }
    }

    @Override
    public int getItemCount() {
        return tags.size() + 1;
    }

    @Override
    public long getItemId(int adapterPosition) {
        switch(getItemViewType(adapterPosition)) {
            case TYPE_TAG:
                return tags.get(getDataSetPosition(adapterPosition)).getTagId();
            case TYPE_HEADER:
            default:
                return RecyclerView.NO_ID;
        }
    }

    @Override
    public int getItemViewType(int adapterPosition) {
        if(adapterPosition == 0) {
            return TYPE_HEADER;
        }
        return TYPE_TAG;
    }

    @Override
    public boolean onItemMoved(final int fromAdapterPosition, final int toAdapterPosition) {
        Log.i("TAGS", "move from " + fromAdapterPosition + " to " + toAdapterPosition);
        if(getItemViewType(toAdapterPosition) != TYPE_TAG) {
            return false;
        }

        Tag task1 = tags.get(getDataSetPosition(fromAdapterPosition));
        Tag task2 = tags.get(getDataSetPosition(toAdapterPosition));
        Log.i("TAGS", "realm pos from=" + getDataSetPosition(fromAdapterPosition) + " ; to=" + getDataSetPosition(toAdapterPosition));
        int order1 = task1.getOrder();
        realm.beginTransaction();
        task1.setOrder(task2.getOrder());
        task2.setOrder(order1);
        realm.copyToRealmOrUpdate(task1);
        realm.copyToRealmOrUpdate(task2);
        realm.commitTransaction();
        notifyItemMoved(fromAdapterPosition, toAdapterPosition);
        return true;
    }

    @Override
    public void onItemSwiped(RecyclerView.ViewHolder holder, int direction) {}

    public class TagViewHolder extends RecyclerView.ViewHolder {
        public final TextView title;

        public TagViewHolder(View itemView) {
            super(itemView);
            this.title = (TextView) itemView.findViewById(R.id.label);
        }
    }

    public class HeaderViewHolder extends RecyclerView.ViewHolder {
        public final TextView header;

        public HeaderViewHolder(View itemView) {
            super(itemView);
            this.header = (TextView) itemView.findViewById(R.id.label);
        }
    }
}

The Tag table definition:
public class Tag extends RealmObject {
    @Ignore
    private final static Object nextIdLock = new Object();
    @Ignore
    private static Integer nextId;

    @PrimaryKey
    @Required
    private Integer tagId;
    @Required
    private Integer order;
    @Required
    private String tag;

    public Tag() {
        synchronized(nextIdLock) {
            if(nextId == null) {
                Realm realm = Realm.getDefaultInstance();
                RealmResults<Tag> tags = realm.where(Tag.class).findAll();
                if(tags.size() != 0) {
                    nextId = tags.max("tagId").intValue() + 1;
                } else {
                    nextId = 0;
                }
                realm.close();
            }
            order = tagId = nextId++;
        }
    }

    public Integer getTagId() {
        return tagId;
    }

    public Tag setTagId(Integer tagId) {
        this.tagId = tagId;
        return this;
    }

    public Integer getOrder() {
        return order;
    }

    public Tag setOrder(Integer order) {
        this.order = order;
        return this;
    }

    public String getTag() {
        return tag;
    }

    public Tag setTag(String tag) {
        this.tag = tag;
        return this;
    }
}

Other files (classes, interfaces, layouts, etc.) are pretty straigthforward so I will not paste them here to keep the question readable but they are available in the repository.
Now the symptoms:

*

*realm version 0.88.2 (branch master):

*

*Clicking on the 'add item' button adds an item on top of the list with a smooth animation

*Touching an item allows to drag it to reorder the list

*So it works as expected

*realm version 0.89.0 (branch realm-0.89.0):

*

*Clicking on the 'add item' button:

*

*1st click: adds the item to the realm but does not update the view

*further clicks: crashes the app ("java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{349439e7 position=2 id=0, oldPos=1, pLpos:1 scrap [attachedScrap] tmpDetached no parent}")

*Touching an item:

*

*Stops the dragging at first swap

*swaps the items in the realm (can be seen by forcing the activity to re-create, thus building the RecyclerView from fresh data)

*Reverts view to its original state or swaps others elements??

The only thing that changed between the two branches is the Realm version.
I looked around for a similar issue with no luck. At this point, I am not sure if this is the 0.89.0+ that breaks the RecyclerView behavior or if this is the 0.88.2 that was not not supposed to work this way.
Any help would be greatly appreciated.

A: That's because in 0.89.0, to create proper iteration behavior on RealmResults, local commits update the RealmResults only on the next looper event, and not immediately.
So this code here
    realm.beginTransaction();
    task1.setOrder(task2.getOrder());
    task2.setOrder(order1);
    realm.copyToRealmOrUpdate(task1);
    realm.copyToRealmOrUpdate(task2);
    realm.commitTransaction();
    notifyItemMoved(fromAdapterPosition, toAdapterPosition);

Will fail, because the list hasn't yet updated after commitTransaction().
I've been meaning to figure out a smart way to solve this problem but to no avail, although forcing an immediate refresh via the HandlerController can achieve the same results.


text:
Q: material ui : reactjs: TextField: Multiline: How to show minimum number of rows and after than no scroll In material ui Texfield for multiline. I want to show a minimum 3 rows in the beginning and there up expand the text area. I dont want to show scroll if the rows exceed 3
I tried this
        <TextField
          id="outlined-multiline-static"
          label="Multiline"
          multiline
          rows={3}
          defaultValue="Default Value"
          variant="outlined"
        />

What is see is

HOw to set min rows.

A: To increase the height, instead of showing scroll you can make use of maxRows prop instead. so the scroll would be added after the maxRows are reached
https://codesandbox.io/s/material-demo-forked-ccchw
<TextField
      id="outlined-multiline-static"
      label="Multiline"
      multiline
      rows={3}
      defaultValue="1"
      maxRows={10}
      variant="outlined"
    />

A: Add minRows to the TextField component
  <TextField
     id="outlined-multiline-static"
     label="Multiline"
     multiline
     rows={3}
     defaultValue="Default Value"
     variant="outlined"
     maxRows={3}
  />


text:
Q: Math.random() outcome seems flipped I'm currently playing with a true or false script on the outcome from Math.Random()
code is as following
var win = Math.random() >= (percent / 100);

        if (win === true) {
           console.log("true")
        } else {
            console.log("false")
        }

*

*In this case percent is 50 by default. If i put the percent to 90% it keeps returing false more or less all the time Math.random() >= (90 / 100); .. But since you only have 10% to return false, thats strange

*If i set the percent to 1% it keeps returning true (but i suppose it almost always should return false, since you technically only have 1% chance to return true).
Is the >= (Greater than or equal too) flipped the wrong side around - it does feel like you get less chance of win = true, even if you put in 90(percent) / 100
Hope someone can clarify if my symbols are wrongly placed

A: If percentage = 90, this means that Math.random has to be 0.9 or greater, which return true in 10% of the cases.
So reverse the comparator:
var win = Math.random() < (percent / 100);


text:
Q: How to Change Counter position for SQL field I have a field called IntQID, which is an id for each post that is recorded in the SQL database. If a post is 1533, the next entery will be 1534,1535, etc...
I recently messed up and inserted a manual entry with an ID of 4000. Now the counter has been using that as the last entry, so now new posted are 4001, 4002, 4003.
How do I change the counter to go back to using the next in line after 1533?
Hope this makes sense. Thanks!

A: To set the auto_increment value to 1533, use:
ALTER TABLE tbl AUTO_INCREMENT = 1533;

To my knowledge, you can't get the highest existing value for setting it in the ALTER TABLE statement without using two queries minimum.

A: ALTER TABLE tbl AUTO_INCREMENT = 1000;


text:
Q: Localhost points to different address I have an app developed with CakePHP and it is working just fine on my local machine. Now, I wanted to develop another app with CakePHP. I installed cake in a different folder, configured vhost and server block and did everything like for the first app. I created an empty app, just basic controller and view and when I type the address for the second app I get the first app!!! Weird thing is that all links are working and when I click I get in browser url like secondapp/companies but the content is firstapp/companies. Once more, the second app is empty, no controllers, views and models, just a basic one. Then I did all that in htdocs, and the same problem occurs (none of the apps wasn't in htdocs, but in folders on E partition).
Can someone please give me some help before I kill myself?
Thank you...

A: If the problem is not on the database configuration, maybe cache problems ? Try it on a private browser/incognito ?


text:
Q: how to add one column array to already existing array with shape 10000*17 Please help me here, I am new to python. I am trying to add an array of one column to another array of shape 10000*17. Below are the samples. Please help me to concatenate two arrays:
 [[ 0.02061183, -0.90794402,  0.92005926, 0.5405426 , 4.85191978,  3.65479782],
   [-0.52203821, .50416184, -0.87750086, -0.625578  , -0.08879011, -0.57718519]]

I need to add a new row of array [1,2,3,4,5,6] to the above array.

A: You can use numpy.insert(arr, i, the_object_to_be_added, axis):
import numpy as np

my_array = [[1, 2, 3],
             4, 5, 6]]

np.insert(my_array, 2, [7, 8, 9], axis=0)
# output my_array = [[1, 2, 3],
#                    [4, 5, 6],
#                    [7, 8, 9]]

or
my_array = [[1, 2, 3],
            [4, 5, 6]]
np.insert(my_array, 1, [7, 8], axis=1)
# output my_array = [[1, 7, 2, 3],
#                    [4, 8, 5, 6]]


text:
Q: Expand card in React I'm using React and Framer motion to create animations in my project. I'm struggling to identify if there is a way to expand a card on click as a new page. There is a list of cards in my home page which look like this, (localhost:3000)
Home Page(localhost:3000)
I need to add an expanding animation, Where once we click on the card, The card itself should expand to the full page and display the content but as a new page/route in React. (localhost:3000/item1) Details Page(localhost:3000/item1
Can I achieve this expanding animation with framer-motion and React? Or do I have to use some other library for animations?


text:
Q: Is Lion server really a valid server for small business? I'm considering to replace my existing windows based server on my small business (< 10 employees) with a mac mini server with Lion Server installed. But after a look at the App Store, I noticed a lot of 1-star reviews labeling this OS as "a toy", "unstable", "downgrade with respect to Leopard Server" and so on. My usage for this would be essentially for e-mail management (but using Kerio to have exchange support), calendar, internal web site (web apps), account management, some centralized apps (to be accessed using VNC), iOS based devices management, Windows virtualization to support legacy apps (essentially for accounting), VPN.
I'm not asking for a complete review of this OS, this is not a right place, bust just a short comment from the users in the community that had the change to work with this new OS.
Besides, and this is a bonus question, do you have some experience in using Lion server to manage centralized Xcode development? (we currently use our own MacBooks and we keep in sync using Git, I'd like to know for different approaches based on OSX Server).

A: I've never tried any of the Mac Server products. But AnandTech has a pretty good in-depth review of Mac OS X Lion Server. A few of the conclusions:

...server administrators will be happy to know that, in spite of its deeply cut price and consumer-friendly distribution method, Lion Sever stacks up favorably against Snow Leopard Server.

and

OS X Server is most useful in a handful of different scenarios: the first is that you have a small network that's in need of a full-featured but easy-to-manage and simple-to-license server product. The second is that you're managing a network of any size that used to be all-Windows, but hosts a growing number of Macs (this is often the case in education, for example) - OS X Server knows that it's going to be finding its way into a lot of Windows houses, and as such it integrates fairly well with existing Active Directory setups. The last is that you have a bunch of iOS devices flooding your network and you have no idea what to do with them - iOS management may be Lion Server's ace in the hole.

(emphasis mine)
Seems to fit your intended usage pretty well.
About your other question:

Besides, and this is a bonus question, do you have some experience in using Lion server to manage centralized Xcode development? (we currently use our own MacBooks and we keep in sync using Git, I'd like to know for different approaches based on OSX Server).

Keep using git, use the OSX server as central repository (maybe consider buying GitHub Enterprise or using an free/open source alternative for managing your git interaction). Install a CI-tool (Jenkins or similar) on the server and use it to create automated builds. Should work quite nicely.


text:
Q: Django template custom filter does not change size of button I have a Django template variable and custom filter inside a button stylized with bootstrap 4.
<button type="submit" class="btn btn-outline-dark text-left mb-2" disabled>
    {{ my_variable | my_filter}}
</button>

If my_filterincreases the length of my_variable, I find that the size of the button is not automatically extended as I assume that its size is processed by Django before the filter is applied. Is there a way around this?


text:
Q: How to increment by group There is a table and now add a new column -- sort_num int default 0
id  level   sort_num
1   1   0
2   1   0
3   2   0
4   2   0
5   2   0
6   3   0
7   3   0
8   3   0
9   3   0

Now I want to set sort_num values like below
id  level   sort_num
1   1   1
2   1   2
3   2   1
4   2   2
5   2   3
6   3   1
7   3   2
8   3   3
9   3   4

The Java code implement above requirement is
    int sortNum = 0;
    int currentLevel = fooList.get(0).getLevel();
    for (RuleConf foo : fooList) {
        if(currentLevel != foo.getLevel()){
            sortNum = 0;
            currentLevel = foo.getLevel();
        }
        foo.setSortNum(++sortNum);
    }

I want to know if Java8 could simplify above code?
PS. Use mysql to implement this requirement
set @index:=0; update t set sort_num = (@index:=@index+1) where level = 1 order by id;
set @index:=0; update t set sort_num = (@index:=@index+1) where level = 2 order by id;
set @index:=0; update t set sort_num = (@index:=@index+1) where level = 3 order by id;

A: The best approach is to stick to your plain enhanced for loop. I don't think it is possible to come up with a single Stream solution, since you need to have intermediate values. Like:
Map<Integer, List<RuleConf>> levels = fooList.stream()
    .collect(Collectors.groupingBy(RuleConf::getLevel));
levels.values().forEach(v ->
    IntStream.range(0, v.size()).forEach(i -> v.get(i).setSortNum(i + 1))
);

A: If you keep track of the next order numbers yourself, you may do it with one stream. This solution is thread safe as well, hence should work with parallel streams:
Map<Integer, AtomicInteger> orders = new ConcurrentHashMap<>();
fooList.stream().forEachOrdered(foo -> {
    orders.putIfAbsent(foo.getLevel(), new AtomicInteger());
    foo.setOrder(orders.get(foo.getLevel()).incrementAndGet());
});

It should outperform the other stream-solutions, because it requires to iterate over the list only ones.


text:
Q: How can I parse *.vector.pbf about Mapbox vector tile map?
*

**.pbf("Protocolbuffer Binary Format") is primarily intended as an alternative to the XML format.

*There are two formats of *.osm.pbf and *.vector.pbf. What tools can I use to open these files? (I know JOSM can open *.osm.pbf files, but it can't open *.vector.pbf files.)

*If I want to write own *.vector.pbf files in Mapbox, how do I work for that?

Thanks!

A: Regarding question #2, extracting PBF data
Using GDAL's ogr2ogr is the easiest method (I found).
Given a file named 1583.vector.pbf decode it to a, for example, shapefile (folder) named output:
# cmd   show prog.  output format     output name     input name
ogr2ogr -progress -f "ESRI Shapefile" output          1583.vector.pbf

Regarding question #3, creating PBF data
Use the same command as above but swap the input/outputs and output format:
# example source: https://gdal.org/drivers/vector/mvt.html
ogr2ogr -f MVT mytileset source.gpkg -dsco MAXZOOM=10

A: The Vector tiles used by Mapbox are serialized as Protocol Buffers.
Protocol Buffers allow you to efficiently compress the vector data inside the tile.
The Mapbox Tile Specification is available on github.
Esri has also adopted the same specification for their products.
You can find a list of parsers, renderers & CLI utilities here: https://github.com/mapbox/awesome-vector-tiles
In the common scenario, you can use mapbox-gl-js to render the vector tiles on the client. To generate vector tiles, you can use Mapbox Studio. This will require uploading your data online in the Studio. You can also use Mapbox Studio Classic (the older version) to generate the tiles locally.
Internally, Mapbox Studio uses the tilelive API, so you can programatically generate the tiles. In the list above there are other good  alternatives as well.


text:
Q: '@' in paste() in R I'm new to R. I'm using 3.5.1. I'm trying to use a piece of code I got from someone else. I generate an object called repcounts that's something like this:
> repcounts
t c
1 6
> class(repcounts)
[1] "integer"
> str(repcounts)
 Named int [1:2] 1 6
 - attr(*, "names")= chr [1:2] "t" "c"

The next line of code is
paste(?~@~\rep count:?~@~\, paste(paste0(names(repcounts), repcounts), collapse=?~@~\_?~@~]))

I get an error here:
Error: unexpected '@' in "paste(?~@"

Same problem with just a portion of the line:
> paste(paste0(names(repcounts), repcounts), collapse=?~@~\_?~@~])
Error: unexpected '@' in "paste(paste0(names(repcounts), repcounts), collapse=?~@"

Does anyone recognize what this line is trying to do, and what the problem with '@' is?

A: It seems that command should be something like:
paste("rep count:", paste(paste0(names(repcounts), repcounts), collapse="_"))


text:
Q: WP7 - How to set the border color for text box from ViewModel How to use GotFocus() and LostFocus() from ViewModel?
 private void TxtDescribeGroup_GotFocus(object sender, RoutedEventArgs e)
    {
        TxtDescribeGroup.BorderBrush = new SolidColorBrush(Colors.Orange);
    }

    private void TxtDescribeGroup_LostFocus(object sender, RoutedEventArgs e)
    {
        TxtDescribeGroup.BorderBrush = new SolidColorBrush(Colors.Gray);
    }

This code written in the Xaml.CS.
But I want to write all the code in ViewModel.
Any one let me know how to write the events in ViewModel?
And also how to write the selection changed event in ViewModel for ListBox?
 private void lstShow_Tap(object sender, GestureEventArgs e)
    {
        if (lstShow.SelectedItem != null)
        {
            ListBox item = (ListBox)sender;
            LoginPageModel listItem = (LoginPageModel)item.SelectedItem;
            MessageBox.Show("Selected FirstName==> " + listItem.FirstName);
        }
    }

This is also written in Xaml.Cs. How to write in the ViewModel.
Thanks in advance..

A: In XAML (assuming you already set your DataContext)
<Border BorderBrush="{Binding Path=BorderBrush}">
    ... your stuff here
</Border>

Then in your ViewModel (assuming you implement INotifyPropertyChanged) just add a property:
private Brush borderBrush;
public Brush BorderBrush {
    get { return borderBrush; }
    set {
        if(value!=borderBrush) {
            value=borderBrush;
            // this notifies your UI that the property has changed and it should read the new value
            // should be already declared in your view model or base view model or whatever
            // MVVM framework you are using
            OnPropertyChanged("BorderBrush");
        }
    }
}


text:
Q: Finding eigenvalues and eigenvectors of a certain matrix Find eigenvalues and eigenvectors of a matrix $A_{n\times n}$  where elements $a_{ij} $ of $A_{n\times n}$ are given as
\begin{cases}
\alpha,  & \text{if }i=j \\[2ex]
1, & \text{if }|i-j|=1\\[2ex]
0 & \text{otherwise}
\end{cases}
where $\alpha$ is a constant.
I tried finding out the eigenvalues by finding the polynomial equation of this equation and the result which I was getting was of the form:-
$|A_{n\times n}-\lambda I_{n\times n}|=(\alpha-\lambda)(|A_{(n-1)\times (n-1)}-\lambda I_{(n-1)\times (n-1)}|-|A_{(n-2)\times (n-2)}-\lambda I_{(n-2)\times (n-2)}|)$
But I was not able to go further.

A: A formula for the eigenvalues and eigenvectors of such a matrix is given here.
We can deduce these eigenvalues and eigenvectors nicely, however, if we correctly "guess" that we can find a complete set of eigenvectors in which each eigenvector is of the form
$$
v = (\sin(\theta), \sin(2 \theta), \dots , \sin (n \theta)).
$$
See this post for details on this approach.
Note that it suffices to consider the case of $\alpha = 0$, since for any matrix $M$, the matrices $M$ and $M + \alpha I$ have the same eigenvalues (where $I$ denotes the identity matrix).


text:
Q: Minimum elevation within km Trying to find the minimum elevation within 10km of a certain latitude and longitude using R.
So far I have
dem <- getData("SRTM", lat=42.90, lon=-78.85, path = datadir)
plot(dem)

I know I need to create spatial points and eventually buffer/extract the information.
When I try:
buffdem <- buffer(dem, width=10000)

It does not work because I don't have any points.
I tried
dem <- getData("SRTM", lat=42.90, lon=-78.85, path = datadir)
coords <- data.frame(
  x = rnorm(100),
  y = rnorm(100)
)
coordinates(dem)

spdf = SpatialPointsDataFrame(coords, dem)

I get the following error:

Error in validObject(.Object) :    invalid class
  "SpatialPointsDataFrame" object: invalid object for slot "data" in
  class "SpatialPointsDataFrame": got class "RasterLayer", should be or
  extend class "data.frame"

A: I think this accomplishes what you need:
library(raster)
#elevation <- getData("SRTM", lat=42.90, lon=-78.85)
#poi <- cbind(lon=-78.85, lat=42.90)

using a smaller example data set for quicker download:
elevation <- getData('alt', country='CHE')
poi <- cbind(8.13, 46.47)

e <- extract(elevation, poi, buffer=10000)

sapply(e, min, na.rm=TRUE)

By the way, this is a duplicate of this and this question.


text:
Q: Dynamic query 'in clause' parameter not working I am using dynamic query in stored procedure. I passed two parameters one for "equal case" and the other for "in case". The in case not working while the equal case is working as shown in the images. Is there any way that I can put the parameter for "in case" in query.
Here is my procedure for better editing.
    Alter PROCEDURE [dbo].[Test_In_Clause]

    -- Add the parameters for the stored procedure here
    @name nvarchar(50) = NULL,
    @class nvarchar(50) = NULL

AS
BEGIN

    declare
    @sql nvarchar(max),
    @ParameterDef NVARCHAR(500)

    set @ParameterDef = '@name nvarchar(50),
                        @class nvarchar(50)'

    set @sql  = 'Select * from aaa_Students where Name = @name and Class in @class'
    print @sql
    exec sp_Executesql @sql, @ParameterDef, @name = @name, @class = @class

END

PS: I don't want to use Select * from aaa_Students where Name = @name and Class in ('+ @class +') format in order to protect sql injection.

A: Try this:
    alter PROCEDURE [dbo].[Test_In_Clause]

    -- Add the parameters for the stored procedure here
    @name nvarchar(50) = NULL,
    @class nvarchar(50) = NULL

AS
BEGIN

    declare
    @sql nvarchar(max),
    @ParameterDef NVARCHAR(500)

    set @ParameterDef = N'@name nvarchar(50),
                        @class nvarchar(50)'

    set @sql  = 'Select * from aaa_Students where Name = @name and Class in (@class)'
    print @sql
    execute sp_Executesql @sql, N'@name nvarchar(50),@class nvarchar(50)', @name = @name, @class = @class


text:
Q: Beautifulsoup: how to iterate a table I am trying to extract data from a dynamic table with the following structure:
Team 1 - Score - Team 2 - Minute first goal.
It is a table of soccer match results and there are about 10 matches per table and one table for each matchday. This is an example of the website in working with: https://www.resultados-futbol.com/premier/grupo1/jornada1
For this I am trying web scraping with BeautifulSoup in Python. Although I've made good progress, I'm running into a problem. I would like to generate a code that would iterate data by data each row of the table and I would get each data to a list so that I would have, for example:
List Team 1: Real Madrid, Barcelona
Score list: 1-0, 1-0
List Team 2: Atletico Madrid, Sevilla
First goal minutes list: 17', 64'

Once I have the lists, my intention is to make a complete dataframe with all the extracted data. However, I have the following problem: the matches that end 0-0. This implies that in the column Minute first goal there is none and it doesn't extract anything, so I can't 'fill' that value in any way in my dataframe and I get an error. To continue with the previous example, imagine that the second game has ended 0-0 and that in the 'Minutes first goal list' there is only one data (17').
In my mind the solution would be to create a loop that takes the data cell by cell and put a condition in 'Score' that if it is 0-0 to the list of Minutes first goal a value for example 'No goals' would be added.
This is the code I am using. I paste only the part in which I would like to create the loop:
page = BeautifulSoup(driver.page_source, 'html.parser') # I have to use Selenium previously cos I have to expand some buttons in the web
table = page.find('div', class_= 'contentitem').find_all('tr', class_= 'vevent')

teams1 = []
teams2 = []
scores = []

for cell in table:
    team1 = cell.find('td', class_='team1')
    for name in local:
        nteam1 = name.text
        teams1.append(nteam1)

    team2 = cell.find('td', class_='team2')
    for name in team2:
        nteam2 = name.text
        teams2.append(nteam2)

    score = cell.find('span', class_='clase')
    for name in score:
        nscore = name.text
        scores.append(nscore)

It is not clear to me how to iterate over the table to be able to store in the list the content of each cell and it is essential to include a condition "when the score cell is 0-0 create a non-goals entry in the list".
If someone could help me, I would be very grateful. Best regards

A: You are close to your goal, but can optimize your script a bit.

*

*Do not use these different lists, just use one:
data = []

*Try to get all information in one loop, there is an td that contains all the information and push a dict to your list:
for row in soup.select('tr.vevent .rstd'):
    teams = row.select_one('.summary').get_text().split(' - ')
    score = row.select_one('.clase').get_text()

    data.append({
        'team1':teams[0],
        'team2':teams[1],
         'score': score if score != '0-0' else 'No goals'
     })

*Push your data into DataFrame
 pd.DataFrame(data)

Example
from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd

driver = webdriver.Chrome(executable_path=r'C:\Program Files\ChromeDriver\chromedriver.exe')
url = 'https://www.resultados-futbol.com/premier/grupo1/jornada1'
driver.get(url)

soup = BeautifulSoup(driver.page_source, 'html.parser') # I have to use Selenium previously cos I have to expand some buttons in the web

data = []

for row in soup.select('tr.vevent .rstd'):
    teams = row.select_one('.summary').get_text().split(' - ')
    score = row.select_one('.clase').get_text()

    data.append({
        'team1':teams[0],
        'team2':teams[1],
        'score': score if score != '0-0' else 'No goals'
    })

pd.DataFrame(data)


text:
Q: Single login in subdomains I have one mvc5 application with few subdomains like this:

*

*example.com

*ex1.example.com

*ex2.example.com

When I log in to example.com i'm not logged in other subdomains. I added in web.config following node:
<authentication mode="Forms">
    <forms name=".ASPXAUTH" loginUrl="~/Account/Login/" protection="Validation" timeout="120" path="/" domain=".example.com"/>
</authentication>

But it still doesnt work :(
Please help.

A: Check that you are using the same machine key for for each of the applications in the subdomains.  Also you may need to set the machine key compatibility mode to Framework20SP2.
Edit:
Take a look at this post as well: ASP.NET Identity Cookie across subdomains