text:
Q: valueNotFound Error when getting back an API call into JSON When I do an API call and get data back it cannot be decoded into my struct properly.
The error I get is:

failed to convert valueNotFound(Swift.Int, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "newDeathsByDeathDate", intValue: nil)], debugDescription: "Expected Int value but found null instead.", underlyingError: nil))

My Code is:
override func viewDidLoad() {
        super.viewDidLoad()

        let url = """
https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=nation;areaName=england&structure=%7b%22date%22:%22date%22,%22areaName%22:%22areaName%22,%22areaCode%22:%22areaCode%22,%22newCasesByPublishDate%22:%22newCasesByPublishDate%22,%22cumCasesByPublishDate%22:%22cumCasesByPublishDate%22,%22newDeathsByDeathDate%22:%22newDeathsByDeathDate%22,%22cumDeathsByDeathDate%22:%22cumDeathsByDeathDate%22%7d
"""
        print(url)
        print(NSURL(string: url))
        getData(from: url)

        // Do any additional setup after loading the view.
    }

    private func getData(from url: String) {
        guard let theURL = URL(string: url) else { print ("oops"); return }
        let getfromurl = URLSession.shared.dataTask(with: theURL, completionHandler: {data, response, error in
            guard let data = data, error == nil else{
                print("Something Went Wrong")
                return
            }

            //Have data
            var result: Response?
            do {
                result = try JSONDecoder().decode(Response.self, from: data)
            }
            catch{
                print("failed to convert \(error)")
            }

            guard let json = result else {
                return
            }

            print(json.data)
        })
        getfromurl.resume()

    }

}

My Structs are:
struct Response: Codable {
    let data: [MyData]
}

struct MyData: Codable{
    let date: String
    let areaName: String
    let areaCode: String
    let newCasesByPublishDate: Int
    let cumCasesByPublishDate: Int
    let newDeathsByDeathDate: Int
    let cumDeathsByDeathDate: Int
}

A: Please look closely at the JSON, the values for keys newDeathsByDeathDate and cumDeathsByDeathDate can be null.
Make the type of the corresponding struct members optional
struct MyData: Codable{
    let date: String
    let areaName: String
    let areaCode: String
    let newCasesByPublishDate: Int
    let cumCasesByPublishDate: Int?
    let newDeathsByDeathDate: Int?
    let cumDeathsByDeathDate: Int?
}

Alternatively – to keep non-optional values – decode the JSON manually and set the values to 0 if they are null

struct MyData : Decodable {
    let date, areaName, areaCode: String
    let newCasesByPublishDate, cumCasesByPublishDate : Int
    let newDeathsByDeathDate, cumDeathsByDeathDate: Int

    private enum CodingKeys : String, CodingKey { case date, areaName, areaCode, newCasesByPublishDate, cumCasesByPublishDate, newDeathsByDeathDate, cumDeathsByDeathDate }

    init(from decoder : Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        date = try container.decode(String.self, forKey: .date)
        areaName = try container.decode(String.self, forKey: .areaName)
        areaCode = try container.decode(String.self, forKey: .areaCode)
        newCasesByPublishDate = (try? container.decode(Int.self, forKey: .newCasesByPublishDate)) ?? 0
        cumCasesByPublishDate = (try? container.decode(Int.self, forKey: .cumCasesByPublishDate)) ?? 0
        newDeathsByDeathDate = (try? container.decode(Int.self, forKey: .newDeathsByDeathDate)) ?? 0
        cumDeathsByDeathDate = (try? container.decode(Int.self, forKey: .cumDeathsByDeathDate)) ?? 0
    }
}

And again, don't ignore useful error messages by printing something meaningless
Replace
print("Something Went Wrong")

with
print("An error occured:", error!)


text:
Q: How to update database entries in Spring Boot based on time? I am trying to implement a subscription-model application that upon startup checks whether the record is expired or not (based on the current date) and eventually updates the "enabled" boolean value.
The Model:
@Entity
@Table(name="users")
public class User {
    @Id
    @Column(name = "user_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Column(unique = true)
    private String name;

    @NotNull
    @DateTimeFormat(pattern = "dd/MM/yyyy")
    private LocalDate expiry_date;

    @NotNull
    private boolean enabled;

    //Constructor, getter, setters
}

Inside the UserService class I implemented the following method:
//Disable records if past expiration Date
public void updateRecordsBasedOnTime(){
    List<User> orgs = (List<User>) userRepository.findAll();
    LocalDate today = LocalDate.now();

    for (User usr: users) {
        if(today.isAfter(org.getExpiry_date())){
            org.setEnabled(false);
        }
    }
}

Now, the question is, where would be appropriate calling this method? At first I though inside the @Controller class, since an instance of the userRepository is already used, but the following method doesn't work:
@PostLoad
private void updateStatus() {
    userService.updateRecordsBasedOnTime();
}

Alternatively I though about implementing a cron method that would run though the records once every 12h:
@Scheduled(cron = "0 */12 * * *")
    public static void updateDatabase() {
}

but even if I manage to successfully implement this method, I won't have the data updated at startup. Could anyone shed some light on this and maybe provide me with a better approach?

A: I would recommend you to use triggers. With the help of triggers, you can not only execute tasks on startup but also at a periodic interval. you can read more about that and what suits your particular need.
https://docs.spring.io/spring-framework/docs/4.0.x/spring-framework-reference/html/scheduling.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Open Close Braces checking I am checking open brace and close brace. assume this is my input

{xyz{njdjd{lkdf}fj}jf}

when I compile that input open brace and close braces want to separate and stored in list for that I used following code
`List<Match> open=new List<Match>();
        List<Match> close = new List<Match>();

        MatchCollection openbrace = Regex.Matches(MELEdtior, "{");
        foreach(Match o in openbrace)
        {
            open.Add(o);
        }
        MatchCollection closebrace = Regex.Matches(MELEdtior, "}");
        foreach(Match c in closebrace)
        {
            close.Add(c);
        }

that's worked perfectly and I got two separate list with open and close brace.
Now I want compare both the list and pair the open and close brace. if any one open or close missed that pair means wants to show the error. for that I used for each loop. what I am facing means one open brace that check all close brace. but I want to check open brace with one close brace.
 if(open.Count==close.Count)
       {
        foreach(var openi in open)
        {
            foreach(var closei in close)
            {
               if( openi != closei)
               {

               }
               else { return "failed"; }
            }
        }

        }
        else{return "count failed";}

        return "";

what is wrong?

A: Single loop running both collection should solve your problem.
        if (open.Count == close.Count)
        {
            var listCount = open.Count;

            for (var i = 0; i < listCount; i++)
            {
                if (open[i] != close[i])
                {
                }
                else
                {
                    return "failed";
                }
            }
        }
        else
        {
            return "count failed";
        }
        return "passed";


text:
Q: How to take a screenshot of a Full Size window in C# I am trying to create an application in C#.net that captures the screenshot of the current active window including the area that has to be scrolled using scroll bars.I found the following code to take screenshot. To be very clear I want the code to take screenshot of the active window including the area that is not displayed and is only revealed by using scroll bars.
public class ScreenShot
{
    /// <summary>
    /// Captures the screenshot of the entire desktop
    /// </summary>
    /// <returns>Image object containing the screenshot of the desktop</returns>
    private Image CaptureDesktop()
    {
        return CaptureWindow(User32.GetDesktopWindow());
    }

    public Image CaptureAciveWindow()
    {
        return CaptureWindow(User32.GetForegroundWindow());
    }

    /// <summary>
    /// An Internal method, that captures the screenshot of any given Application window, given its Handle.
    /// </summary>
    /// <param name="handle">The handle of the window you want to Capture</param>
    /// <returns>An Image object containing the screenshot of the active application window</returns>
    private Image CaptureWindow(IntPtr handle)
    {
        // get te hDC of the target window
        IntPtr hdcSrc = User32.GetWindowDC(handle);
        // get the size
        User32.RECT windowRect = new User32.RECT();
        User32.GetWindowRect(handle, ref windowRect);
        int width = windowRect.right - windowRect.left;
        int height = windowRect.bottom - windowRect.top;
        // create a device context we can copy to
        IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
        // create a bitmap we can copy it to,
        // using GetDeviceCaps to get the width/height
        IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc, width, height);
        // select the bitmap object
        IntPtr hOld = GDI32.SelectObject(hdcDest, hBitmap);
        // bitblt over
        GDI32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, GDI32.SRCCOPY);
        // restore selection
        GDI32.SelectObject(hdcDest, hOld);
        // clean up
        GDI32.DeleteDC(hdcDest);
        User32.ReleaseDC(handle, hdcSrc);
        // get a .NET image object for it
        Image img = Image.FromHbitmap(hBitmap);
        // free up the Bitmap object
        GDI32.DeleteObject(hBitmap);

        return img;
    }

    /// <summary>
    /// Helper class containing Gdi32 API functions
    /// </summary>
    private class GDI32
    {
        public const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter

        [DllImport("gdi32.dll")]
        public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest,
            int nWidth, int nHeight, IntPtr hObjectSource,
            int nXSrc, int nYSrc, int dwRop);
        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth,
            int nHeight);
        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
        [DllImport("gdi32.dll")]
        public static extern bool DeleteDC(IntPtr hDC);
        [DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr hObject);
        [DllImport("gdi32.dll")]
        public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
    }

    /// <summary>
    /// Helper class containing User32 API functions
    /// </summary>
    private class User32
    {
        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int left;
            public int top;
            public int right;
            public int bottom;
        }

        [DllImport("user32.dll")]
        public static extern IntPtr GetDesktopWindow();
        [DllImport("user32.dll")]
        public static extern IntPtr GetWindowDC(IntPtr hWnd);
        [DllImport("user32.dll")]
        public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
        [DllImport("user32.dll")]
        public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect);
        /// <summary>
        /// Gets the Handle for current active window
        /// </summary>
        /// <returns>Active windows Handle</returns>
        [DllImport("user32.dll")]
        public static extern IntPtr GetForegroundWindow();
    }
}

A: You're making an assumption here that's not necessarily true: that there's something there already waiting in the unscrolled area.  An application can build scroll bars for a certain height or width and not actually render anything to the surface until the user actual drags the scroll bar.  The image you want to capture exists only in potential. This can be used to improve performance — think just-in-time loading, or reducing memory use.  It's a fairly common technique, and so what you're asking for doesn't really make sense.

A: Capture screen contents without using any Win32 API calls, just using .NET 2.0 at CodeProject.

A: If you're trying to get content that's offscreen, then WM_PRINT may work.  BitBlt assuredly will not.
See:

*

*MSDN description of WM_PRINT

*Window Contents Capturing using WM_PRINT Message

A: You would need to redraw the whole window/form onto a graphics object. A (simple) example of how this can be done can be found in this CodeProject article. You'd need to implement support for all controls that you need in your project. Also, if you resize the window in the example application (obscure some controls) and make a test print, you'll see that the main form, which is just another control, is drawn over the other controls, which is no real problem but doesn't look very good - you could just remove support for drawing the main form if thats an issue.
Alternatively, if using or switching to WPF, you can print controls (including the main window) by using PrintDialog.PrintVisual().


text:
Q: I can't seem to connect to my Azure Database for MySQL server from my Azure Linux VM I have a Linux Virtual Machine (Debian 9) deployed in Azure with Service Endpoints for Sql enabled and properly added -if I navigate the portal towards the VNet and enter the Service Endpoints tab, I can clearly see the Sql Service Endpoint listed. Just FYI, the reason for the Service Endpoint is that the VM has a dynamic IP, so I can't just whitelist it in the DB resource's configuration.
On the other hand, I have an 'Azure Database for MySQL server' deployed in the same resource group, same location and whatnot, but I can't seem to connect to it.
The steps I take when I try to connect are as follow:

*

*I connect to the VM through SSH.

*In my VM I have mysql-server installed

*I write mysql --host <fully qualified server name> --user <server admin login name>@<server name> -p

*I get the following error: "ERROR 9002 (28000): Server is not ready for incoming connections."

I've been reading the documentation and searching in forums for a reason why this might be happening, but I simply cannot seem to make it work. I have tried changing the status of the "Allow access to Azure services" option in the Connection security tab of the DB resource, but it doesn't seem to matter.
Could anyone have any idea of how I might go about solving this??

A: You said you enabled the SQL endpoint on the virtual network, but did you add a VNET rule to the instance (Attach an existing VNET)?  You can find this in Azure Database for MySQL server -> Connection Security -> VNET Rules -> Attach existing VNET.
If you can't see your VNET listed then there is a mismatch between the regions of your SQL server and your VNET: They must be deployed to the same one. Additionally check that you have a General Purpose or Memory Optimized server, this feature is not available in Basic tier.
If all of this is in place, try enabling Diagnostics on the SQL Server, try logging in again a few times, then view the log file and post anything strange.


text:
Q: flutter 'System UI isn't responding' crashing after installing firebase I'm getting the 'System UI isn't responding' message every time I launch my app & periodically whilst using it even though the app is working fine.
I installed firebase_core and firebase_firestore and since then i've been having these issues and I'm not sure why.
potentially related dependencies and versions:
 http: 0.12.2
 get: ^4.1.4
 get_storage: ^2.0.2
 firebase_core: ^0.7.0
 cloud_firestore: ^0.16.0

I'm getting these errors in the console (I'm also using GetX which is why there is some logging for it)
Restarted application in 1,184ms.
W/DynamiteModule(10246): Local module descriptor class for providerinstaller not found.
I/DynamiteModule(10246): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller(10246): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
W/ConnectivityManager.CallbackHandler(10246): callback not found for CALLBACK_AVAILABLE message
[GETX] Instance "GetMaterialController" has been created
[GETX] Instance "GetMaterialController" has been initialized
[GETX] Instance "AuthController" has been created
[GETX] Instance "AuthController" has been initialized
I/flutter (10246): null
[GETX] REPLACE ROUTE null
[GETX] NEW ROUTE null
F/crash_dump32(12592): crash_dump.cpp:474] failed to attach to thread 180: Permission denied

I've added these to my gradle.properties
android.useAndroidX=true
android.enableJetifier=true

I've also added v to my AndroidManifest as was suggested in another question
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

I've ensured that I've done the firebase setup correctly. The only other thing I could think of is my http version, I had to downgrade it to work with the firebase dependencies.
This is the error: https://chumberjosh-websites.s3.eu-west-2.amazonaws.com/gainzzz-error.png

A: The issue here is that the emulator I was using was running android api 30, when I changed it to 29 it worked


text:
Q: Assigning different materials to different meshes on the same object I initially had a function that created a rectangular mesh given a specific height/width:
void BoxMesh(float width, float height)
{
    MeshFilter mf = GetComponent<MeshFilter>();
    Mesh mesh = new Mesh();
    mf.mesh = mesh;

    //Verticies
    Vector3[] verticies = new Vector3[4]
    {
        new Vector3(0,0,0), new Vector3(0, height, 0), new Vector3(width, height, 0), new Vector3(width, 0, 0)
    };

    //Triangles
    int[] tri = new int[6];

    tri[0] = 0;
    tri[1] = 1;
    tri[2] = 3;

    tri[3] = 1;
    tri[4] = 2;
    tri[5] = 3;

    //normals

    Vector3[] normals = new Vector3[4];

    normals[0] = -Vector3.forward;
    normals[1] = -Vector3.forward;
    normals[2] = -Vector3.forward;
    normals[3] = -Vector3.forward;

    //UVs

    Vector2[] uv = new Vector2[4];

    uv[0] = new Vector2(0, 0);
    uv[1] = new Vector2(0, 1);
    uv[2] = new Vector2(1, 1);
    uv[3] = new Vector2(1, 0);

    //initialise
    mesh.vertices = verticies;
    mesh.triangles = tri;
    mesh.normals = normals;
    mesh.uv = uv;

    //setting up collider
    polyCollider.pathCount = 1;

    Vector2[] path = new Vector2[4]
    {
        new Vector2(0,0), new Vector2(0, height), new Vector2(width, height), new Vector2(width, 0)
    };

    polyCollider.SetPath(0, path);

}

I then decided I wanted this mesh to have an outline so I edited the function so it is now:
void BoxMesh(float width, float height, float OLwidth)
{
    MeshFilter mf = GetComponent<MeshFilter>();
    Mesh mesh = new Mesh();
    mf.mesh = mesh;

    MeshFilter mfOL = GetComponent<MeshFilter>();
    Mesh meshOL = new Mesh();
    mfOL.mesh = meshOL;

    //Verticies
    Vector3[] verticies = new Vector3[4]
    {
        new Vector3(0,0,0), new Vector3(0, height, 0), new Vector3(width, height, 0), new Vector3(width, 0, 0)
    };

    //Verticies Outline
    Vector3[] verticiesOL = new Vector3[4]
    {
        new Vector3(-OLwidth,-OLwidth,0), new Vector3(-OLwidth, height + OLwidth, 0), new Vector3(width + OLwidth, height + OLwidth, 0), new Vector3(width + OLwidth, -OLwidth, 0)
    };

    //Triangles
    int[] tri = new int[6];

    tri[0] = 0;
    tri[1] = 1;
    tri[2] = 3;

    tri[3] = 1;
    tri[4] = 2;
    tri[5] = 3;

    //normals

    Vector3[] normals = new Vector3[4];

    normals[0] = -Vector3.forward;
    normals[1] = -Vector3.forward;
    normals[2] = -Vector3.forward;
    normals[3] = -Vector3.forward;

    //UVs

    Vector2[] uv = new Vector2[4];

    uv[0] = new Vector2(0, 0);
    uv[1] = new Vector2(0, 1);
    uv[2] = new Vector2(1, 1);
    uv[3] = new Vector2(1, 0);

    //initialise
    mesh.vertices = verticies;
    mesh.triangles = tri;
    mesh.normals = normals;
    mesh.uv = uv;

    meshOL.vertices = verticiesOL;
    meshOL.triangles = tri;
    meshOL.normals = normals;
    meshOL.uv = uv;

    //setting up collider
    polyCollider.pathCount = 1;

    Vector2[] path = new Vector2[4]
    {
        new Vector3(-OLwidth,-OLwidth,0), new Vector3(-OLwidth, height + OLwidth, 0), new Vector3(width + OLwidth, height + OLwidth, 0), new Vector3(width + OLwidth, -OLwidth, 0)
    };

    polyCollider.SetPath(0, path);

}

So i now have two meshes one outside the other. However I want the one on the outside to have a different material: so it looks like an outline.

I have these two materials in my mesh renderer, so how would I go about assigning one material to the outer mesh, and another to the inner mesh.

A: The concept you might be missing here is "SubMesh", each submesh of a mesh will be rendered using a material from the list at a given index.
To create a submesh you can call
mesh.SetTriangles(int[] triangles, int submesh);

You can re-use your vertexes, by specifying different faces basing on the same list of points. If you specify more submeshes than materials, remaining submeshes will be rendered solid magenta.


text:
Q: JUnit tests with Hypersonic database Can anyone guide me to an url or resource where I can find how to write JUnit tests with a Hypersonic Database?

A: This search on JUnit and HSQLDB should give you enough links to get started. It also provides links for integrating HSQLDB for unit testing with other frameworks like Spring and Hibernate. For beginners "Using HSQLDB For Unit Testing Database Access Code" is a good read.


text:
Q: Apache2 wont start, error code New to ubunutu, installed mysql for Kodi and configured, now I am working on Owncloud and as I am working through install, Apache doesn't want to play nice. Here is journalctl -xe results:
-- Unit apache2.service has begun starting up.
Sep 01 07:50:25 Kodi-Server apachectl[16967]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. S
Sep 01 07:50:25 Kodi-Server apachectl[16967]: (98)Address already in use: AH00072: make_sock: could not bind to address [::]:80
Sep 01 07:50:25 Kodi-Server apachectl[16967]: (98)Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:80
Sep 01 07:50:25 Kodi-Server apachectl[16967]: no listening sockets available, shutting down
Sep 01 07:50:25 Kodi-Server apachectl[16967]: AH00015: Unable to open logs
Sep 01 07:50:25 Kodi-Server apachectl[16967]: Action 'start' failed.
Sep 01 07:50:25 Kodi-Server apachectl[16967]: The Apache error log may have more information.
Sep 01 07:50:25 Kodi-Server systemd[1]: apache2.service: Control process exited, code=exited status=1
Sep 01 07:50:25 Kodi-Server systemd[1]: apache2.service: Failed with result 'exit-code'.
Sep 01 07:50:25 Kodi-Server systemd[1]: Failed to start The Apache HTTP Server.
-- Subject: Unit apache2.service has failed
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- Unit apache2.service has failed.
--
-- The result is RESULT.

Here is result of lsof -i:80
COMMAND  PID     USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
nginx   7241     root    6u  IPv4 1656474      0t0  TCP *:http (LISTEN)
nginx   7241     root    7u  IPv6 1656475      0t0  TCP *:http (LISTEN)
nginx   7242 www-data    6u  IPv4 1656474      0t0  TCP *:http (LISTEN)
nginx   7242 www-data    7u  IPv6 1656475      0t0  TCP *:http (LISTEN)
nginx   7243 www-data    6u  IPv4 1656474      0t0  TCP *:http (LISTEN)
nginx   7243 www-data    7u  IPv6 1656475      0t0  TCP *:http (LISTEN)
nginx   7244 www-data    6u  IPv4 1656474      0t0  TCP *:http (LISTEN)
nginx   7244 www-data    7u  IPv6 1656475      0t0  TCP *:http (LISTEN)
nginx   7245 www-data    6u  IPv4 1656474      0t0  TCP *:http (LISTEN)
nginx   7245 www-data    7u  IPv6 1656475      0t0  TCP *:http (LISTEN)

Thank you for your help.


text:
Q: Adding Minutes to Date is not changing the Date C# .NET double TotalMinute=300.0
double TotalMinutesAdded=1378.0

double TotalMinute=300.0
double TotalMinutesAdded=1378.0

foreach(DataRow dr in ds.Tables[0].Rows)
                {

                    //Add The above Timings to each Row's 2nd Column
                    DateTime correctDate=Convert.ToDateTime(dr[2]);

                    correctDate.AddMinutes(TotalMinute);
                    correctDate.AddMinutes(TotalMinutesAdded);

                    dr[2]=correctDate;

                }

A: DateTime is immutable; functions like AddMinutes return a new DateTime; so you need to catch the returned value:
DateTime foo = ...
DateTime bar = foo.AddMinutes(5);

A: As mentioned, due to DateTime objects being immutable you have to reassign the variable.
However, a point to note is that you can chain the manipulations as so:
correctDate = correctDate.AddMinutes(TotalMinute)
                         .AddMinutes(TotalMinutesAdded);

A: DateTiem Add* functions are not supposed to change current DateTime value. They RETURN the new Value.
If you want your value changed, type like this:
correctDate = correctDate.AddMinutes(TotalMinute);

A: You have to set the correctDate variable to instance returned from the AddMinutes call:
correctDate = correctDate.AddMinutes(TotalMinute);

A: DateTime is an immutable type, much like String is. You would write date = date.AddDays(1) like you would write str = str.Replace("hello", "").

A: AddMinutes() does not change the value of the original DateTime. It returns a new DateTime with the new value that you have to assign to a variable.

A: The problem lies with
correctDate.AddMinutes(TotalMinute);
correctDate.AddMinutes(TotalMinutesAdded);

it should be
correctDate = correctDate.AddMinutes(TotalMinute);
correctDate = correctDate.AddMinutes(TotalMinutesAdded);

The AddMinutes method returns the result, not adding the minutes to correctDate

A: ...and to add say 5 minutes to the current time to a datetime variable:
dim dateFive_Minute_Time as datetime

dateFive_Minute_Time = Now.AddMinutes(5)


text:
Q: How to stop setEmptyView displaying a TextView while populating a ListView with Android? In my MainActivty i'm displaying a list of items, from a Firebase database using a FirebaseListAdapter like this:
firebaseListAdapter = new FirebaseListAdapter<String>(MainActivity.this, String.class, R.layout.list, ref) {
@Override
protected void populateView(final View v, final String listName, int position) {
       ((TextView )v.findViewById(R.id.list_name)).setText(listName);
    }
};
listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(firebaseListAdapter);

TextView emptyView = (TextView) findViewById(R.id.empty_view);
listView.setEmptyView(emptyView);

The problem is, when the activity starts, the emptyView is displayed even if i have data in my adapter. This is happening for a short time, while the ListView is populated and than disappears. How can i stop this from happening? As you you can see, i have set listView.setEmptyView(emptyView); after i have set the firebaseListAdapter but no luck. This is how my .xml file looks like:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
    android:id="@+id/empty_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="gone"/>

    <ListView
    android:id="@+id/list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</android.support.design.widget.CoordinatorLayout>

Thanks in advance!

A: If your adapter has this method, you can set empty view in this method,
adapter.registerDataSetObserver(new DataSetObserver() {

            @Override
            public void onChanged() {
                super.onChanged();

              TextView emptyView = (TextView) findViewById(R.id.empty_view);
               listView.setEmptyView(emptyView);

            }
        });


text:
Q: Mandrill API Templating I'm using Mandrill's Ruby API Gem and have the follow simple template for testing:

testastic

Following the example on Heroku's guide I have the follow Ruby code:
require 'mandrill'
  m = Mandrill::API.new
  rendered = m.templates.render 'test-template', [{:header => 'some header text', :main_section => 'The main content block', :footer => '
asdf
'}]

  mail(:to => "Jayson Lane <jayson@domain.com>", :subject => "Test Email") do |format|
       format.html { rendered['html'] }
       #format.text { render "test" }
  end

This works great and the email sends my template just fine, however, it doesn't replace the template mc:edit variables. Am I missing something?

A: You need to construct a hash for each element you're trying to replace. For instance, I have this inside of a template:

And this on the mailer:
mandrill.messages.send_template(template,[
    {
     :name => 'plan_info_name',
     :content => extra[:membership_info].name
    },
    {
     :name => 'plan_info_description',
     :content => extra[:membership_info].long_description
    },
    {
     :name => 'plan_info_benefits',
     :content => benefits_list
    }
  ....


text:
Q: Ошибка при компиляции проекта в Android Studio Устанавливаю библиотеки ApacheHttp в build.gradle, нигде ничего не подчеркивает, но при компиляции выдаёт ошибку.
Код в build.gradle :

Сама ошибка :

Как можно исправить ошибку?

A: Конфликт в последних 2 строчках. Удалите и замените на
android{
    ...
    useLibrary  'org.apache.http.legacy'
}

P.S. А лучше используйте HttpURLConnection.

A: Помню сперва то же намучился с этим. Потом подключил библиотеку вот так
dependencies {
    //compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.google.android.gms:play-services:8.4.0'
    compile 'org.apache.httpcomponents:httpcore:4.4.1'
    compile 'org.apache.httpcomponents:httpclient:4.5'
    compile files('libs/json-20090211.jar')
}

в итоге работает.


text:
Q: Parallel memcpy in cpp I am trying to copy a matrix in parallel.  Below is the code that I am working with.  Currently, it works as expected with char, but it seg faults when I use shorts.  I assume that the bug is in copying outside of the memory outside of the vector.  I have tried to debug my assumption without success.
CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
project(memcpy CXX)
find_package (Threads)
add_executable(memcpy main.cpp)
set_property(TARGET memcpy PROPERTY CXX_STANDARD 17)
target_link_libraries (memcpy ${CMAKE_THREAD_LIBS_INIT})

main.cpp
#include <cassert>
#include <condition_variable>
#include <cstring>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

class Barrier {
  public:
    explicit Barrier(std::size_t const count) : m_threshold(count), m_remaining(count), m_generation(0) {}

    void wait() {
        auto local = std::unique_lock<std::mutex>{m_mutex};
        auto current_generation = m_generation;

        m_remaining--;
        if (!m_remaining) {
            m_generation++;
            m_remaining = m_threshold;
            m_condition.notify_all();
        } else {
            m_condition.wait(local, [this, current_generation] { return current_generation != m_generation; });
        }
    }

  private:
    std::mutex m_mutex;
    std::condition_variable m_condition;
    std::size_t m_threshold;
    std::size_t m_remaining;
    std::size_t m_generation;
};

template <typename T>
class Matrix {
    using reference = typename std::vector<T>::reference;
    using const_reference = typename std::vector<T>::const_reference;

  public:
    Matrix(std::size_t rows, std::size_t cols) : m_rows(rows), m_cols(cols), m_data(m_cols * m_rows) {}
    Matrix(std::size_t rows, std::size_t cols, T const& default_val) : m_rows(rows), m_cols(cols), m_data(m_cols * m_rows, default_val) {}

    constexpr std::size_t get_columns() const { return m_cols; }
    constexpr std::size_t get_rows() const { return m_rows; }
    constexpr std::size_t get_element_count() const {
        assert(m_cols * m_rows == m_data.size());
        return m_cols * m_rows;
    }

    T* data() { return m_data.data(); }
    T const* data() const { return m_data.data(); }

    reference operator()(std::size_t const column_x, std::size_t const row_y) {
        assert(0 <= column_x);
        assert(column_x < get_columns());
        assert(0 <= row_y);
        assert(row_y < get_rows());

        return m_data[row_y * m_cols + column_x];
    }

    const_reference operator()(std::size_t const column_x, std::size_t const row_y) const {
        assert(0 <= column_x);
        assert(column_x < get_columns());
        assert(0 <= row_y);
        assert(row_y < get_rows());

        return m_data[row_y * m_cols + column_x];
    }

  private:
    std::size_t const m_rows;
    std::size_t const m_cols;
    std::vector<T> m_data;
};

static_assert(false, "FIX ME");
using T = char;
// using T = short;
// using T = int;
// using T = double;

void run(std::size_t const my_rank, std::size_t const num_threads, Barrier& barrier, Matrix<T> const& from_data, Matrix<T>& to_data) {
    auto n = from_data.get_element_count();
    std::string str;

    if (my_rank == 0) {
        std::cerr << "bytes to copy: " << (n * sizeof(T)) << '\n';
    }

    // initialization
    std::size_t segment_size = n / num_threads;
    std::size_t start = (my_rank * segment_size) * sizeof(T);
    std::size_t end = ((my_rank + 1) * segment_size) * sizeof(T);
    std::size_t distance = end - start;

    str += "  my_rank: " + std::to_string(my_rank);
    str += "  segment_size: " + std::to_string(segment_size);
    str += "  start: " + std::to_string(start);
    str += "  end: " + std::to_string(end);
    str += "  distance: " + std::to_string(distance);
    str += "  rank: " + std::to_string(my_rank);
    str += "  start: " + std::to_string(start);
    str += "  end: " + std::to_string(end);
    str += "  distance: " + std::to_string(distance);
    str += "  e: " + std::to_string(start + distance);
    str += "\n";
    std::cerr << str;

    barrier.wait();
    std::memcpy(to_data.data() + start, from_data.data() + start, distance);
    barrier.wait();

    if (my_rank == 0)
        for (auto y = 0; y < from_data.get_rows(); y++) {
            for (auto x = 0; x < from_data.get_columns(); x++) {
                if (to_data(x, y) != from_data(x, y)) {
                    std::cerr << "x: " << x << '\t' << "y: " << y << "\t\t";
                    std::cerr << "to: " << to_data(x, y) << '\t' << "from: " << from_data(x, y) << '\n';
                }
            }
        }

    barrier.wait();
}

int main() {
    auto const num_threads = 1;
    // auto const num_threads = 4;

    // auto const width = 64;
    // auto const height = 64;
    auto const width = 97;
    auto const height = 101;

    auto from_data = Matrix<T>(width, height, 70);
    auto to_data = Matrix<T>(width, height, 84);

    std::vector<std::thread> threads;
    auto barrier = Barrier{num_threads};
    for (auto i = 0; i < num_threads; i++) {
        threads.emplace_back(run, i, num_threads, std::ref(barrier), std::ref(from_data), std::ref(to_data));
    }

    for (auto& thread : threads) {
        thread.join();
    }
}

A:
std::memcpy(to_data.data() + start, from_data.data() + start, distance)

std::vector<T>::data() returns a T* so if you add an integral value foo to it, you effectively add foo * sizeof T bytes ... but you allready multiplied with sizeof(T) earlier when calculating start and end. Also, std::memcpy() won't work for Ts that are not PODs.
Better use std::copy().


text:
Q: how to change width of columns and data below columns based on witdth of column in flutter DataTable? I use DataTable to show columns and rows. When i map columns i also use split on column and place them in columnName and columnWidth based the index. This way i can determine the width based on the data in columns. But the problem is that it only changes the width of column header and not the data below the column. This is because i place the DataTable inside ListView so it is horizontally scrollable. My question is how can i say for example pass the width of Title column and also change the width of DataCell: Title1, Title2 and Title3? I also need the ListView and scrollable in my usecase.
This is the full code :
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class AppView6 extends StatefulWidget {
  const AppView6({Key? key}) : super(key: key);

  @override
  State<AppView6> createState() => _AppView6State();
}

class _AppView6State extends State<AppView6> {
  var columns = ["title|50", "date|90", "description|100"];
  var rows = [
    ["Title1", "01-01-2022", "Lorem ipsum dolar set amit"],
    ["Title2", "02-01-2022", "Lorem ipsum dolar set amit"],
    ["Title3", "03-01-2022", "Lorem ipsum dolar set amit"],
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        scrollDirection: Axis.horizontal,
        children: [
          DataTable(
            columns: columns.map<DataColumn>((column) {
              var columnData = column.split("|");
              var columnName = columnData[0];
              var columnWidth = columnData[1];
              return DataColumn(
                  label: SizedBox(
                width: double.parse(columnWidth),
                child: Text(
                  columnName,
                ),
              ));
            }).toList(),
            rows: rows.map<DataRow>((rows) {
              return DataRow(
                  cells: rows.map<DataCell>((row) {
                return DataCell(
                  SizedBox(
                    child: Text(
                      row,
                    ),
                  ),
                );
              }).toList());
            }).toList(),
          ),
        ],
      ),
    );
  }
}


text:
Q: how do I make a text disappear and make different text appear by hovering over another text How do I make a text disappear and make different text appear by hovering over another text.

#a:hover + #b {
  display: none;
}
#c {
  display: none;
}

Hover here

This will disappear

This will appear

A: So I guess this is what you are looking for:

#a:hover + #b {
  display: none;
}
#a:hover ~ #c {
  display: block;
}
#c {
  display: none;
}

Hover here

This will disappear

This will appear

Explanation:
As you are already using the adjacent sibling selector (+) that selects the sibling element that immediately follows.
Using the general sibling selector (~) you can select from all the succeeding sibling elements.
Let me know your feedback on this. Thanks!

A:

var a = document.getElementById('a'),
 b = document.getElementById('b'),
 c = document.getElementById('c');

a.onmouseenter = function(){
 b.style.display = 'none';
  c.style.display = 'inherit';
}

a.onmouseleave = function(){
 b.style.display = 'inherit';
  c.style.display = 'none';
}
#c {
    display: none;
}

Hover here

This will disappear

This will appear

This is how you do it using javascript. Hope it helps you.


text:
Q: How to change category in wordpress url? For example, I have
http://mysite.com/category/sport?post_type=question =

to
http://mysite.com/sport/question

A: Change the Permalink form admin panel.
By default permalink is default you have to select POST NAME and Click on SAVE buuton...
Add the following code to your .htaccess file
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Ensure that mod_rewrite module is enabled.


text:
Q: Asymptotic notation (big Theta) I'm currently in the process of analyzing runtimes for some given code (Karatsuba-ofman algorithm).
I'm wondering if I'm correct in saying that $\Theta(\left\lceil n/2\right\rceil) + \Theta(n)$ is equal to $\Theta(n)$? (Taking the maximum of both costs)
I know that $\Theta(n/2) +\Theta(n)$ is equal to $\Theta(n)$. But my concern with the first asymptotic runtime is that given $n = 0.6, \left\lceil n/2\right\rceil$ would be equal to $1$, which is greater than $0.6$.
If $\Theta(\left\lceil n/2\right\rceil) + \Theta(n) \stackrel{?}{=} \Theta(n)$ could anybody please give some insight on why this is true?

A: Yes you are right.. intuitively it's clear that it does not change a thing, since when $n \to \infty$ effects like this are definitely too small to notice.
The whole concept behind asymptotics is that we ignore small terms.. sometimes we can even  ignore something "huge" like $2^n$, for example $\Theta(2^n + 3^n) = \Theta(3^n)$
So we don't really care about effect like this; yes if $n=0.6$ you would get $1$, but the error is at most $1/2$ which is not relevant. if you had $n = 10^9 + 0.6$, would you be worried about wether the result is rounded up or down?

If you want to be a little bit more formal you can start noting that $\lfloor \frac n2 \rfloor \le n$, and $\Theta(n) + \Theta(n) = \Theta(n)$
Or you can also notice that the error from rounding is at most $1/2$ or $1$, depends on the rounding that one uses and find some bonds from there.

A: Remember that
$f(n)
=\Theta (g(n))
$
means that
there are positive constants
$a$ and $b$ such that
$a g(n) < f(n) < b g(n)
$
for all large enough $n$.
Therefore,
if
$f(n)
=\Theta (h(n))
$
and
$g(n)
=\Theta (h(n))
$
then
$f(n)+g(n)
=\Theta(h(n))
$.

A: If you consider the problem for the natural numbers it is true that $\Theta(\lceil n/2 \rceil) = \Theta (n)$. As $   \lceil n/2 \rceil \le n \le 2 \lceil n/2 \rceil$. And as a consequence also $\Theta(\lceil n/2 \rceil) + \Theta (n)= \Theta (n)$.
However, if you consider it for the positive real numbers (as $n \to 0$) as your example $0.6$ might suggest then it is not true that $\Theta(\lceil n/2 \rceil) = \Theta (n)$ and neither is $\Theta(\lceil n/2 \rceil) + \Theta (n)= \Theta (n)$.
In this  case $n = O (\lceil n/2 \rceil)$ as $n \le 2 \lceil n/2 \rceil$ still holds.
Yet as $\lceil n/2 \rceil = 1$ for all $0< n \le 2$ we get that $\lceil n/2 \rceil$ is not $O(n)$ as $n \to 0$.


text:
Q: Quadtree for collision detection implementaion I'm trying to create a quad tree for my 3D environment (all elements are on a flat terrain, so they can be represented with 2D data), but I'm a little lost on the implementation of the finer parts of it.
I will first begin by describing my current quad tree, than move on to its flaws, and than ask the questions.
What I currently have is a quad tree that takes in a very specific rectangle in which I define the x,z,width, and forward. Here is an overview of my operations.
Insert an object into the quadtree:
Check if the current node has any child. If it does, check if the object is able to completely fit into any of the four nodes. If Possible, recurse and repeat. If the object does not completely fit into the four nodes or there are no nodes at all, it will add it to a std vector, than check if it should split. If it splits, split it and split the current objects into their respective nodes.
Delete an object from the quadtree:
Check if the object is inside the current node. Than move onto children. If found, pop the object out of the vector.
Update the quadtree:
Moving and static objects are stored in different quad trees. Moving quad tree will always delete whatever has moved and reinsert. Static quad tree just chills.
Retrieving an object
First find which of the four nodes it belongs to, than move recursively, taking all of the node's current objects and adding it to a vector that is returned at the end.
So here are my flaws: Not all of my rects are located in the leaf. I have no idea what I should do with those that intersect between the nodes. This also makes collision detection checking kinda stupid in a quad tree; why do I need to put rects inside parent nodes? I am thoroughly unhappy about the Retrieve object function.
My second flaw is that I can only take a rect in. While this was useful in making the quad tree and debugging it, I would like to move on and be able to directly put my Objects in my game inside.
So here are my questions
I've read Quadtree for 2D collision detection. Everything seems good enough, until "Objects can belong to several collections inside the quadtree. You're going to need an extra linear collection outside the quadtree to enumerate every object without duplicates."
I have no idea what that means, or how to do that. The operations for collision detection also seems much better than what I currently have. I want to know what he means and how its done.
My second question is regarding the insertion of objects into the tree. All my objects in the game would be part of a base class. Should I just make them add the base class directly? Or should I cast the objects into rects and than add a pointer to the object? I am loading some models for my game as well, and they are stretched around and played with by glScalef(). Thus it seems really hard (but possible) to get the scaling of and the position of the models after scaling.
On a side note, the main reason I am scaling the models is because I am basically making walls for a maze game. So I need them to fit perfectly around, and I can't mathematics on maya.

A: How do you use quad tree for 3d? Maybe you mean 2d? Because usually octree is used for 3d.
About you first question. Your objects may belong to several quads in quadtree. When you retrieve objects you need to check collision with you just check if you already detected collision between two objects and if you did you dont do the detection again to bypass duplicates. For example you have 2 objects in one quad. You check collision between 1st and second and then between 2nd and 1st. You need to check that you already detected this collision before.
Try reading this link for details.

A: You can try a morton curve to find overlapping area I also think you need an octree:http://dmytry.com/texts/collision_detection_using_z_order_curve_aka_Morton_order.html. Here are example of overlapping objects:https://books.google.fr/books?id=1mu099DN9UwC&pg=PA29&lpg=PA22&ots=pzvPDLu5qi&focus=viewport&dq=hilbert+curve+overlapping+objects&hl=de&output=html_text


text:
Q: Implementing Adams-Bashforth of order 2 (AB2) algoirthm Assuming we are given the initial condition for an ODE such that:
$$ \begin{cases} x' = f(x,t) \\ x(t_0) = x_0 \end{cases} $$
We are  going to solve it numerically using AB2.
We know  that the first iteration of AB2 produces $x_{2}$ using $x_{1}$ and $x_0$.
So it need two nodes to start. but  we have only one node given in initial condition. I never paid attention to this until I myself wanted to code the  AB2 algorithm.
What should I do to find $x_{1}$?

A: As you say, you could use a forward method like Euler or RK2 to compute the next solution and then continue with AB2.
Another option is to compute a backward step; As you know the derivative at any point, you could evaluate it at $x_0$ to approximate the value of $x$ at the previous time, using backward difference approximation of derivative:
$$\frac{x_0 - x_{-1}}{h} = x'(t_0, x_0) \rightarrow x_{-1} = x_0 - h \ x'(t_0, x_0) $$
where $h$ is the time step.

A: Ok I think I found the answer by myself. In situations like this we can use another method that only need one node, to approximate the second node $x_1$.
So one should take the initial condition $x_0$ and then use a numerical method (for example forward Euler) to approximate  the next node $x_1$ then uses these two nodes to boot up the AB2 iterations.


text:
Q: An error occurred (AccessDenied) when calling the ListObjects operation: Access Denied while trying access with another user I am getting above error while trying to access s3 through another user, Below is bucket policy
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::xxxxbucket/*"
        },
        {
            "Sid": "AllowAll",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::1111111111:user/xxx_user"
            },
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::xxxxbucket",
                "arn:aws:s3:::xxxxbucket/*"
            ]
        }
    ]
}

Command Used:
aws s3 ls s3://xxxxbucket
Can somebody please help with this issue

A: Is there any chance that you have the Requester pays option enabled on the bucket?  I've blown a whole day on a matter like this.  Even if I opened the bucket up completely, allowing any access, it seems that Requester pays attribute was blocking access.
It makes sense, of course, though I don't fully understand the underlying implementation.

A: That policy looks like it should work - have you considered testing it using the IAM Policy Simulator at https://policysim.aws.amazon.com/
It should allow you to test your policy and user and confirm that it's setup correctly (or if not, give you more information about why access is being denied - it may be due to another policy you have somewhere in your account).


text:
Q: Nvidia driver for Macbook Pro 9,1 I am current using the default nouveau driver on my Macbook Pro 9,1. I tried installing nvidia-current, then Ubuntu just went blank after restart.
Is there any safe way to install nvidia proprietary driver?

A: I was able to install nvidia driver from the nvidia page. Just grab the driver in .run file and install it.
The command is like this:
sudo stop service lightdm
chmod +x NVIDIA-Linux-x86_64-331.49.run
sudo ./NVIDIA-Linux-x86_64-331.49.run

However I found that I could switch off the nvidia and run intel card instead. The intel card is much better than nvidia considering I'm using my MBP mostly for work and study but not gaming. Following is how I did that:
sudo vi /etc/grub.d/10_linux

+ Add following:
   echo "    outb 0x728 1" | sed "s/^/$submenu_indentation/"
   echo "    outb 0x710 2" | sed "s/^/$submenu_indentation/"
   echo "    outb 0x740 2" | sed "s/^/$submenu_indentation/"
   echo "    outb 0x750 0" | sed "s/^/$submenu_indentation/"
after these lines:
   if [ x$type != xrecovery ] ; then
        echo "    gfxmode \$linux_gfx_mode" | sed "s/^/$submenu_indentation/"
   fi

   echo "    insmod gzio" | sed "s/^/$submenu_indentation/"

+ Rebuild grub:
grub-mkconfig > /boot/grub/grub.cfg

+ Open Grub Customizer, add following options:
i915.lvds_channel_mode=2 i915.modeset=1 i915.lvds_use_ssc=0

+ Reboot and enjoy low power and low heat

+ To confirm Nvidia is off:
sudo cat /sys/kernel/debug/vgaswitcheroo/switch

+ Download mbp_power.c and compile it:
sudo gcc -O2 -o /usr/local/bin/mbp_power mbp_power.c

+ Make it run right after resuming from sleep
vim /etc/pm/sleep.d/10_disable_nvidia.sh

case "${1}" in
    hibernate|suspend)
        # this is called when going to hibernate or to sleep
            ;;
    resume|thaw)
        # this is called when waking up
        /usr/local/bin/mbp_power
            ;;
esac

+ Make sure every thing is executable
chmod +x /usr/local/bin/mbp_power
chmod +x /etc/pm/sleep.d/10_disable_nvidia.sh

mbp_power.c:
// compile:
// sudo gcc -O2 -o /usr/local/bin/mbp_power mbp_power.c

#include <stdio.h>
#include <sys/io.h>

#define PORT_SWITCH_DISPLAY 0x710
#define PORT_SWITCH_SELECT 0x728
#define PORT_SWITCH_DDC 0x740
#define PORT_DISCRETE_POWER 0x750

static int gmux_switch_to_igd()
{
    outb(1, PORT_SWITCH_SELECT);
    outb(2, PORT_SWITCH_DISPLAY);
    outb(2, PORT_SWITCH_DDC);
    return 0;
}

static void mbp_gpu_power(int state)
{
    outb(state, PORT_DISCRETE_POWER);
}

static void mb_gpu_print()
{
    printf("SELECT:  %hhu\n", inb(PORT_SWITCH_SELECT));
    printf("DISPLAY: %hhu\n", inb(PORT_SWITCH_DISPLAY));
    printf("DDC:     %hhu\n", inb(PORT_SWITCH_DDC));
    printf("POWER:   %hhu\n", inb(PORT_DISCRETE_POWER));
}

int main(int argc, char **argv)
{
    if (iopl(3) < 0) {
        perror ("No IO permissions");
        return 1;
    }
    int state=0;
    if (argc > 1) state = atoi(argv[1]);
    printf("Before:\n");
    mb_gpu_print();
    mbp_gpu_power(state);
    gmux_switch_to_igd();
    printf("After:\n");
    mb_gpu_print();
    return 0;
}

Proof in the following pic:


text:
Q: to select all the employees who have joined most recently under king emp table
empno ename    sal    deptno mgr      job       comm  hiredate

7369  SMITH   800.0000  20  7902      CLERK           1980-12-17 00:00:00.000
7499  ALLEN1  600.0000  30  7698      SALESMAN  300   1981-02-20 00:00:00.000
7521  WARD    1250.0000 30  7698      SALESMAN  500   1981-02-22 00:00:00.000
7566  JONES   2975.0000 20  7839      MANAGER         1981-04-02 00:00:00.000
7654  MARTIN  1250.0000 30  7839      SALESMAN  1400  1981-09-28 00:00:00.000
7698  BLAKE   2850.0000 30  7839      MANAGER         1981-05-01 00:00:00.000
7782  CLARK   2450.0000 10  7839      MANAGER         1981-06-09 00:00:00.000
7788  SCOTT   3000.0000 20  7566      ANALYST         1987-04-19 00:00:00.000
7839  KING    5000.0000 10            PRESIDENT       1981-11-17 00:00:00.000
7844  TURNER  1500.0000 30  7698      SALESMAN  0     1981-09-08 00:00:00.000
7876  ADAMS   1100.0000 20  7788      CLERK           1987-05-23 00:00:00.000
7900  JAMES   950.0000  30  7698      CLERK           1981-12-03 00:00:00.000
7902  FORD    3000.0000 20  7566      ANALYST         1981-12-03 00:00:00.000
7934  MILLER  1300.0000 10  7782      CLERK           1982-01-23 00:00:00.000

Here is what I have so far:
select e.*,datediff(dd,e.hiredate,getdate()) min_exp
from emp e
join emp e1 on e.mgr=e1.empno1
where e1.empname='king'
  and datediff(dd,e.hiredate,getdate()) =
      (
          select min(datediff(dd,e.hiredate,getdate())) from emp
      )

A: So if you just need a list of employees that were hired after King was hired, just use King's hire date as the filter.
select e.*,datediff(dd,e.hiredate,getdate()) min_exp
from emp e
where e.hiredate > (SELECT hiredate FROM emp WHERE ename = 'king')

Test the statement and make adjustments where needed.  I didn't verify it.

A: select top(1) from (
    select * from emp
    where empname='king' order by hiredate desc
) t;


text:
Q: How to reload the fragment with new dimensions when the screen orientation changes I have a fragment, in which a TextView takes it's width from folders:
values and values-port.
and these values change when there is an orientation change, but the fragment's UI doesn't have any effect.
In fact it actually picks values from values-port and:
if the device is in landscape mode: onConfigurationChanged() with new orientation as landscape is called.
if the device is in portrait mode: onConfigurationChanged() is not called.
and when ever I change the orientation, then onConfigurationChanged() is definitely called.
So,
Why does it always starts with portrait mode?
What to do to have the effect of dimensions change of the UI elements.
I tried something like this in the fragment:
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    getView().requestLayout();
}

But doesn't work.
My TextView is always with the width from values-port folder.
EDIT : might seem redundant, but this is the code:
<activity
    android:name=".FeedActivity"
    android:configChanges="orientation|screenSize|keyboardHidden"
    android:screenOrientation="portrait" >
</activity>

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}

I know I could have removed android:screenOrientation="portrait" from the manifest instead of setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); in the Activity, but want to know the behavior with this code.

A: FeedActivity has a fixed orientation, specified in your manifest by the attribute android:screenOrientation. Therefore it will do nothing when you rotate your device. Even if it would, you're overriding the android:configChanges. Here's what the docs say:

Lists configuration changes that the activity will handle itself. When a configuration change occurs at runtime, the activity is shut down and restarted by default, but declaring a configuration with this attribute will prevent the activity from being restarted. Instead, the activity remains running and its onConfigurationChanged() method is called.

Your manifest tells the system that FeedActivity will handle orientation, screenSize and keyboard configuration changes itself. Alas, you don't really do that.
Since you say you're loading your Fragment in XML, I'll assume it looks something like this:
<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

    <fragment android:layout_width="@dimen/frag_width"
              android:layout_height="match_parent"
              android:tag="your_tag_here"
              class="path.to.your.Fragment"/>

</FrameLayout>

To get the behaviour you're expecting, you should update the manifest with
<activity
    android:name=".FeedActivity"
    android:configChanges="screenSize|keyboardHidden"/>

UPDATE
If you insist on changing your Fragment width with onConfigurationChanged method, this could work:
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    final View view = getView();
    if (null != view) {
        view.getLayoutParams().width = getResources().getDimensionPixelSize(R.dimen.width);
    }
}

I would advise against this approach though.

A: You can simply just put the fragments with different code for landscape in 'layout-land' folder.
When the screen orientation changes to landscape all the layout and fragments will be called from this folder.
So you can copy your fragment, do necessary changes for landscape mode and put it in 'layout-land' folder.
This should do the trick.


text:
Q: Google Cloud SQL import size bigger than original DB I'm confronting a strange situation here with Google Cloud SQL.
I'm migrating a 15.7Gb mysql database to Google cloud. I've followed the migration process exactly as the doc says. And everything worked perfectly. Absolutely no issue during the process, my application works just fine. The only problem here is that the size used by the DB shown on Google Cloud is much bigger that the original DB. Right now I have a 39Gb sql database, from a 15.7Gb database.
After some research and testing I've come to the conclusion that it's the way that Google count the data on their side.
I just wanted to know if somebody have any idea, or can confirm what I'm saying.
Thank you for your answers.

A: Thanks to @Vadim.
The huge database size was due to the binary logs option that was enabled by default on Google Cloud SQL.
I've pruned them by disabling and re-enabling the binary logs option. The database got from 39Gb to 24Gb.


text:
Q: Determine the critical points and identify them as asymptotically stable or unstable? Drawing phase lines? Here's the question:
Determine the critical (equilibrium) points, and classify each one as
asymptotically stable or unstable. Draw the phase line, and sketch
several graphs of solutions in the $ty$-plane
$$dy/dt = 1 − e^y,\; −∞ < y_0 < ∞.$$
This section of the textbook is all about population growth and is supposed to be in the form $dy/dt=r(1-y/k)y$, so I don't understand how to find the critical pts. in this case. Do I have to actually solve the DE to graph the solutions? Is the phase line just the $y$-axis?

A: The only equilibrium point of $$dy/dt = 1 −    e^y,\; −∞ < y_0 < ∞.$$ is at  $dy/dt =0.$
Thus  equilibrium happens at $$ e^y =1 $$ that is  $y=0$
This equilibrium is asymptotically stable because  $y>0 \implies  dy/dx <0$ and  $ y<0 \implies dy/dx>0.$
Therefore the solutions approach the equilibrium solution $y=0$ asymptotically.


text:
Q: MYSQL condense group by two columns into group by one column with breakdown I am trying to condense an order by 2 columns query, into an order by 1 column query with a breakdown column. If this has a proper name I would greatly appreciate knowing what it is!
Example:
ocean
name     | type    | colour
fishy    | salmon  | red
splishy  | salmon  | red
splashy  | salmon  | pink
sploshy  | salmon  | pink
floaty   | whale   | blue
humprhey | whale   | grey
wilson   | whale   | grey

Looking for (I'm not sure what doing this is called):
type  | count | colour breakdown
salmon| 4     | 2 red, 2 pink
whale | 3     | 1 blue, 2 grey

Preferentially with minimal use of string functions.

Not sure how to proceed from:
(Order by one column)
SELECT o.type, count(*)
FROM ocean o
GROUP BY `type`

type  | count
salmon| 4
whale | 3

(Order by two columns)
SELECT o.type, o.colour, count(*)
FROM ocean o
GROUP BY `type`, `colour`

type  | colour     | count
salmon| red        | 2
salmon| pink       | 2
whale | blue       | 1
whale | grey       | 2

A: Ugly, untested, but may just do what you want:
SELECT type, SUM(color_count),
   GROUP_CONCAT(CONCAT(color_count, ' ', colour) SEPARATOR ', ') AS colour_breakdown
FROM (
    SELECT type, colour, COUNT(colour) AS colour_count
    FROM ocean
    GROUP BY type, colour
) AS subt
GROUP BY type

A: Using your second query as a data source, you can use group_concat() to get the output you want:
select type, sum(`count`), group_concat(colBreak separator ',') as color_breakdown
from
    (
        SELECT
            o.type,
            o.colour,
            count(o.type) as `count`,
            concat(o.colour, ' ', count(o.type)) as colBreak
        FROM ocean o
        GROUP BY `type`, `colour`
    ) as a
group by type;


text:
Q: Animating react-native-svg dash length of a  Hey everyone I'm trying to achieve effect similar to: https://kimmobrunfeldt.github.io/progressbar.js
(circle one)
I was able to successfully animate some svg elements before using setNativeProps approach, but it is failing for me this time with dash length, below is a gif demonstrating current behaviour (circle is change from full to semi full when it receives new props):

Essentially I am trying to animate this change instead of it just flicking in, below is full source for this rectangular progress bar, basic idea is that is uses Circle and strokeDasharray in order to show circular progress, it receives currentExp and nextExp as values for characters experience in order to calculate percentage left before they reach next lvl.
Component uses pretty standard set of elements, besides few dimension / animation and colour props from stylesheed and styled-components library for styling.
NOTE: project is importing this library from expo.io but it's essentially react-native-svg
import React, { Component } from "react";
import PropTypes from "prop-types";
import styled from "styled-components/native";
import { Animated } from "react-native";
import { Svg } from "expo";
import { colour, dimension, animation } from "../Styles";

const { Circle, Defs, LinearGradient, Stop } = Svg;

const SSvg = styled(Svg)`
  transform: rotate(90deg);
  margin-left: ${dimension.ExperienceCircleMarginLeft};
  margin-top: ${dimension.ExperienceCircleMarginTop};
`;

class ExperienceCircle extends Component {
  // -- prop validation ----------------------------------------------------- //
  static propTypes = {
    nextExp: PropTypes.number.isRequired,
    currentExp: PropTypes.number.isRequired
  };

  // -- state --------------------------------------------------------------- //
  state = {
    percentage: new Animated.Value(0)
  };

  // -- methods ------------------------------------------------------------- //
  componentDidMount() {
    this.state.percentage.addListener(percentage => {
      const circumference = dimension.ExperienceCircleRadius * 2 * Math.PI;
      const dashLength = percentage.value * circumference;
      this.circle.setNativeProps({
        strokeDasharray: [dashLength, circumference]
      });
    });
    this._onAnimateExp(this.props.nextExp, this.props.currentExp);
  }

  componentWillReceiveProps({ nextExp, currentExp }) {
    this._onAnimateExp(currentExp, nextExp);
  }

  _onAnimateExp = (currentExp, nextExp) => {
    const percentage = currentExp / nextExp;
    Animated.timing(this.state.percentage, {
      toValue: percentage,
      duration: animation.duration.long,
      easing: animation.easeOut
    }).start();
  };

  // -- render -------------------------------------------------------------- //
  render() {
    const { ...props } = this.props;
    // const circumference = dimension.ExperienceCircleRadius * 2 * Math.PI;
    // const dashLength = this.state.percentage * circumference;
    return (
      <SSvg
        width={dimension.ExperienceCircleWidthHeight}
        height={dimension.ExperienceCircleWidthHeight}
        {...props}
      >
        <Defs>
          <LinearGradient
            id="ExperienceCircle-gradient"
            x1="0"
            y1="0"
            x2="0"
            y2={dimension.ExperienceCircleWidthHeight * 2}
          >
            <Stop
              offset="0"
              stopColor={`rgb(${colour.lightGreen})`}
              stopOpacity="1"
            />
            <Stop
              offset="0.5"
              stopColor={`rgb(${colour.green})`}
              stopOpacity="1"
            />
          </LinearGradient>
        </Defs>
        <Circle
          ref={x => (this.circle = x)}
          cx={dimension.ExperienceCircleWidthHeight / 2}
          cy={dimension.ExperienceCircleWidthHeight / 2}
          r={dimension.ExperienceCircleRadius}
          stroke="url(#ExperienceCircle-gradient)"
          strokeWidth={dimension.ExperienceCircleThickness}
          fill="transparent"
          strokeDasharray={[0, 0]}
          strokeLinecap="round"
        />
      </SSvg>
    );
  }
}

export default ExperienceCircle;

UPDATE: Extended discussion and more examples (similar approach working for different elements) available via issue posted to react-native-svg repo: https://github.com/react-native-community/react-native-svg/issues/451

A: It is actually quite simple when you know how SVG inputs work, one of the problems with react-native-SVG (or SVG inputs, in general, is that it doesn't work with angle), so when you want to work on a circle you need to transform angle to the inputs which it takes, this can be done, by simply writing a function such as (you necessarily don't need to memorize or totally understand how transformation works, this is the standard):

function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
        var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;

        return {
            x: centerX + (radius * Math.cos(angleInRadians)),
            y: centerY + (radius * Math.sin(angleInRadians))
        };
    }

Then you add another function which can give you the d props in the right format:
function describeArc(x, y, radius, startAngle, endAngle){

        var start = polarToCartesian(x, y, radius, endAngle);
        var end = polarToCartesian(x, y, radius, startAngle);

        var largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";

        var d = [
            "M", start.x, start.y,
            "A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
        ].join(" ");

        return d;
    }

Now it is great, you have the function (describeArc) which gives you the perfect  parameter you need to describe your path (an arc of a circle):
so you can define the PATH as:
<AnimatedPath d={_d} stroke="red" strokeWidth={5} fill="none"/>

for example, if you need an arc of a circle of radius R between 45 degrees to 90 degrees, simply define _d as:
_d = describeArc(R, R, R, 45, 90);

now that we know everything about how SVG PATH works, we can implement react native animation, and define an animated state such as progress:
import React, {Component} from 'react';
import {View, Animated, Easing} from 'react-native';
import Svg, {Circle, Path} from 'react-native-svg';

AnimatedPath = Animated.createAnimatedComponent(Path);

class App extends Component {
    constructor() {
        super();
        this.state = {
            progress: new Animated.Value(0),
        }
    }
componentDidMount(){
        Animated.timing(this.state.progress,{
            toValue:1,
            duration:1000,

        }).start()
}

    render() {
        function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
            var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;

            return {
                x: centerX + (radius * Math.cos(angleInRadians)),
                y: centerY + (radius * Math.sin(angleInRadians))
            };
        }

        function describeArc(x, y, radius, startAngle, endAngle){

            var start = polarToCartesian(x, y, radius, endAngle);
            var end = polarToCartesian(x, y, radius, startAngle);

            var largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";

            var d = [
                "M", start.x, start.y,
                "A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
            ].join(" ");

            return d;
        }

        let R = 160;
        let dRange = [];
        let iRange = [];
        let steps = 359;
        for (var i = 0; i<steps; i++){
            dRange.push(describeArc(160, 160, 160, 0, i));
            iRange.push(i/(steps-1));
        }

        var _d = this.state.progress.interpolate({
            inputRange: iRange,
            outputRange: dRange
        })

        return (
            <Svg style={{flex: 1}}>
                <Circle
                    cx={R}
                    cy={R}
                    r={R}
                    stroke="green"
                    strokeWidth="2.5"
                    fill="green"
                />
                {/*       X0  Y0               X1   Y1*/}
                <AnimatedPath d={_d}
                      stroke="red" strokeWidth={5} fill="none"/>

            </Svg>
        );
    }
    }

    export default App;

This simple component will work as you want

*

*At the top of the componet, we write,

AnimatedPath = Animated.createAnimatedComponent(Path);
  because Path which is imported from react-native-svg is not native react-native component and we turn it to animated by this.

*

*at constructor we defined progress as the animated state which should change during animation.

*at componentDidMount the animation process is started.

*at the beginning of render method, the two functions needed to define SVG d parameters are declared (polarToCartesian and describeArc).

*then react-native interpolate is used on this.state.progress to interpolate the change in this.state.progress from 0 to 1, into change in d parameter. However, there are two points here that you should bear in mind:
   1- the change between two arcs with different lengths is not linear, so linear interpolation from angle 0 to 360 does not work as you would like, as a result, it is better to define the animation in different steps of n degrees (i used 1 degrees, u can increase or decrease it if needed.).
   2- arc cannot continue up to 360 degrees (because it is equivalent to 0), so it is better to finish animation at a degree close to but not equal to 360 (such as 359.9)

*at the end of the return section, the UI is described.

A: If you aren't tied to the svg library, I think you could checkout this library: https://github.com/bgryszko/react-native-circular-progress, it might be a much simpler way to achieve what your looking for.

A: Another absolute great library for animating svg's is https://maxwellito.github.io/vivus/
This is standalone without dependencies and easy to use.
Maybe this fits your needs?


text:
Q: xsession error - libvdpau_nvidia.so. But no nvidia card The .xsession-errors file in my home directory has this error many times:
Failed to open VDPAU backend libvdpau_nvidia.so: cannot open shared object file: No such file or directory
But I do not have a nvidia card (I have only an ATI/Radeon card.)
I looked around and I have only 1 package installed with nvidia in the name:
   nvidia-common
I tried to remove the package but it is tied to the desktop..   :(
The following packages have unmet dependencies:
 ubuntustudio-desktop : Depends: nvidia-common but it is not going to be installed.
The following actions will resolve these dependencies:
 Remove the following packages:

1)     ubuntustudio-desktop
 Leave the following dependencies unresolved:

2)     jockey-common recommends nvidia-common (>= 1:0.2.36)
History/background:
Yesterday, I wiped my disk and re-installed Ubuntu Studio from scratch.
So, I was looking through the errors to get some sort of a baseline.
(Maybe I shouldn't do that..)
What can I do to remove the error?
Or should I just ignore it.
Thanks in advance.
Jay E.
PS
 Many Thanks to all the people that put the fglrx package together so I
can crunch data with Catalyst for BOINC !!

A: You should track down which application is reporting that error and turn of hardware acceleration in that app.
My guess is that it is your flash player, because I had this error too. So test it out:
First run in a terminal:
tail -f ~/.xsession-errors

This will open .xsession-erros in a "live" mode, showing everything what is newly written to it. Then launch a browser and open a flash video (e.g. youtube, but not in HTM5 mode). If then the error message pops up in your terminal then flash is causing your problem. So just right click on the video -> select Settings... and uncheck Enable hardware acceleration. If it wasn't flash, then try opening other graphical apps which you use regularly and watch if the error pops up in your terminal, then turn off hardware acceleration in that app.


text:
Q: Interpretation hierarchical regression I'm running hierarchical regression to determine whether or not a number of independent variables are able to explain a dependent variable. I have following models:

*

*Model 1: only controlvariables

*Model 2: Model 1 + independent variables

*Model 3: Model 2 + interaction term

When interpreting the significance of the different terms, should I only consider the last model or should I consider the model where I entered the terms. For instance, to investigate which controlvariables are significantly significant to the dependent variable, should I look at Model 1, and then, for the independent variables, consider Model 2? Or should I just look at the last model for the significance of the different terms?

A: Interpretation of hierarchical regression

*

*Model Summary Box:
Read 3rd column named 'R square' for all your models and interpret like this.
Check the R Square in the Model Summary box. Variables entered in
Block 1 (control variable) explained X (depends on your output) % of the variance in DV.
After Block 2 variables (IDV's) has been included , the model as a whole explained Y (depends on your output) % of variance in DV.
Adding Block 3 variable (interaction term), the model as a whole explained Z (depends on your output) % of variance in DV.

*Now look at change statistics
The column labelled R Square Change shows how much change in R square (explained variation) as compare to previous model. For example, for model 1, it is same as X, for model 2, it is same as (Y - X) and so on.
To infer if this change is statistically significant or not, you need to look at the last column (Sig. F Change)

*The ANOVA table:
It indicates that the models as a whole are significant or not.
Hope it helps!


text:
Q: Internet Explorer 7 Bugs - incorrect display OR dead links I recently launched a website I have been developing over the past year - http://Live.heritageartpapers.com/. My dad, who owns the company, had a phone call today saying it doesnt display properly in IE7.
Bug #1: The header and footer are both in a div, whereas the content is in a table between the two divs. Reportedly the content (table) sometimes (not always, according to IETester) displays below the footer, but the footer still displays where it is supposed to (ie there is a massive gap where the content should fit).
Bug #2: When the content does display in the correct place, all the links on the page are dead - click on them and nothing happens. As you can see if you view it in Firefox (the version I am using is 3.6), the links in the left hand menu turn orange on mouseover. However they do not even do this in IE7. Note that they do turn orange and do work if the content is displayed below the footer.
I cant see why its happening - according to IETester, the IE7 interpreted source code has all the tags capitalised and many quotes removed (for example for the id attribute on most, if not all, tags) but I doubt this could cause the above bugs, could it?
My question is whether anyone has ever seen any of these problems before, and/or has a solution to any of these problems??
I currently do not have the application open, but will post any relevant code in a few minutes. Alternatively just use view source.
Many thanks in advance.
Regards,
Richard Clarke

A: Well having spent quite a while on this tonight, I decided to take a look in the IE specific stylesheet, on the basis that the problem was specific to IE.
I remember a while back, when trying to get mouse over image enlargements working, I found that the image enlargements were appearing only down to the next row (on the catalogue page - have a look on the site and you will be able to see what I mean). At the time I had a div layout, as I worked for a council a year ago and they taught me to use divs instead of tables wherever possible, and to avoid tables for layout on the basis that some customers may have browsers which dont support tables.. I found that the fix (to make the image enlargements appear fully over all the rows) was to set the z-index of each row to -1. Since this was only an IE issue, I put it in the IE stylesheet.
So anyway I removed the z-index: -1 from the stylesheet and BAM all the links in the entire page started working!!
As far as I know this only happens in IE7 but not IE8. I am not sure about any other IEs or Firefox.
Hope this helps anyone who has the same problem.
Regards,
Richard


text:
Q: Microsoft graph API request on behalf of Application My organization has implemented authorization using Oauth on our APIs utilizing Azure AD B2C. We have different applications registered and have given them app roles that we ensure are on the JWT for authorization, as well as other claims we use for validation.
My question is it best practice to then use our own graph API credentials to handle changes on the backend of our API, or should we be using theirs?
For example, an application wants to edit a user in B2C. They call us with their JWT scoped to our backend API. We validate it and update the user. Should the update be performed using our own graph API credentials, or should we be performing some form of token exchange to obtain a graph token tied to their credentials somehow?

A: Azure AD B2C doesn't support on-the-behalf-of flow yet for API's. This being said, there is value of this design with complex resource API delegation models. This requirement generally is something that evolves from mature services due to acquisitions or just increasing data points from multiple sources but requires scale architecture.
For simple services that don't have 100's/1,000's of resource API's, then a simpler design (not requiring token exchange) makes sense.
Using something like Azure API Manager is ideally to put in front of your application. This gives you the typical control that an APIM provides. Other things it provides are:

*

*DNS control for API endpoints that are not service dependent

*Ability to do fallback logic by controlling endpoints and automation

*A/B testing and release controlled by DNS

*Requires no application dev change to update endpoints

Depending on industry, you may require/need OBO - for having the authorization Web API (API-1) not obtain user data in the original token - and data is in the 2nd token (API-2)i.e. resource API. Mostly it's a design requirement on how the API resources requires. I'd recommend looking at the OAuth token exchange protocol to see what makes sense for you. It's important to understand OBO does not align with the token exchange protocol.


text:
Q: How to check browser support for HTML5 form attributes? How can I check if a browser supports the formtarget or the form attribute?
Modernizr is no help here and I couldn't even find something on the web on the current state of form support in browsers. Although a quick test revealed all current browsers except IE 9 do support them.
So how can I check if a browser handles the form* attributes?

A: Here you go:
if("formtarget" in document.createElement("input")){
    //good job, browser
}else{
    //nope
}

A: The form attribute on input is a special case. It was used before the HTML5 feature, to reference the parent form, but now it's used as an attribute as well, so you will have false positives on IE.
There is a checking function but it involves interaction with DOM which will probably affect performance, but here you go anyway. Hope it helps.
function testInputFormSupport() {
    var input = document.createElement('input'),
         form = document.createElement('form'),
         formId = 'test-input-form-reference-support';
    // Id of the remote form
    form.id = formId;
    // Add form and input to DOM
    document.body.appendChild(form);
    document.body.appendChild(input);
    // Add reference of form to input
    input.setAttribute('form', formId);
    // Check if reference exists
    var res = !(input.form == null);
    // Remove elements
    document.body.removeChild(form);
    document.body.removeChild(input);
    return res;
}

A: Have a look at this site.
It covers all the new form features and gives a handy little function to test the support of an attribute
// Function to test for attribute support
function elSupportsAttr(el, attr) {
  return attr in document.createElement(el);
}

A: Try
if ("attribute" in document.createElement("tag"))

from How can I tell of a HTML attribute exists or not, using Javascript


text:
Q: What's the meaning of the sentence "or so he would have us believe"?
He wrote: 'Pytheas tells us that Thule is one day's sail from the congealed sea... and this Pytheas saw with his own eyes - or so he would have us believe.

Mainly the mood or the conjunction bewildered me.

A: I love AMERICAN English!
"-/, or so he/she/they would have us/you believe." implies that the precedent may be being presented a falsehood, lie, or misrepresentation.
In your example, it implies that Pytheas may be bearing false witness and was in fact, not an eyewitness to the event(s).
Example: "Monsanto is a lovely corporation that makes safe products, or so they would have you believe." implies Monsanto is (or may be) in fact, not a lovely corporation AND/OR does not make safe products. This could indicate direct mirepresentation by Monsanto, or by third parties ('they') such as new outlets or attorneys.


text:
Q: CallContext is carrying foreward the previous data which was set I have this condition where I see that the thread's CallContext is carrying foreward the data in consequent calls.
Consider I have a simple API which when queired, will set one data entry into CallContext using :
// entry to the API execution within OnStartProcessingRequest method of DataService
if(CallContext.LogicalGetData("data") != null)
    CallContext.LogicalSetData("data", someValue)
print("data " + CallContext.LogicalGetData("data"))

When I see the logs after some API queries, I see similar logs.
| thread | log |
| 237 | data 23 |
| 145 | data 19 |
| 872 | data 78 |
| 237 | data 23 |
My concern is why did thread with ID 237 pick up old data? i.e. 23
I'm sure the control didn't go inside the LogicalSetData block of code as it already had data.
I'm not sure why this is happening? Can anyone help me with this?
The service is a WCF dataservice. Call is being made from postman REST client.

A: Consider switching to OperationContext as it is built-in and natural context for storing data for a specific request.CallContext.GetData will get the data that was set via SetData from the same thread. Data stored via CallContext.LogicalSetData is considered to be "logical thread" local. That is, any data that is stored via CallContext.LogicalSetData will be "flowed" to any child threads. If you call CallContext.LogicalGetData in the same thread or any child threads, you will get the data that was stored by that thread's (or the parent thread's) call to CallContext.LogicalSetData. Better description in this great article. I was unable to find any information that CallContext must be clean on each request start, however I found this old article, describing custom ICallContextInitializer implementation. It says:

WCF by default is more frugal than other stacks, such as ASP.NET, when
  it comes to protecting state. Saving and restoring lots of
  thread-local settings takes time regardless of whether you actually
  did something with those settings or not. WCF tries not to do as much
  on your behalf so that you don't have to pay for cleanup unless you're
  using those features. It does however give you the hooks necessary to
  arrange for this cleanup to take place at the appropriate time.


text:
Q: asp.net regex mixture of letters and numbers I want to have a mixture of letters and numbers for product code in my ASP.Net project. It should have a mixture of 4 uppercase letters and 3 numbers for example,
A1B2C3D, ABCD123, A123BCD.
I did this but its not working
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
         ControlToValidate="ProductCode" ErrorMessage="Must be 7 characters in length and a mixture of 4 uppercase characters and 3 numerals " ForeColor="Red"
         ValidationExpression="/^(?=(?:[^A-Z]*[A-Z]){4}[^A-Z]*$)(?=(?:\D*\d){3}\D*$)[A-Z\d]{7}$/"></asp:RegularExpressionValidator>

So how can I get it?
Thanks in advance.

A: Remove the delimiters /:
ValidationExpression="^(?=(?:[^A-Z]*[A-Z]){4}[^A-Z]*$)(?=(?:\D*\d){3}\D*$)[A-Z\d]{7}$">

The example in documentation of RegularExpressionValidator.ValidationExpression Property doesn't have /, so it is wrong to include them in your regex.
You may want to change \d and \D to [0-9] and [^0-9]. If the content is validated on the server side, it probably will go through Regex class, where \d and \D by default works on Unicode characters.


text:
Q: Calling Firebase auth UI from an R Shiny app Calling Firebase auth UI from an R Shiny app
I am trying to call in firebase auth UI from within my Shiny app. The aim is a basic authorization flow in Shiny with Firebase.
Following is the folder structure
├──  ui.R
├──  server.R
├──  global.R
├──  www
    ├──  fire-auth-sign-in.js
    ├──  firebase-console-config.js
    ├──  firebase-ui-auth.css
    ├──  firebase-ui-auth.js //Firebase's own authentication js file
├──  ui
    ├── successfulRegistration
    ├── sign-in.R

global.R
library(shiny)
library(shinyjs)
library(DT)

server.R
function(input, output, session) {
  ##### App for signed in user
  signed_in_user_df <- reactive({
    req(session$userData$current_user())
    out <- session$userData$current_user()
    out <- unlist(out)
    data.frame(
      name = names(out),
      value = unname(out)
    )
  })
  output$user_out <- DT::renderDT({
    datatable(
      signed_in_user_df(),
      rownames = FALSE,
      options = list(
        dom = "tp",
        scrollX = TRUE
      )
    )
  })
}

ui.R
fluidPage(
  shiny::singleton(
    shiny::tags$head(

      tags$script(src="https://www.gstatic.com/firebasejs/7.5.2/firebase-app.js"),
      tags$script(src="https://www.gstatic.com/firebasejs/7.5.2/firebase-auth.js"),

      shiny::tags$script(src="firebase-ui-auth.js"),
      shiny::tags$link(rel = "stylesheet", href="firebase-ui-auth.css"),

      shiny::tags$script(src="fire-auth-sign-in.js"), # UI loader
      shiny::tags$script(src="firebase-console-config.js") #Firebase app configuration copied from firebase console

    )
  ),

  tags$script("firebase.initializeApp(firebaseConfig);"),

  source("ui/sign-in.R", local = TRUE)$value,

  source("ui/successfulRegistration.R", local = TRUE)$value
)

fire-auth-sign-in.js
// Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());

var uiConfig = {
  callbacks: {
    signInSuccessWithAuthResult: function(authResult, redirectUrl) {
      // User successfully signed in.
      return true;
    },
    uiShown: function() {
      document.getElementById('loader').style.display = 'none';
    }
  },
  signInSuccessUrl: 'github.com',
  signInOptions: [
    firebase.auth.EmailAuthProvider.PROVIDER_ID,
    firebase.auth.PhoneAuthProvider.PROVIDER_ID
  ],
  // Terms of service url.
};

// Finally, render the FirebaseUI Auth interface:
ui.start('#firebaseui-auth-container', uiConfig);

Between ui.R and my fire-auth-sign-in.js, I am not able to create a proper connect as the UI won't load to begin with. Can you tell me what could I do to make this work?


text:
Q: JQuery animate to "Height: 0px;" is still showing I have recently tried to implement my drop-down menu to work upon clicking on my button to animate from "Height: 0px;" to "Height: 260px;", however, upon loading of the document, the div is visible even though overflow is set to be hidden and the height is set as 0px.
$('.DropBtn a').click(function() {
    if ($(this).attr("href") == "#Open") {
        $(this).attr("href", "#Close");
        $('#Font-Size .DropList').stop().animate({
            height: "260px",
        }, 400);
    } else if ($(this).attr("href") == "#Close") {
        $(this).attr("href", "#Open");
        $('#Font-Size .DropList').stop().animate({
            height: "0px",
        }, 400);
    }
});

Above is the recent addition to my script and you can view it live on JSFiddle here.
Thank you for any help provided for a solution to my problems,
Best Regards,
Tim

A: Setting the height to 0 does not hide the element. It still has margin and padding which cause it to be displayed. Try this: http://jsfiddle.net/anw4B/1/
else if ($(this).attr("href") == "#Close") {
        $(this).attr("href", "#Open");
        $('#Font-Size .DropList').stop().animate({
            height: "0px",
        }, 400, function() {$('#Font-Size .DropList').hide()});
    }

I believe this is better than changing the margin and the padding because it allows you to regularly use the CSS. Also note, that there are two more changes in the fiddle (showing the list before expanding it and hiding it by default in the CSS).

A: It is visible because of the padding and the border properties.
Updated fiddle
In this fiddle I animate the padding along with the height and have a callback function after the animation is over to remove the border property. I do this just for the sake of demonstrating to you where the problem is, if I were you, I'd rather have a callback function that hides the element at the end of the animation, and shows it before the animations runs.
Edited fiddle
// This is how the line to show the list would look like.
// Note the .show() before .animate().
$('#Font-Size .DropList').stop().show().animate({
    height: "260px",
}, 400);

// That's for hiding. Note the callback function that hides
// the element at the end of the animation
$('#Font-Size .DropList').stop().animate({
     height: "0px",
}, 400,
function () { $(this).hide() });

Technically this will make the element disappear when it reaches height: 0 but it has still 3px of padding and 2px of border; but in my opinion this is unnoticeable. Try it yourself.


text:
Q: Safest way to ground a metal enclosure I am currently building a nixie clock with some high frequency components (GPS) and I am planning on putting the clock in a metal enclosure.  The highest voltage used in the clock is approximately 510V (referenced to CLOCK GROUND).  There are three different grounding configurations of the metal enclosure I am contemplating.  I want to discuss the safety considerations of each and ultimately determine which is the safest / best practice option (or if the correct / safest option is something else and not one I have listed below!).  I was unable to find a post which discussed the safety considerations of all of these options.
Below are a list of the 3 grounding options I am considering with accompanying schematic representations for each option.  Each schematic has the connection in question highlighted in yellow.
EDITED: Images updated to explicitly show EARTH connection for clarity.
Option 1: Connect the metal enclosure to the CLOCK GROUND

Since I will have some SMA connectors mounted to the metal enclosure, if I do not insulate these connectors from the metal enclosure of the clock, they will connect the metal enclosure to CLOCK GROUND.  This option will allow the CLOCK TRANSFORMER to act as an isolation transformer and also will prevent large voltage differences from building up between the metal enclosure and the internal electronics of the clock.  However, I am concerned that this does not follow the common practice of connecting the metal enclosure of mains powered equipment to EARTH.
Pros:

*

*CLOCK TRANSFORMER acts as an isolation transformer.

*Prevents large voltage differences from building up between the metal enclosure and the internal electronics of the clock.

Cons:

*

*Does not follow the common practice of connecting the metal enclosure of mains powered equipment to EARTH.  The metal enclosure may build up a large potential difference with respect to EARTH, leading to a shock if someone touches the metal enclosure.

Option 2: Connect the metal enclosure to EARTH

If I choose this option, I would insulate the SMA connectors (which are CLOCK GROUND) from the metal enclosure of the clock.  This seems to be following the common practice of connecting the metal enclosure of mains powered equipment to EARTH.  However, should I be concerned that the internal electronics of the clock may build up large potential differences with respect to the case?
Pros:

*

*Follows the common practice of connecting the metal enclosure of mains powered equipment to EARTH.

*CLOCK TRANSFORMER acts as an isolation transformer.

Cons:

*

*Large voltage differences may build up between the metal enclosure and the internal electronics of the clock.

Option 3: Connect the metal enclosure to both EARTH and CLOCK GROUND

This option prevents the internals electronics of the clock from building up large voltages with respect to the case and, at the same time, follows the common practice of connecting the metal enclosure of mains powered equipment to EARTH.  However, this option eliminates the safety of the CLOCK TRANSFORMER acting as an isolation transformer.
Pros:

*

*Follows the common practice of connecting the metal enclosure of mains powered equipment to EARTH.

*Eliminates the possibility of large voltage differences building up between the enclosure and the internal electronics of the clock.

Cons:

*

*CLOCK TRANSFORMER is no longer acting as an isolation transformer.  Touching an internal electrical node in the clock (such as CLOCK VDD) could result in a serious electrical shock.

It appears that each option poses some advantages, but still has some safety flaws.  I suppose working with mains power is inherently dangerous, however, is there one option that stands out as significantly safer than the other two?

A: From a safety standpoint the enclosure should be connected to earth, not to the neutral leg of the power supply.  You should have a three prong plug with the enclosure connected to the ground pin.  Now anybody touching the enclosure is safe assuming the wall plug is properly grounded.  Even if it isn't you need another fault to make the enclosure dangerous.  You don't get to count on the neutral wire being at earth ground.

A: You can power this with a 9V  and a boost regulator, both from the same low voltage low VA transformer over a wide range. All you need is a 12Vdc wall supply input with DC and a ground ESD wire to bleed off any charge on a metallised, plastic case or metal case.
There is no need for a big 1:1 transformer.
You do not need over 500V, only 190 Vdc for std Nixie tubes

The case can be double insulated or earth bonded with AC input or DC input with an ESD ground wire with 1 Mohm R and small ceramic C to shunt RF noise. The Resistor will bleed off static charge in a double insulated case that can be spray coated on a plastic box with static dissipative paint.  But if you prefer a metal box , 3 wire earth bonding is must with fusing on power.

A: Option 4: bond the enclosure to earth, and connect it to the clock ground with a high impedance, maybe 1 megohm.
This prevents large voltages building up between the internal circuit and the enclosure, and at the same time limits the damage that can be done by an electric shock from the internal circuit.