text:
Q: How to add and remove a relation in a many_to_many association? So, as per the example in the Ecto docs, I have the following:
defmodule Post do
  use Ecto.Schema
  schema "posts" do
    many_to_many :tags, Tag, join_through: "posts_tags"
  end
end

and
defmodule Tag do
  use Ecto.Schema
  schema "tags" do
    many_to_many :posts, Post, join_through: "posts_tags"
  end
end

Now what are the different ways to:
a) Associate an existing post with an existing tag.
b) Disassociate an existing post from a tag.
Note I do not wish to create a nested resource, but rather the situation is I have a %Post{} and a tag_id, and I wish to either create or destroy an association between them.

A: There are two ways I can think of which do not require loading all tags for the post:

*

*Create a module for the join table, e.g. PostTag and then associate/disassociate by creating/deleting a PostTag row:
# web/models/post_tag.ex
defmodule PostTag do
  use Ecto.Schema

  @primary_key false
  schema "posts_tags" do
    belongs_to :post, Post
    belongs_to :tag, Tag
  end
end

# Create association
Repo.insert!(%PostTag(post_id: 1, tag_id: 2))

# Remove association
Repo.get_by(PostTag, post_id: 1, tag_id: 2) |> Repo.delete!

*Use Repo.insert_all/2 and Repo.delete_all/2 directly on the posts_tags table:
# Create assoication
Repo.insert_all "posts_tags", [%{post_id: 1, tag_id: 2}]

# Delete association
Repo.delete_all "posts_tags", [%{post_id: 1, tag_id: 2}]


text:
Q: Where is the "App Bundle" looking for my media folder? Folder found when running app from Qt Creator, "file not found" when using Terminal I'm having a little trouble making my app bundle work from the terminal or just double clicking it.
This App actually compiles, links and runs perfectly within the Qt Creator IDE. But, if I try to open it from the terminal I get a "media/file.x file not found" error. The App bundle nor the /Contents/MacOS/executable is finding the "media" folder that is supposed to be beside the executable.
In my app I do something like:
openFile("media/file.x");

In Windows and Linux, this file WILL be found if the "media" folder is exactly in the same hierarchical position of the executable (beside it). On the Mac I have discovered it works differently cause Qt Creator builds an "App Bundle" and the actual executable is inside the /Contents/MacOS folder, so I copied the "media" manually there. This worked without any hassle when "playing" my app from the Qt Creator but as mentioned before it doesn't work when running the bundle itself.
So does anyone know where or how can I homogenize the look for this "media" folder so it works on both: Qt Creator and the App bundle?
Lately, I have been using the following command to "install" the folder on the bundle.
mac {
    MediaFiles.files = media
    MediaFiles.path = Contents/MacOS
    QMAKE_BUNDLE_DATA += MediaFiles
}

Thanks for your help.

A: After looking for a few days I found a couple of posts discussing the relative path problem. I was just not searching with the right words... The answer is displayed in:
Relative Paths Not Working in Xcode C++
http://www.experimentgarden.com/2009/06/how-to-load-resource-from-your.html
Basically it is necessary to add this:
//On the include part
#ifdef __APPLE__
#include "CoreFoundation/CoreFoundation.h"
#endif

// On the main of your app
// This makes relative paths work in C++ in Xcode by changing directory to the Resources         folder inside the .app bundle
#ifdef __APPLE__
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
    char path[PATH_MAX];
    if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX))
    {
        // error!
    }
    CFRelease(resourcesURL);

    chdir(path);
    std::cout << "Current Path: " << path << std::endl;
#endif
// ----------------------------------------------------------------------------

IMPORTANT:
The chdir, changes the working path of the app, so it is not necessary to change you relative code after that...

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to verify user only with uid and access_token (facebook) The problem is how to verify user only with uid and accessToken.
graph.facebook.com/100000726976284?access_token=xxxxxx
For example, is there any simple way to check if user 100000726976284's access token is xxxxxx.
I guess the 'verified' filed is the key.
Only when I put correct xxxxxx(which is of that user), I could see verified=true in the response.

A: graph.facebook.com/me will get you info on whichever current user matches the access token (or an error if the token is invalid)

A: Paste your access token here:  https://developers.facebook.com/tools/debug
it will tell you all the permissions granted for that particular token as well as other meta data.


text:
Q: Using JavaScript to change CSS style based on page width I'm working on an assignment for a class where I have to make an external JavaScript file that checks a page's current width and changes the linked CSS style based on it, and have that occur whenever the page loads or is resized. Normally, we are given an example to base our assignment off of, but that was not the case this time around.
Essentially we are to use an if...then statement to change the style. I have no clue what the appropriate statements would be for the function. I've looked around and the potential solutions are either too advanced for the class or don't go over what I need. As far as I know I cannot use jQuery or CSS queries.
If someone could give me an example of how I would write this out, I would be very appreciative.

A: Try this code
html is

javascript is
var resize = document.getElementById('resize');
window.onresize=function(){
    if(window.innerWidth <= 500) {
        resize.style = "background:blue; height: 100px; width: 100px;";
    }
    else {
        resize.style = "background:red; height: 100px; width: 100px;";
    }
};

i have create a sample for you look at here TESTRESIZE
try resizing your browser and let me know if it is what you are looking for.

A: //Use This//
function adjustStyle() {
var width = 0;
// get the width.. more cross-browser issues
if (window.innerHeight) {
    width = window.innerWidth;
} else if (document.documentElement && document.documentElement.clientHeight) {
    width = document.documentElement.clientWidth;
} else if (document.body) {
    width = document.body.clientWidth;
}
// now we should have it
if (width < 799) {
    document.getElementById("CSS").setAttribute("href",     "http://carrasquilla.faculty.asu.edu/GIT237/smallStyle.css");
} else {
    document.getElementById("CSS").setAttribute("href", "http://carrasquilla.faculty.asu.edu/GIT237/largeStyle.css");
}
}

// now call it when the window is resized.
window.onresize = function () {
adjustStyle();
};
window.onload = function () {
adjustStyle();
};

A: Use CSS and media queries. It's bad idea to change style by js.


text:
Q: Delphi IDE - CodeRush visual "connectors" alternative I used to work in Delphi 6, and got very used to having CodeRush's various helpful IDE additions.  Many are now in the IDE itself, or I've managed to replace with something else, but the one feature I REGULARLY find myself wishing I had in Delphi 2007 still, is the ability CodeRush had that added little "connecting lines" between components that were linked to each other (lines showing the connections between TDataSets and TDataSources, for instance).
Does anyone make something that does that in the newer Delphi IDE?
=== * LATER NOTE / Clarification * ===
Andreas is correct in his comments below... "I don't think that he meant structural highlighting which works on the source code. He wants "connection lines" between components in the form designer."
He also says "as far as I know there is no such tool for Delphi 2005 or newer".. which is a bummer if true.  (...and if that IS the case, what's the best place to make Delphi IDE feature requests?)

A: I don't think it exists. The best place to make form designer feature requests is here.

A: another freeware/opensource option would be to look at CNPack which supports structural highlighting and runs well in Delphi 2009.  The library contains many other enhancements to the IDE also, some which are duplicated in other packages such as GExperts.  I run both CNPack and GExperts in both 2009 and 2006 without any problems.

A: You want Castalia, which works fine here on my D2007 for structural highlighting.
Castalia from Twodesk


text:
Q: WinRAR Context menu and file type detection of Windows So far I know Windows display context menu based on the file extension rather than the file type. I just tested with empty text file with mp3 extension with winamp and the result is below:

The same way I test empty file with extension exe and Windows gives me context menu like "Run as Administrator" and so.

But if I create a sfx archive which has the same exe extension, how Windows gives me different icon and WinRAR gives me special context menu like "Extract here" as shown in the below picture?

My question is either Windows readers file header and represents relevant data or WinRAR has any special file detection scheme? I doubt that second one, since during the context menu creation WinRAR didn't invoked.
Another question is if it's because of Windows's behavior to read headers (like it creating thumbnail for pictures or videos), now extension has less importance? Don't they have any influence in context menu?

A: Windows context menu handlers can be both static as well as dynamic. If you're interested in delving into it further, I advise you to read the Shortcut (Context) Menus and Shortcut Menu Handlers article, especially Choosing a Static or Dynamic Shortcut Menu Method and Customizing a Shortcut Menu Using Dynamic Verbs.
Quoting from this Visual Basic Shell Programming book excerpt:

Dynamic Context Menus
Static context menus are limited because they are the same for every
file object of a given type. Also, the number of files that can be
processed through a static menu is limited by the program that is used
to carry out the command. What if you need to process 20 files? What
if you need different processing options based on the state of the
file itself? There are also situations where you might need one
context menu for a group of files and another for a single file. This
is where dynamic context menus come into play.
...
You might want different menu items displayed based on whether one or
multiple files have been selected. Since the number of files selected
can be determined in IShellExtInit::Initialize, this becomes a trivial
matter. You also have the ability to base the menu item on the file
itself. In addition to the number of files selected, you would also
already know the filenames in question. This means you could open
the file, retrieve information, and base the menu item on actual
data. Or you could examine some other attribute of the file (such as
its creation date, its size, or its read-only status) and base the
menu item on that information as well.

Finally, if you want proof that the file is actually being read by WinRAR's shell extension DLL (since you seem to doubt it), here are the various ReadFile calls registered by Process Monitor on simply right-clicking a WinRAR SFX:

(The process name is displayed as explorer.exe and not rarext.dll, because the context menu handler is an "in-process" COM object that the shell loads directly into explorer.exe's memory space for execution.)
As you can see, it reads the first 7 bytes to confirm that it's an EXE:

After reading more data (no doubt to obtain and parse the header), it then reads 7 bytes from offset 101,376 to confirm that it's a WinRAR SFX and not just any old EXE:

This prompts it to add various context menu entries such as Open with WinRAR, Extract with WinRAR and so on, which don't get added for "normal" EXEs.
Furthermore, in WinRAR's Settings dialog there's an option titled Where to check for SFX archives:

Here's what the help file has to say about it:

"Where to check for SFX archives" options control processing of SFX
archives in context menus. Checking contents of executable file and
detecting if it is a self-extracting (SFX) archive introduces some
delay when right clicking every ".exe" file, because WinRAR needs to
read and analyze file data to find out if it is SFX. While such delay
is negligible for fast local hard drives, it can be noticeable in case
of slow network disks. This group of options allows to enable or
disable SFX processing for local hard disks, network disks and other
disks like CD-ROM and USB separately. If you turn these options off,
you will not see all SFX related context menu items when right
clicking SFX archive. So disable these options only if you really
experience delays when right clicking ".exe" files.

Hope that puts your doubts to rest. :) As for your second question about whether extensions have "less importance" now and lack "any influence in context menu[s]", I don't understand what you mean. Even image/video thumbnails are generated by shell extension handlers (DLLs). A list of different handlers can be found here. As you can see, it's possible to have custom shell extension handlers for everything ranging from shortcut menus, drag & drop operations, icons, icon overlays, property sheets, thumbnails, infotips, metadata, Explorer columns, copy/move/delete/rename dialogs, search...
Edit: Coincidentally, Raymond Chen happened to post an article about shell extensions today as well (don't forget to read the previous one too).

A: Windows explorer not read headers.
Initially formed menu for any extension based on registry keys, they can be considered startup keys for windows explorer:
HKLM\SOFTWARE\Classes\Protocols\Filter
HKLM\Software\Microsoft\Windows\CurrentVersion\Explorer\ShellExecuteHooks
HKLM\Software\Classes\*\ShellEx\ContextMenuHandlers
HKLM\Software\Classes\Directory\ShellEx\ContextMenuHandlers
HKLM\Software\Classes\Directory\Shellex\DragDropHandlers
HKLM\Software\Wow6432Node\Classes\Directory\Shellex\DragDropHandlers
HKLM\Software\Classes\Directory\Shellex\CopyHookHandlers
HKLM\Software\Classes\Directory\Background\ShellEx\ContextMenuHandlers
HKLM\Software\Classes\Folder\Shellex\ColumnHandlers
HKLM\Software\Wow6432Node\Classes\Folder\Shellex\ColumnHandlers
HKLM\Software\Classes\Folder\ShellEx\ContextMenuHandlers
HKLM\Software\Classes\Folder\ShellEx\DragDropHandlers
HKLM\Software\Classes\Folder\ShellEx\PropertySheetHandlers
HKLM\Software\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers
HKLM\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers

HKCU\Software\Classes\*\ShellEx\ContextMenuHandlers
HKCU\Software\Classes\Directory\Background\ShellEx\ContextMenuHandlers

There is a search by file extension in HKEY_LOCAL_MACHINE\Software\Classes and HKEY_CURRENT_USER\Software\Classes, if file extension found, run designated file handlers.


text:
Q: Terminals - Creating Multiple Identical Folders within Subdirectories and Moving Files I have a bunch of files I'm trying to organize quickly, and I had two questions about how to do that. I really appreciate any help! I tried searching but couldn't find anything on these specific commands for OSX.
First, I have about 100 folders in a directory - I'd like to place an folder in each one of those folders.
For example, I have
Cars/Mercedes/

Cars/BMW/

Cars/Audi/

Cars/Jeep/

Cars/Tesla/

Is there a way I can create a folder inside each of those named "Pricing" in one command, i.e. ->
Cars/Mercedes/Pricing

Cars/BMW/Pricing

Cars/Audi/Pricing

Cars/Jeep/Pricing

Cars/Tesla/Pricing

*

*My second question is a little tougher to explain. In each of these folders, I'd like move certain files into these newly created folders (above) in the subdirectory.
Each file has a slightly different filename but contains the same string of letters - for example, in each of the above folders, I might have
Cars/Mercedes/payment123.html
Cars/BMW/payment432.html
Cars/Audi/payment999.html
Cars/Jeep/payment283.html
Is there a way to search each subdirectory for a file containing the string "payment" and move that file into a subfolder in that subdirecotry - i.e. into the hypothetical "Pricing" folders we just created above with one command for all the subdirectories in Cars?
Thanks so much~! help with either of these would be invaluable.

A: I will assume you are using bash, since it is the default shell in OS X. One way to do this uses a for loop over each directory to create the subdirectory and move the file. Wildcards are used to find all of the directories and the file.
for DIR in Cars/*/ ; do
    mkdir "${DIR}Pricing"
    mv "${DIR}payment*.html" "${DIR}Pricing/"
done

The first line finds every directory in Cars, and then runs the loop once for each, replacing ${DIR} with the current directory. The second line creates the subdirectory using the substitution. Note the double quotes, which are necessary only if the path could contain spaces. The third line moves any file in the directory whose name starts with "payment" and ends with ".html" to the subdirectory. If you have multiple files which match this, they will all be moved. The fourth line simply marks the end of the loop.
If you are typing this directly into the command line, you can combine it into a single line:
for DIR in Cars/*/ ; do mkdir "${DIR}Pricing"; mv "${DIR}payment*.html" "${DIR}Pricing/"; done


text:
Q: SharePoint and  I would like to use integrated authentication to access a SQL database from a web part. It should use the IIS Application pool identity.
By default you will get the error:
System.Data.SqlClient.SqlException: Login failed for user 'SERVER\IUSR_VIRTUALMACHINE'.

Because in web.config impersonation is set to true:
<identity impersonate="true" />

I can set this to false and the database code will work. Anonymously accessed sites will also work. Any SharePoint site that uses authentication will fail however so this is not really a solution..
To solve this would I have to encapsulate all my database access code to run with elevated priviliges, is that how SharePoint does it internally? Somehow that doesn't seem like the most performant solution.
Is that still the way to go, just use SQL security to access databases from SharePoint custom web parts?

A: The <identity /> and <authentication /> elements in the web.config file will together determine the account that is used in to connect to SQL Server when using integrated authentication.
When <authentication mode="Windows" /> is configured, you're deferring to IIS to authenticate users. I'm guessing that your your web.config contains:
<authentication mode="Windows" />
<identity impersonate="true" />

and that IIS is configured to allow anonymous users. Setting <identity impersonate="true" /> causes IIS to pass the identity of the IIS anonymous access account to SQL Server.
As Lars point out, using SPSecurity.RunWithElevatedPrivileges will achieve what you want. I don't believe you'll see any noticeable impact on performance but that's something you can test :-)

A: Use SPSecurity.RunWithElevatedPrivileges to run your code in the context of the app pool identity.

A: This is incorrect. Because <identity impersonate="true" /> is set to true ASP.NET / IIS will run the thread as the user that is currently logged in (so not the app pool account but the actual user logged into the website).
Something else is going on here. Could you post your connection string for the custom database? (minus the private data off course)


text:
Q: Microsoft Visual Studio asks for login endlessly Microsoft Visual Studio Community 2019
Version 16.4.2

Every time, something changed in my local git repository (while solution is open), or i open another solution, or at random point of time Visual Studio asks me for login, i'm entering correct login pass, and VS asks for login again after 20 secods. The process repeats endlessly.
How to avoid this repeats for login, login just once and work for a log time?
tried this, but it doesn't help https://developercommunity.visualstudio.com/t/caught-in-a-login-loop/107160

A: Login loop can happen if there is a Nuget package from a custom source. To verify whether this is the problem, go to

*

*Tools -> Nuget Package Manager -> Package Manager Settings -> Package Sources

*Copy and paste each source into a browser and inspect the result

*If it says something like User 'xyz' lacks permission to complete this action. you may need an Azure DevOps team to give you ReadPackages permission.

A: I solve the problem by using credentials not from my VisualStudio, but from azure devops, where do we keep .sln
I don't know how these things are related, but it works (may be it's related to submodules some how, since few day ago we swtiched authentication for the from ssh to https. Another guess that it's because some of nuget packages are stored in feed and nuget tries to update packages source in a background.
UPDATE
Yes, the problem was related to the fact .sln used nuget packages from feed, to access them you need to authorize

A: In my case, I needed to log in to the source location from my browser.
I don't know why it works, but it does, the code is hosted in azure-devops.

A: You can disable git integrations from VSCode see Remove git integrations from VSCode
or you can use ssh key see https://learn.microsoft.com/en-us/azure/devops/repos/git/use-ssh-keys-to-authenticate?view=azure-devops


text:
Q: ASP.NET MVC - jQuery POST method is null I'm calling a PartialView and injected it to a
 from another PartialView to make it popup modal using Boostrap Modal.
So far, my Boostrap Modal is displaying as expected BUT, NOT behaving as expected. The following are my objectives in my Boostrap Modal.

*

*Make a Boostrap Modal - OK

*Add validation on the Boostrap Modal - OK

*Send the value of my modal to save in the database - NOT OK
This is the
 where I inject the PartialView and make it a modal

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Create Sample

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary" id="btnCreateSample">Create</button>

PartialView to show as Boostrap Modal (This will be injected in the above
)
@model WebSensoryMvc.Models.SampleData

 @using (Html.BeginForm("Create", "SessionData", FormMethod.Post, new { id = "FormCreateSample", name = "FormCreateSample" }))
 {
@Html.AntiForgeryToken()

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.GroupNo, htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.GroupNo, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.GroupNo, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.MaterialID, "Material", htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.DropDownList("MaterialID", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.MaterialID, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.SampleCode, htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.SampleCode, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.SampleCode, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.BatchCode, htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.BatchCode, new { htmlAttributes = new { @class = "form-control text-uppercase" } })
                    @Html.ValidationMessageFor(model => model.BatchCode, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.SizeID, "Size", htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.DropDownList("SizeID", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.SizeID, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.AgeID, "Age", htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.DropDownList("AgeID", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.AgeID, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.TemperatureID, "Temperature", htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.DropDownList("TemperatureID", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.TemperatureID, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.PackagingTypeID, "Packaging Type", htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.DropDownList("PackagingTypeID", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.PackagingTypeID, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.Spike, htmlAttributes: new { @class = "control-label col-md-2" })

                        @Html.EditorFor(model => model.Spike)
                        @Html.ValidationMessageFor(model => model.Spike, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.SampleType, htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.SampleType, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.SampleType, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.Remarks, htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.Remarks, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Remarks, "", new { @class = "text-danger" })

 }

Currently, I'm having hard time debugging in saving the modal value in the database. I'm using ajax to call a method in a controller. But, I'm experiencing the following problems.

*

*When the below code is executed, the $('#FormCreateSample').serialize() which expected to return the model of the PartialView is blank, where all the properties are null.
  $(document).ready(function () {
     $("#btnModal").on('click', function () {
    var url = "/SessionData/Create";

    $.ajax({
        url: url,
        type: 'GET',
        success: function (data) {
            $('#modalBodyContainer').html(data)
            $('#myModal').modal('show');

            $("#btnCreateSample").off().on('click', function () {

                var form = $('form');

                form.data('validator', null);
                $.validator.unobtrusive.parse(form);

                if ($('form').valid()) {

                    $.ajax({
                        url: "/SessionData/Create",
                        type: "POST",
                        data: $('#FormCreateSample').serialize(),
                        success: function () {
                            alert("POST success");
                        },
                        error: function () {
                            alert("POST error");
                        }
                    });

                }
            });
        }
    });
});
 });

*Since my action method in controller have [ValidateAntiForgeryToken] annotation, the above script throw an exception "Token is not present...". To fix that, I updated my code and add the below lines of code.
 var token = $('input[name="__RequestVerificationToken"]').val();
  $.ajax({
     url: "/SessionData/Create",
     type: "POST",
     data: { $('#FormCreateSample').serialize(), __RequestVerificationToken: token },
    success: function () {
       alert("POST success");
    },
    error: function () {
        alert("POST error");
    }
 });

The problem in # 2 approach is, it passes null value in my action method sampleData parameter. Below is my action method in my controller.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public void Create(SampleData sampleData)
    {
        if (ModelState.IsValid)
        {
            sampleData.SessionID = Convert.ToInt32(TempData["CurrentSessionId"]);

            db.SampleDatas.Add(sampleData);
            db.SaveChanges();

            RedirectToAction("List", "SessionData");
        }

    }

Anyone have an idea why $("FormCreateSample").serialize() is null? Or maybe it cannot find the form id FormCreateSample?
TIA
UPDATE 1
After using the first answer, the model is now pass to method but all properties are still null.

A: You need to add AntiForgeryToken in your message header in the ajax call:
var token = $('input[name="__RequestVerificationToken"]').val();
var tokenadr = $('form[action="/SessionData/Create"] input[name="__RequestVerificationToken"]').val();

var headers = {};
var headersadr = {};
headers['__RequestVerificationToken'] = token;
headersadr['__RequestVerificationToken'] = tokenadr;

 $.ajax({
 url: "/SessionData/Create",
 type: "POST",
 headers: headersadr,
 data: "__RequestVerificationToken=" + token + "" + $('form[action="/SessionData/Create"]').serialize(),
success: function () {
   alert("POST success");
},
error: function () {
    alert("POST error");
}
});

A: Try changing
.serialize()

To
.serializeArray()

A: var token = $('input[name="__RequestVerificationToken"]').val();
  $.ajax({
     url: "/SessionData/Create",
     type: "POST",
     data: { $('#FormCreateSample').serialize(), __RequestVerificationToken: token },
     content-type : 'application/json',
    success: function () {
       alert("POST success");
    },
    error: function () {
        alert("POST error");
    }
 });

ADD this :  content-type : 'application/json',

A: After couple of days in debugging my scenario, I found my solution now. Instead of using Bootstrap Modal, I use Bootbox. Using Bootbox fixed all my problems from validation up to saving to database.
Below is the script that I use to open a modal.


text:
Q: Invalid use of incomplete type for named template argument I have the following class template:
 template<typename T=class idType, typename U=class uType>
 class f {

    std::unordered_map<T::Type, float> id_; // error!

 }

I am using the dependency injection framework boost::di and I therefore need to name my template argument to be able to bind those templates to actual types.  I am surprised  that I get an error when I try to declare a hashmap using the underlying type of the template idType. Yes, I would imagine an error if the template argument I use did not have defined a Type, but I certainly do in my case. They are defined after I include the file containing the example above.
The error is:
error: invalid use of incomplete type 'class idType'
   14 |     std::unordered_map<typename T::Type, float> rpc;
      |                                                          ^~~
example.hpp:9:29: note: forward declaration of 'class idType'
    9 | template<typename T = class idType, typename U = class uType>

A:
They are defined after I include the file containing the example above

Yeah, that's not gonna work.
While templates and class definitions do have some specific leeway in that they can sometimes reference things declared/defined after them, these are very specific cases. The bodies of class member functions can reference other elements of their own class that have not at that point been declared (essentially, the compiler moves the member function definition to just after the class definition).
And templates can reference as-of-yet undefined names... so long as those names are dependent on a template parameter.
The code you've presented uses idType, which is not a template parameter name. The parameter is T; idType is merely the default value of that parameter. If the user provides a different type, your use of idType will ignore it.
Therefore, the compiler must search for idType at the point of use within the template, not at instantiation time.
Indeed, the fact that you use idType as a default value at all also imposes the requirement that type needs to exist at the location of the template definition. You named it, after all; it needs to exist if you name it.


text:
Q: Manually order intersections UpSetR I'm trying to manually order my intersections with UpSetR but I don't know if it's possible to do it. order.by only allows freq or degree and I don't see any other parameter that could produce what I want.
a <- list(one = c(1, 2, 3, 5,11,19),
          two = c(1, 2, 4, 5, 11, 13),
          three = c(1, 5, 6, 7, 11, 19),
          four = c(1, 5, 6, 8, 13, 19))
upset(fromList(a), sets = c("one", "two", "three", "four"))

On the left is what I actually have, on the right is what I want to reproduce.

Does anyone knows if it is possible? Thanks.

A: I just found the solution with ComplexUpset package :
 if(!require(devtools)) install.packages("devtools")
devtools::install_github("krassowski/complex-upset")

upset(a,colnames(a),intersections=list(c("one"),c("one","two"),c("one","two","three","four"),c("one","three","four"),c("one","two","three"),c("three"),c("two"),c("four"),c("three","four"),c("two","four")),sort_intersections=FALSE)


text:
Q: Getting a TextBlock/Label in Viewbox to Scale without undesirable padding Here is my very simple xaml:
<Window x:Class="Test.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300" Background="Black" Padding="0" Margin="0" >
    <Viewbox Margin="0">
        <TextBlock Text="Test" Background="AliceBlue" Foreground="Red"
            Padding="0" Margin="0" />
    </Viewbox>
</Window>

This is supposed to scale the Label/Textblock (I've tried both) to fill as much of the window as possible while maintaining aspect ratio of the text.  The issue is, if you drag the size of the window around you can see that there seems to be some sort of invisible, un-changeable padding on the top and bottom of the text.
The left and right don't seem to have it (left image), but the top and bottom do (right image):

Here I pointed out the extra padding I was talking about:

I would expect it to render more like this (I did this manually, so the aspect ratio is not perfect):

Has anyone ever overcome this?  Maybe I need to be drawing this text directly with GDI+ or something, but I'm not even sure where to start with that, so any keywords I should hit Google with would also be appreciated!

A: It's part of the font as far as i can tell, try setting FontFamily to Webdings.


text:
Q: Merging two polygons in Java Is there a clean Java method for merging the points of two given overlapping polygons into one polygon?

A: What you want is a Convex Hull Algorithm it will take a set of points and return a minimal set of points that encloses the original points. This can be done in n.log n time.

A: The Area class supports addition of closed polygons.

A: Convex Hull is different from adding. Adding means making a polygon that looks like the two polygons overlapped which is not necessarily convex.

A: You can use JTS (Java Topology Suite) for that.

*

*Create your Polygon objects

*Use the union method which will return a Set of all points from both polygons

Simple code example:

*

*Given Polygon 1 (as WKT): POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))

*Given Polygon 2 (as WKT): POLYGON ((5 5, 15 5, 15 15, 5 15, 5 5))
// create polygons
Polygon p1 = new GeometryFactory().createPolygon(new Coordinate[]{new Coordinate(0, 0), new Coordinate(0,10), new Coordinate(10,10), new Coordinate(10,0), new Coordinate(0,0)});
Polygon p2 = new GeometryFactory().createPolygon(new Coordinate[]{new Coordinate(5,5), new Coordinate(15,5), new Coordinate(15,15), new Coordinate(5,15), new Coordinate(5,5)});
// calculate union
Geometry union = p1.union(p2);
// print as WKT
System.out.println(union.toText());

The result is a new polygon:
POLYGON ((0 0, 0 10, 5 10, 5 15, 15 15, 15 5, 10 5, 10 0, 0 0))

A: Using the algorithm @Charles Keepax provided, you can do something like this:
public static Polygon mergePolygons(Polygon a, Polygon b) {
    // create arrays for border of each polygon
    Point[] a_pts = new Point[a.npoints];
    Point[] b_pts = new Point[b.npoints];
    // fill them in an array of Points instead of separate coords.
    Arrays.setAll(a_pts, i -> new Point(a.xpoints[i], a.ypoints[i]));
    Arrays.setAll(b_pts, i -> new Point(b.xpoints[i], b.ypoints[i]));
    // first merge 2 arrays into 1
    Point[] all_pts = (Point[]) mergeArrays(a_pts, b_pts);
    // apply Convex Hull on resulting array
    convexHull(all_pts, all_pts.length);

    // separate x and y coordinates back
    int[] x_pts = new int[all_pts.length];
    int[] y_pts = new int[all_pts.length];
    Arrays.setAll(x_pts, i -> all_pts[i].x);
    Arrays.setAll(y_pts, i -> all_pts[i].y);
    // return polygon object using those coordinates
    return new Polygon(x_pts, y_pts, all_pts.length);
}

But of course solution by @Lars is more practical, this is how you could do it in a naive way.


text:
Q: Alexa Account Linking - Expected format I am trying to use account linking in my skill. The problem is that the documentation is not clear enough. I have the login screen, it redirects to the amazon redirect uri provided in the URL parameters, I also include the code (btw I'm using Auth Code Grant) and here comes the problem. My script gets the code and the client credentials and generates the two tokens, but what should it do with them? Does their system wait a json response or something containing the two tokens using their names as keys or should I redirect again? What do they mean in the documentation when they say the server should return the access token and the refresh token?

A: The token response should look like this. I believe the exires_in and refresh_token properties are optional.
{
  "access_token": "...",
  "refresh_token": "...",
  "expires_in": 3600
  "token_type": "bearer"
}

https://developer.amazon.com/docs/alexa-voice-service/authorize-companion-site.html#auth-code-grant.

A: There are multiple threads on this topic from the Amazon Developer Forum I tried the tutorial referenced on a home brew AVS device (RPi3) and it works with no issue (I can get the user name etc. from my Amazon account), although I still can't figure out how to access activity api json within AVS SDK.

A: Steps in Account Linking(Auth code grand flow):
•   User will be redirect to form based login page, used to get the user credentials
•   After validating the user credentials and user authorities by your backend security script, it will be redirect the request to authorize endpoint to generate the authorization code.
•   Once the request reached the authorize end point, it will validate the client details.
•   Once it is validated, user will be redirected to the approval page.
•   Once we get the confirmation from the user, your backend security server script need to create the autorization code and need to give it back to the AWS alexa client.
•   AWS client will call our access token end point to get the access token and refresh token.
•   Once AWS client gets the access token and refresh token, the skill will be linked to the user.
•   AWS Alexa client send the access token in every request once the user have linked the skill
Your Problem: AWS client will call your access token end point url along with Authorization code and client credentials, Your back-end script need to validate those inputs and need to create access token, refresh token and send it back to AWS client.Its a POST request from AWS client, you have to return back response to same POST request.


text:
Q: Issue with the number of changes after I made on change after I cloned I have cloned a fresh version of the repository, created my own development branch, and made only one change in one file.
Now, that I want to see the changes, it shows 12K changes. Maybe it is comparing it to the main not the local. I am not sure.


text:
Q: Barrier and image transition I am wondering why we usually (from Vulkan tutorial and Sascha Willems example) the barrier on the top of pipeline.
If I am reasoning like a producer and consumer (for mipmap creation for example), I have both in src and dst stage the "flag" "TRANSFER_BIT".
So, if I am using the same stage for src and dst, the barrier should happend immediatly, which is the same case if I am using TOP_OF_PIPE flag?
Am I right?

A: I am not sure if I understand the question, but hopefully I will cover it explaining barriers.
src=TOP_OF_PIPE or dst=BOTTOM_OF_PIPE make a non-blocking barrier (effectivelly being only a half of a Memory Dependency and no Execution Dependency). Is that what you mean by "immediatelly happening" barrier?
dst=TOP_OF_PIPE or src=BOTTOM_OF_PIPE is supposed to be all-blocking barrier (at least I often see it in examples and tutorials). I am not so clear about that from the spec (especially if Memory Dependency needs to be there too) and ALL_COMMANDS (or |ing specific stages) seem to be a better replacement.
(BTW I have written about my peeve with that API design.)
Generally as for Execution Dependency what the barriers do is: they make sure srcStage of all the commands recorded before the barrier is finished before dstStage of any of the commands recorded after the barrier started.
(The above special cases should be consistent with that description too.)
So, that being said, TOP_OF_PIPE does not seem like a suitable replacement for TRANSFER. It would either not perform its intended function at all or be inefficient (based on the descriptions above).
Having srcStage==dstStage has no special meaning. Using TRANSFER in that case means TRANSFER stage of previously recorded commands finished before TRANSFER stage of commands recorded after the barrier.


text:
Q: Airflow: Is there a way where I can trigger a job at 35th second, every minute using CRON expression? I want to trigger a shell script at 35th second, every minute. However, I see that airflow supports CRON from the minute level instead of the second level.
For example, the cron Expression
35 * * * *

triggers a job at every 35th minute in airflow.

A: I'm not familiar with Airflow, but cron only supports 1-minute resolution.
You could use cron to invoke a job every minute and let the job sleep for 35 seconds:
* * * * * sleep 35 ; do_something


text:
Q: Rails Devise - Update column from another controller Rails 3.0
Following these instructions:
https://github.com/plataformatec/devise/wiki/How-To%3a-Require-admin-to-activate-account-before-sign_in
I've generated a migration :approved (boolean) for my devise user.rb. Now I want to edit it with a checkbox from a different controller: unapproved_users_controller.rb.
When I load the form in the edit I get this error: undefined method `user_path'.
routes.rb, the resources for my new controller
resources :unapproved_users

app/models/user.rb, notice that :approved is attr_accessible.
class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  attr_accessible :email, :password, :password_confirmation, :remember_me, :approved

  def active_for_authentication?
    super && approved?
  end

  def inactive_message
    if !approved?
      :not_approved
    else
      super # Use whatever other message
    end
  end

  def self.send_reset_password_instructions(attributes={})
    recoverable = find_or_initialize_with_errors(reset_password_keys, attributes, :not_found)
    if !recoverable.approved?
      recoverable.errors[:base] << I18n.t("devise.failure.not_approved")
    elsif recoverable.persisted?
      recoverable.send_reset_password_instructions
    end
    recoverable
  end
end

app/controllers/unapproved_controllers.rb
class UnapprovedUsersController < ApplicationController

  def index
    if params[:approved] == "false"
      @users = User.find_all_by_approved(false)
    else
      @users = User.all
    end
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    @user.update_attributes(params[:user])
  end

end

app/views/unapproved_users/index.html.haml
%h1 Users

= link_to "All Users", :action => "index"
|
= link_to "Users awaiting approval", :action => "index", :approved => "false"

%table
    - @users.each do |user|
        %tr
            %td= user.email
            %td= user.approved
            %td= link_to "Edit", edit_unapproved_user_path(user)

app/views/unapproved_users/edit.html.haml
= render 'form'

app/views/unapproved_users/_form.html.haml
= form_for (@user) do |f|

  -if @user.errors.any?
    #error_explanation
      %h2= "#{pluralize(@user.errors.count, "error")} prohibited this user from being saved:"
      %ul
        - @user.errors.full_messages.each do |msg|
          %li= msg

  .field
    = f.label :approved, 'Approved?'
    = f.check_box :approved
  .actions
    = f.submit 'Save'

A: You need to change the form_for.
It should be
= form_for(@user, :url => unapproved_user_path(@user)) do |f|


text:
Q: Skip table if not found using selenium I have html code that is very similar to this:
MovieOne

Movies

    Genre
    Time
    Days
    Where
    Date Range
    Seating
    Actors

    Action
    10:00 am - 12:00 pm
    SMTWTHFSA
    AMC Showplace
    Aug 20, 2014 - Sept 12, 2014
    Reservations
    Will Ferrel (P)  target="Will Ferrel" >

MovieTwo

Movies

    Genre
    Time
    Days
    Where
    Date Range
    Seating
    Actors

    Action
    11:00 am - 12:30 pm
    SMTWTHFSA
    Showplace Cinemas
    Aug 20, 2014 - Sept 12, 2014
    TBA
    Zach Galifinakis (P)  target="Zach Galifinakis" >

MovieThree

Coming Soon

What I want to be able to do, is take the individual table data that is relevant for the movie title, and if a Movie doesn't have a table I want to say the values are TBA. So far, I am able to get the relevant table information, but I am unable to skip a table. For example I use this code to get the genre of the movie:
int tcounter = 1;

for (Element elements : li) {
WebElement genre = driver.findElement(By.xpath("//table[@class='datadisplaytable']/descendant::table["+tcounter+"]//td[1]"));
WebElement time = driver.findElement(By.xpath("//table[@class='datadisplaytable']/descendant::table["+tcounter+"]//td[2]"));
WebElement days = driver.findElement(By.xpath("//table[@class='datadisplaytable']/descendant::table["+tcounter+"]//td[3]"));
WebElement where = driver.findElement(By.xpath("//table[@class='datadisplaytable']/descendant::table["+tcounter+"]//td[4]"));
WebElement date_range = driver.findElement(By.xpath("//table[@class='datadisplaytable']/descendant::table["+tcounter+"]//td[5]"));
WebElement seating = driver.findElement(By.xpath("//table[@class='datadisplaytable']/descendant::table["+tcounter+"]//td[6]"));
WebElement actors = driver.findElement(By.xpath("//table[@class='datadisplaytable']/descendant::table["+tcounter+"]//td[7]"));
tcounter++;
}

elements refers to a list storing all links on the webpage
(result  for [1] would be action, [2] would be 10:00 am - 12:00pm ...).
This is within a for loop that increments the value of the tcounter by 1 in order to receive the data for different tables. Is there a way I can be able to tell the program to see if a table is present under the TH class, and if not give the values TBA and skip it?
This is my second attempt based on siking's answer:
List<WebElement> linstings = driver.findElements(By.className("ddtitle"));
    String genre = "";
    String time = "";
    String days = "";
    String where = "";
    String dateRange = "";
    String seating = "";
    String actors = "";
    for(WebElement potentialMovie : linstings) {
        try {
            WebElement actualMovie = potentialMovie.findElement(By.xpath("//table[@class='datadisplaytable']"));
            // System.out.println("Actual: " + actualMovie.getText());
            // make all your assignments, for example:
            type = actualMovie.findElement(By.xpath("/descendant::table//td")).getText();
            time = actualMovie.findElement(By.xpath("/descendant::table//td[2]")).getText();
            days = actualMovie.findElement(By.xpath("/descendant::table//td[3]")).getText();
            location = actualMovie.findElement(By.xpath("/descendant::table//td[4]")).getText();
            dates = actualMovie.findElement(By.xpath("/descendant::table//td[5]")).getText();
            schedType = actualMovie.findElement(By.xpath("/descendant::table//td[6]")).getText();
            instructor = actualMovie.findElement(By.xpath("/descendant::table//td[7]")).getText();
            System.out.println(genre+" "+time+" "+days+" "+where+" "+dateRange+" "+actors);

        } catch(Exception ex) {
            // there is no table, so:
            genre = "TBA";
        }
    }

The problem with this code is that it keeps returning the values for only the first table.

A: I trimmed down your HTML sample to the following:
MovieOne

Movies

        Genre

        Action

MovieTwo

Coming Soon

MovieThree

Movies

        Genre

        Action

Hopefully it is representative of all your cases!
Don't use a counter, but use the actual WebElements to iterate over:
// default all your variables to TBA, like:
String genre = "TBA";

// find all the listings on the page...
List<WebElement> linstings = driver.findElements(By.className("ddtitle"));
// ... and iterate over them
for (WebElement listing : linstings) {

    // grab whatever is the _first_ element under the TH ...
    WebElement potentialMovie = listing.findElement(By.xpath("following-sibling::*[1]"));
    // ... check if it has a child element CAPTION
    if (potentialMovie.findElement(By.xpath("caption")) != null) {
        // make all your assignments, for example:
        genre = potentialMovie.findElement(By.xpath("tr[2]/td[1]")).getText();
    }
}

Please note that this code is untested, your mileage may vary!


text:
Q: Error "error: package com.google.firebase.messaging does not exist" even though dependency is added I have the following line in my MainActivity.java that is giving the error...
import com.google.firebase.messaging.FirebaseMessaging;

Which gives error:
error: package com.google.firebase.messaging does not exist

My app level build.gradle has the dependency added...
plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

android {
    compileSdk 32

    defaultConfig {
        applicationId "com.tenera.fcm_reliability_test_android_native_client"
        minSdk 21
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'com.google.android.material:material:1.7.0'
    implementation platform('com.google.firebase:firebase-bom:31.1.0')
    implementation platform('com.google.firebase:firebase-messaging')
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
}

The build process does not complain about any issue with the build.gradle, so I assume it is configured correctly (according to the firebase docs). I am not sure what else I can do to diagnose this issue, since there is no indication that the build file is misconfigured.


text:
Q: react-dom.production.min.js:216 TypeError: Cannot read property 'split' of undefined on production environment I am having this issue every time I deploy my react application to Heroku:

const TodoSuggestion = () => {
    const classes = useStyles();
    const {register, handleSubmit, errors, setValue} = useForm();
    const [navData, setNavData] = useState(SUGGEST_NAVBAR_DATA);

    const onSubmit = (data) => {
        console.log(data)
    }

    React.useEffect(() => {
        register("fullName");
        register("todoTitle");
        register("todoDescription");
    }, [register])

    return (

            <Navbar navData={navData}></Navbar>

                <form onSubmit={handleSubmit(onSubmit)}>
                    <Grid container spacing={2}>
                        <Grid item xs={12}>
                            <Typography variant="h6" className={classes.Typography}>
                                <Box m={1} letterSpacing={6}>
                                    Send Me Your Creative Todo Ideas
                                </Box>
                            </Typography>
                        </Grid>
                        <ThemeProvider theme={theme}>
                            <Grid item xs={12}>
                                <TextField
                                    className={classes.margin}
                                    label="Your Full Name"
                                    variant="outlined"
                                    id="fullName"
                                    ref={register({required: true})}
                                    inputRef={register} name="fullName"
                                />
                            </Grid>
                            <Grid item xs={12}>
                                <TextField
                                    className={classes.margin}
                                    label="Title of the Todo"
                                    variant="outlined"
                                    id="todoTitle"
                                    ref={register({required: true})}
                                    inputRef={register} name="todoTitle"
                                />
                            </Grid>
                            <Grid item xs={12}>
                                <TextField
                                    className={classes.margin}
                                    label="Description of the Todo"
                                    variant="outlined"
                                    id="todoDescription"
                                    ref={register({required: true})}
                                    inputRef={register} name="todoDescription"
                                />
                            </Grid>
                        </ThemeProvider>
                    </Grid>
                    <BootstrapButton variant="contained" style={{backgroundColor: "darkslategray"}} disableRipple type="submit"
                                     className={classes.margin}>
                        <WhiteTextTypography variant="h6" className={classes.title}>
                            <Box m={1} letterSpacing={6}>
                                Send Request
                            </Box>
                        </WhiteTextTypography>
                    </BootstrapButton>
                </form>

    );

}

export default TodoSuggestion;

Any idea what be the issue? the code works locally however, once deployed to Heroku it generates the above error. I already searched for a smiliar error but could not manage to solve the issue.
I am using the following buildpack:
https://github.com/mars/create-react-app-buildpack
I saw that an issue might be that the component is loading multiple times. However, even once including the useEffect the same error still occurs.

A: Looking at your code sample, I think you are using material-ui with react-hook-form.
I found 2 issues, and I hope this will help you.

*

*You don't need that useEffect part

    React.useEffect(() => {
        register("fullName");
        register("todoTitle");
        register("todoDescription");
    }, [register])

This part is not needed for material UI.

*just use inputRef, not the ref.

Make the code as
<TextField
   className={classes.margin}
   label="Your Full Name"
   variant="outlined"
   id="fullName"
   inputRef={register({required: true})}
   name="fullName"
/>


text:
Q: Prereqs for "Require NTLMv2 session security"? I have a requirement to set this up for servers on my Domain environment (both the client and server version).  Workstations are Windows 10 and all Servers are Server 2019.
I know how to do it through GPO, but I am wondering if this can be done without certificates?  All of our workstations are devoid of any (according to the Cert Manager "Personal" store anyways) and a few of the servers have yet to get any either.  Would setting this policy to "Require 128-bit encryption" break things if certain elements of my Domain have no certificates?
As yet when I think "encryption" I think "certificates" so this is what I am basing my question on.  MS documentation just says "older clients that don't support it wont be able to communicate" without any elaboration - I'd imagine both Windows versions I'm using are new enough at least, but there may be more I'm not considering.


text:
Q: Query performance degraded after upgrading Postgres I have a table with several million records in a PostgreSQL 12 database, and after an upgrade from 11 to 12, a few queries started performing horribly. They went from taking ~1 second to ~5 minutes. I tried rebuilding all indexes, vacuuming, and all usual Postgres low-hanging fruit, but performance is still terrible.
This is the query:
SELECT id, activity_count
FROM user
WHERE (search_index) @@ (to_tsquery('pg_catalog.english', '''1234567890'':*') AND active = true
ORDER BY activity_count DESC LIMIT 101

In other words, find all active users matching the given account number, and sort from most active to least.
This query takes about 5 minutes to return just 2 records. Something's not right.
The column search_index is a tsvector storing all the keywords from the table's various text fields (just things like account_number, name, etc).
I have a GIN index created for this column with:
CREATE INDEX user_search_index_gin
    ON public.user USING gin
    (search_index)
    TABLESPACE pg_default;

I also have an index for the active column with:
CREATE INDEX user_active
    ON public.user USING btree
    (active ASC NULLS LAST)
    TABLESPACE pg_default;

And I have an orderd index for the activity_count with:
CREATE INDEX user_activity_count
    ON public.user USING btree
    (activity_count ASC NULLS LAST)
    TABLESPACE pg_default;

Yet when I run EXPLAIN, I get:
"Limit  (cost=0.56..11443.66 rows=101 width=1552)"
"  ->  Index Scan Backward using user_activity_count on user  (cost=0.56..36010185.91 rows=317836 width=1552)"
"        Filter: (active AND (search_index @@ '''1234567890'':*'::tsquery))"

Why is it only using the user_activity_count index and not the more efficient GIN index? How do I fix this?

A: Which index to use?
While your WHERE conditions are not very selective, the current query plan makes a lot of sense with ORDER BY activity_count DESC LIMIT 101. See:

*

*How to search a table with 80 million records faster?
However, your predicates strike me as pretty selective:
WHERE (search_index) @@ (to_tsquery('pg_catalog.english', '''1234567890'':*') AND active = true

That's unless your example '1234567890' is misleading. (Are you sure you want the single quotes in the search term?) It's obviously not the actual query you used. Unmatched parentheses. In any case, you probably want the  "simple" text search configuration (plus some improvements):
WHERE  search_index @@ to_tsquery('pg_catalog.simple', '''1234567890'':*')
AND    active

See:

*

*Get partial match from GIN indexed TSVECTOR column
Statistics
So it seems your statistics are not up to date.

after an upgrade from 11 to 12, a few queries starting performing
horribly. They went from taking ~1 second to ~5 minutes. I tried
rebuilding all indexes, vacuuming, and all usual Postgres low-hanging
fruit, but performance is still terrible.

Why is it only using the user_activity_count index and not the more efficient GIN index?

Did you also add ANALYZE to your basket of all usual Postgres low-hanging fruit? You certainly didn't mention it. Consider instructions in the manual:

*Statistics
Because optimizer statistics are not transferred by pg_upgrade, you
will be instructed to run a command to regenerate that information at
the end of the upgrade. You might need to set connection parameters to
match your new cluster.

If your DB is big, you may be interested in vacuumdb with the option --analyze-in-stages. (That ship may have sailed for the case at hand.) The manual:

This option is useful to analyze a database that was newly populated
from a restored dump or by pg_upgrade. This option will try to create
some statistics as fast as possible, to make the database usable, and
then produce full statistics in the subsequent stages.

Related:

*

*Optimizing slow performance of simple SELECT query


text:
Q: Different flavors with GCM I have two flavors of my app, one debug and one release. The reason why these are different flavors is that I want to allow others to download the debug version to test out new features. So it should be possible to have both apps installed at once.
My app uses GCM which has created some problems with the new security features in Android Lollipop.
This is what I get when I have one flavor install, and try to install the other flavor:

Failure [INSTALL_FAILED_DUPLICATE_PERMISSION
  perm=com.example.test.permission.C2D_MESSAGE pkg=com.example.test]

I have tried to change the permission in the debug flavor by adding this to its Android Manifest:
<permission
    android:name="com.example.test.debug.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
<uses-permission android:name="com.example.test.debug.permission.C2D_MESSAGE" />

But I still get the same error. Anyone know how to solve this?

A: In the link provided by Sunil Mishra it is said that it will work when they are signed by the same key. In my case they were not since one was signed with the release key and the other with the debug key. When releasing my apps for testing they will be signed by the same key.
Thanks Sunil!


text:
Q: $type in AlertRule Condition in ARM Template I'm new to ARM templates and I'm working on a template to deploy a web test and an alert rule to an application insights instance. The app insights is created and maintained using Terraform but alert rules and web tests are not properly supported in Terraform yet. I was using an example taken from this Github issue but we now want to separate it into an ARM step in the Azure DevOps pipeline as we need to obtain the URL for the webhook alert which we can't do easily inside the Terraform script.
I've been cleaning up what came from this example and using this quickstart template as a reference point. However I've noticed something in the quickstart example which I don't have in my example and I cannot seem to find any information on it.
In the alert rule definition properties object we have the condition object which has an odata.type and the associated dataSource has an odata.type as well like so:
"properties": {
    "name": "[parameters('test').name]",
    "description": "[parameters('test').description]",
    "isEnabled": true,
    "condition": {
        "odata.type": "Microsoft.Azure.Management.Insights.Models.LocationThresholdRuleCondition",
        "dataSource": {
            "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource",
            "resourceUri": "[resourceId('microsoft.insights/webtests/', parameters('test').name)]",
            "metricName": "GSMT_AvRaW"
         },
         "windowSize": "PT5M",
         "failedLocationCount": "[parameters('test').failedLocationCount]"
},

The quickstart example is almost identical, but before the odata.type entries is a $type entry like so:
"properties": {
    "name": "[parameters('tests')[copyIndex(1)].name]",
    "description": "[parameters('tests')[copyIndex(1)].description]",
    "isEnabled": true,
    "condition": {
      "$type": "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.LocationThresholdRuleCondition, Microsoft.WindowsAzure.Management.Mon.Client",
      "odata.type": "Microsoft.Azure.Management.Insights.Models.LocationThresholdRuleCondition",
      "dataSource": {
        "$type": "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleMetricDataSource, Microsoft.WindowsAzure.Management.Mon.Client",
        "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource",
        "resourceUri": "[resourceId('microsoft.insights/webtests/', parameters('tests')[copyIndex()].name)]",
        "metricName": "GSMT_AvRaW"
      },
      "windowSize": "PT15M",
      "failedLocationCount": "[parameters('tests')[copyIndex(1)].failedLocationCount]"
    },

My template seems to work nonetheless, but should I include the $type properties? Or are they dependent upon use case? I've not had a lot of success in finding any documentation on this.

A: I have found a possible error , if it doesn't mention $type in the Action and condition something like below:
"condition": {
      "$type": "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.ThresholdRuleCondition, Microsoft.WindowsAzure.Management.Mon.Client",
      "odata.type": "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition",
      "dataSource": {
        "$type": "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleMetricDataSource, Microsoft.WindowsAzure.Management.Mon.Client",
        "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource",
        "resourceUri": "[resourceId('microsoft.insights/components', variables('appInsName'))]",
        "metricName": "request.duration"
      },
      "threshold": "[parameters('responseTime')]",
      "windowSize": "PT5M"
    },
    "actions": [
      {
        "$type": "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleEmailAction, Microsoft.WindowsAzure.Management.Mon.Client",
        "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleEmailAction",
        "sendToServiceOwners": true,
        "customEmails": []
      }

Error while running this script:
New-AzureRmResourceGroupDeployment -Verbose -ResourceGroupName rg.test.ARM -TemplateFile azuredeploy.json -TemplateParameterFile azuredeploy.parameters.json -DeploymentDebugLogLevel All

Error message: Error- There is no target resource for this alert CPU default-app-name-plan.
So ideally one should give the $type in the condition and action to avoid this error while deploying from PowerShell/cli.
There is also an similar issue here.


text:
Q: Is there a Ruby method to print an object to the console in a way that is easy to read? I understand that one can use something like object.inspect to view an object's state in the console (or to whichever output one is using), but does there exist a built-in method or a gem which provides a method to print out the object's state in an easy-to-read fashion?
Example:
> some_blog_post_object.beautiful_inspect
=> "title:    'Some Amazing Title'
    subtitle: 'Hopefully I'm not down-voted for n00b-ness'
    image:    'some_image.jpg'
           .
           .
           .
   "

Or something along these lines.

A: https://github.com/awesome-print/awesome_print can be a good fit. I recommend to combine it with pry.


text:
Q: Django : How to use LIKE while fetching data from mysql DB I need a way to fetch similar records from DB using LIKE from Django .
My code is :
def fetchProductsDate1(request):
    query = request.session.get('query')
    date1 = request.session.get('date1')
    db = pymysql.connect(host=host,user=user,passwd=passwd,db=dbName)
    # Create a Cursor object to execute queries.
    cur = db.cursor()
    # Select data from table using SQL query.
    stmt = "SELECT FSN FROM tab WHERE query LIKE '%s' AND DATE(updated_at) LIKE '%s' " % (query.replace("'", r"\'"), date1)
    log.info(stmt)
    cur.execute(stmt)
    rows = cur.fetchall()
    json_data = rows[0][0]

The db statement looks like:
SELECT num FROM tab WHERE query LIKE 'soch sarees' AND DATE(updated_at) LIKE '2018-11-14'

I want the statement to be like :
SELECT num FROM tab WHERE query LIKE '%soch sarees%' AND DATE(updated_at) LIKE '2018-11-14'

Any help will be really nice :)
Thanks.

A: You can use %% to do that
stmt = "SELECT FSN FROM tab WHERE query LIKE '%%%s%%' AND DATE(updated_at) LIKE '%s' " % (query.replace("'", r"\'"), date1)

Which will give us

SELECT FSN FROM tab WHERE query LIKE '%soch sarees%' AND DATE(updated_at) LIKE '2018-11-14'

Also, I think it' a bad practice to concat parameters like this.This opens path to SQL Injection
You could try:
select_stmt = "SELECT FSN FROM tab WHERE query LIKE '%%%(name)%%%' AND DATE(updated_at) LIKE '%(date)%'"
cursor.execute(select_stmt, { 'name': 'soch sarees','date':'2018-11-14' })


text:
Q: C# Connecting to mysql using linq VS OleDB I'm developing a web application with ASP.net & C# and it needs to connect to mysql database.
I'm not sure if I should use linq or OleDB to connect to mysql!!!
can you give me some advices about that?

A: Couple of options:

*

*http://code2code.net/DB_Linq/

*http://code.google.com/p/dblinq2007/

*http://www.alinq.org

A: you can use either Entity Framework or NHibernate. Both support Linq.


text:
Q: Using Mechanize To login to gmail I am trying to scrap gmail.com and have used mechanize to authenticate but since gmail has two step authentication it was quite tricky but i managed to login but i face loading problem.
My code is
from os import system
import sys
import speech_recognition as sr
import pyaudio
import urllib, urllib2
from bs4 import BeautifulSoup, Comment
import unicodedata
import mechanize
import cookielib
import time

cj = cookielib.CookieJar()
br = mechanize.Browser()
br.set_handle_robots(False)
br.set_cookiejar(cj)
br.open("https://www.gmail.com")

br.select_form(nr=0)
br.form.set_all_readonly(False)
br.form['Email'] = 'vivek0293@gmail.com'

br.submit()

br.select_form(nr=0)
br.form['Passwd'] = '*******'
br.submit()

print"Success"

soup = BeautifulSoup(br.response().read(),"html.parser")

for row in soup.find_all('div'):
    print "hi"
    print row.text

My Output looks like this:
/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7      /Users/vivekrahul/PycharmProjects/untitled/sample.py
Success
hi
hi
Loading vivek0293@gmail.com…Loading standard view |  (for slow connections)This is taking longer than usual. Try reloading the page.If that doesn't work, you can:Disable Labs and try again.If you're on a slow connection, try .For more troubleshooting tips, visit the Help Centre.
hi
Loading vivek0293@gmail.com…
hi
Loading vivek0293@gmail.com…
hi
hi
hi
Loading standard view |  (for slow connections)
hi
This is taking longer than usual. Try reloading the page.If that doesn't work, you can:Disable Labs and try again.If you're on a slow connection, try .For more troubleshooting tips, visit the Help Centre.
hi
If that doesn't work, you can:Disable Labs and try again.If you're on a slow connection, try .For more troubleshooting tips, visit the Help Centre.
hi
Process finished with exit code 0

A: After login submit basic html view form as shown below, you will be redirect to basic HTML view of gmail.
  GMAIL_URL = 'https://mail.google.com/mail/u/0/'

  soup = BeautifulSoup(br.response().read(),"html.parser")
  form = soup.find("form")
  action = form.get('action')
  post_url = GMAIL_URL + action
  g_html = self.session.get(post_url)
  gmail_doc = BeautifulSoup(g_html.text, 'html.parser')


text:
Q: Django save override ImageField handling After the problems I had on this thread, there is still a big problem in my models.py when I'm using the Django Admin. Here is my code (I removed stuff non related to my problem) :
from django.core.files.uploadedfile import InMemoryUploadedFile
from PIL import Image as Img
import StringIO

class Mymodel(models.Model):
        photo = models.ImageField(upload_to="photo/", blank=True, null=True)

        def save(self, *args, **kwargs):
            width = 500
            height = 500
            size = (width,height)

            if self.photo:
                image = Img.open(StringIO.StringIO(self.photo.read()))
                (imw, imh) = image.size
                if (imw>width) or (imh>height) :
                    image.thumbnail(size, Img.ANTIALIAS)

                #If RGBA, convert transparency
                if image.mode == "RGBA":
                    image.load()
                    background = Img.new("RGB", image.size, (255, 255, 255))
                    background.paste(image, mask=image.split()[3]) #3 is alpha channel
                    image=background

                output = StringIO.StringIO()
                image.save(output, format='JPEG', quality=60)
                output.seek(0)
                self.photo = InMemoryUploadedFile(output,'ImageField', "%s.jpg" %self.photo_principale.name.split('.')[0], 'image/jpeg', output.len, None)

            try:
                this = Mymodel.objects.get(id=self.id)
                if this.photo != self.photo:
                    this.photo.delete(save=False)
            except: pass # when new photo then we do nothing, normal case

            super(Mymodel, self).save(*args, **kwargs)

It works, the files are uploaded, resized and converted to JPEG successfully when needed. The problem, every time I edit it, even when NOT uploading a new image, it creates a new image (for example, I save my model a first time with image "hello.jpg", then I edit it, it'll create a new image called "hello_1.jpg" even if I didn't upload anything).
I thought the try/except block would work when only editing (so no new file upload), but apparently not.
Thanks in advance for the help :)

A: Final solution, working for me :
from django.core.files.uploadedfile import InMemoryUploadedFile
from PIL import Image as Img
import StringIO
from django.db.models.signals import post_delete
from django.dispatch import receiver

Class Mymodel(models.Model):
  photo= models.ImageField(upload_to="photo/", blank=True, null=True)

  def save(self, *args, **kwargs):
        width = 500
        height = 500
        size = (width,height)
        isSame = False
        if self.photo:
            try:
                this = Mymodel.objects.get(id=self.id)
                if this.photo==self.photo :
                    isSame= True
            except: pass # when new photo then we do nothing, normal case

            image = Img.open(StringIO.StringIO(self.photo.read()))
            (imw, imh) = image.size
            if (imw>width) or (imh>height) :
                image.thumbnail(size, Img.ANTIALIAS)

            #If RGBA, convert transparency
            if image.mode == "RGBA":
                image.load()
                background = Img.new("RGB", image.size, (255, 255, 255))
                background.paste(image, mask=image.split()[3]) # 3 is the alpha channel
                image=background

            output = StringIO.StringIO()
            image.save(output, format='JPEG', quality=60)
            output.seek(0)
            self.photo = InMemoryUploadedFile(output,'ImageField', "%s.jpg" %self.photo.name.split('.')[0], 'image/jpeg', output.len, None)

        try:
            this = Mymodel.objects.get(id=self.id)
            if this.photo==self.photo or isSame :
                self.photo=this.photo
            else :
                this.photo.delete(save=False)
        except: pass # when new photo then we do nothing, normal case

        super(Mymodel, self).save(*args, **kwargs)

@receiver(post_delete, sender=Mymodel)
def photo_post_delete_handler(sender, **kwargs):
    instance = kwargs['instance']
    storage, path = instance.photo.storage, instance.photo.path
    if (path!='.') and (path!='/') and (path!='photo/') and (path!='photo/.'):
        storage.delete(path)

Hope it can help somebody ;)

A: This Builds on Ralph's answer worked for me for python 3 and django 2
first you must import io:
from io import BytesIO

To resize and add white background where necessary:
def resize_with_white_background(pil_image: Image.Image, desired_width, desired_height):

        img_copy = pil_image.copy()

        # get proportioned image ie (if image is 200X600 and trying to resize to 100X200
        # thumbnail will NOT do this but resize to keep the ratio so it would be 67x200 to maintain the ratio (uses the larger)
        # img_copy changed in place (does not create new image)
        img_copy.thumbnail((desired_width, desired_height), Image.ANTIALIAS)

        # create white background
        background = Image.new('RGB', (desired_width, desired_height), (255,255,255))

        pixels_to_move_left = int((background.width - img_copy.width) * 0.50)  # centered horizontally
        pixels_to_move_down = int((background.height - img_copy.height) * 0.50) # centered vertically

        # paste image into white background box argument tells where to paste
        background.paste(img_copy, box=(pixels_to_move_left, pixels_to_move_down))

        return background  # this will return the background with img_copy pasted in and will be resized to fit your desired size

To set the resized image to and ImageField  create a method in your model:
def set_image(self, desired_width, desired_height):
    try:
        this = MyModel.objects.get(id=self.id)
    except MyModel.DoesNotExist:
        pass
    else:
        # will not resize or set to new image (this avoids setting image every single time you edit and save
        if this.image == self.image and (self.image.width, self.image.height) == (desired_width, desired_height):
            return

    im = Image.open(BytesIO(self.image.read()))

    resized_image = resize_with_white_background(
        pil_image=im,
        desired_width=desired_width,
        desired_height=desired_height
    )

    # output (file like object)
    output = BytesIO()

    # save image into file-like object
    resized_image.save(output, format='JPEG', quality=94)

    # get size of file
    a_size = output.tell()

    # reset to beginning of file-like object
    output.seek(0)

    self.image.file = InMemoryUploadedFile(
        output,
        'ImageField',
        f"{self.image.name.split('.')[0]}.jpg",
        'image/jpeg',
        a_size,
        None
    )

override the save() method of your Model and call the set_image() method before calling the Super().save(*args, **kwargs) method
def save(self, *args, **kwargs):
    self.set_image(
        desired_width=100,  # can be whatever you want
        desired_height=200
    )

    super().save(*args, **kwargs)

A: Try:
if self.photo.name != '':

or
if self.photo.size > 0:


text:
Q: Probability that 100 coins land on heads We flip infinitely many fair coins $1,2,\ldots$ independently.
We have a collection $H$ with infinitely many subsets of $100$ coins. We are interested in the probability $p(H)$ that in at least one of the subsets in $H$, all coins fell on heads.
There are two extreme cases.
Case A: $H$ contains $M$ pairwise-disjoint subsets. The probability that a single subset is all-heads is $2^{-100}$, and all subsets are independent, so $p(H) = 1-(1-2^{-100})^M$. In particular, if $M\to\infty$ then $p(H)\to 1$.
Case B: All subsets in $H$ have a common intersection of size $N<100$. Then, $p(H)$ is (at most) the probability that this common intersection is all-heads, which is $2^{-N}$. In particular, if $N=99$ then $p(H) \leq 2^{-99}$.
MY QUESTION IS: What characterizes the collections $H$ for which $p(H)\to 1$? Is Case A (infinitely many pairwise-disjoint sets) the only case or are there other cases?

A: $p(H)$ is $1$ if and only if there is no finite subset $S$ of $\mathbb N$ such that $h\cap S \neq \varnothing$ for all $h\in H$.
Clearly if such a set $S$ exists then $P(H)<1-2^{-|S|}$.
Suppose that no such $S$ exists, then we can construct a family of disjoint elements of $H:h_1,h_2,\dots$ recursively.
To do this pick $h_1$ arbitrarily, after this, suppose $h_1,h_2,\dots,h_n$ have been selected, notice that $h_1\cup h_2\dots\cup h_n$ is a finite set, so it does not satisfy the condition we asked of $S$, therefore we can pick an $h_{n+1}$.
Using your case $A$ we are done.


text:
Q: Converting a synchronous function to be async As I was implementing service worker subscriptions, I noticed a message from Visual Studio Code, that the following function can be converted to be an async function:

Here is the my original synchronous code.
/**
 * Returns the subscription if it is present, or nothing
 */
function getUserSubscription() {
  return navigator.serviceWorker.ready
    .then(function (serviceWorker) {
      return serviceWorker.pushManager.getSubscription();
    })
    .then(function (pushSubscription) {
      return pushSubscription;
    });
}

I'm not sure how I'd convert this to be an async function. I thought I understood the gist of it, as in converting something like this:
fetchData()
  .then(process())
  .then(processAgain());

to this:
const response1 = await fetchData();
const response2 = await process(response1);
const response = await processAgain(response2);

But I've had no luck converting my function using this technique.

A: Use the async keyword in front of the function. Then await each Promise and return the result.
async function getUserSubscription() {
  const serviceWorker = await navigator.serviceWorker.ready;
  const pushSubscription = await serviceWorker.pushManager.getSubscription();
  return pushSubscription;
}


text:
Q: _GLIBCXX_ATOMIC_BUILTINS not defined in gcc 4.4.5 I have some code that I'm porting and I've tracked down the error to missing
the macro _GLIBCXX_ATOMIC_BUILTINS
Do later versions of gcc not define this?
What's the proper way to get around this?

A: In that version you will also want to check the atomic macros for some particular data type, so you could do:
#if defined(_GLIBCXX_ATOMIC_BUILTINS_4) && !defined(_GLIBCXX_ATOMIC_BUILTINS)
#define _GLIBCXX_ATOMIC_BUILTINS
#endif

or
#if defined(_GLIBCXX_ATOMIC_BUILTINS) || defined(_GLIBCXX_ATOMIC_BUILTINS_4)

The macros are:
/* Define if builtin atomic operations for bool are supported on this host. */
#undef _GLIBCXX_ATOMIC_BUILTINS_1

/* Define if builtin atomic operations for short are supported on this host. */
#undef _GLIBCXX_ATOMIC_BUILTINS_2

/* Define if builtin atomic operations for int are supported on this host. */
#undef _GLIBCXX_ATOMIC_BUILTINS_4

/* Define if builtin atomic operations for long long are supported on this
   host. */
#undef _GLIBCXX_ATOMIC_BUILTINS_8


text:
Q: JIRA not connecting to Server python [python2.7] I am trying to use the rest API functionalities in JIRA which is proviced by its python module.
Here is the code :
from jira import JIRA
options = {
'server': 'https://jira.internal.server',
'verify': 'false'
}

jira = JIRA(options, basic_auth=('usernXXXX', 'PassXXXX'))

After this I am getting the error :
WARNING:root:[Errno 2] No such file or directory while doing GET
https://jira.internal.server/rest/api/2/serverInfo [{u'headers': {'Accept-
Encoding': 'gzip, deflate', u'Accept': u'application/json,*.*;q=0.9', 'User-
Agent': 'python-requests/2.13.0', 'Connection': 'keep-alive', u'X-Atlassian-
Token': u'no-check', u'Cache-Control': u'no-cache', u'Content-Type':
u'application/json'}, 'params': None}]

I have checked the URL through rest client and CUrl https://jira.internal.server/rest/api/2/serverInfo
it gives me perfect result
can anyone help here??

A: from jira import JIRA
options = {
'server': 'https://jira.internal.server',
'verify': False
}

jira = JIRA(options, basic_auth=('usernXXXX', 'PassXXXX'))

You need to change the 'false' to False, because in that case a boolean is needed, not a string. The best solution would be to provide the path to the CA like '/path/ca/cert.pem'. See requests SSL Cert Verification


text:
Q: Oracle DB Developer error on importing .dmp Trying to open a .dmp I've been sent.  I get the following errors from the Import Wizard on Oracle SQL Developer.

Any thoughts on what my problem might be?  I have set full file/folder permissions on Linux and otherwise think I'm using standard boilerplate code...


text:
Q: multiple conditions to subset dataframe based on related id I have the following dataframe called df that has an id column and a related_id column. If the related_id is not null that means there is a desktop version and a mobile version.
I want to subset this dataset to keep only desktop instances if there is a related id. There are also situations however where there can be a mobile observation which has a related id which is also a mobile observation (ids 7 and 8 are examples). In this case i want to keep just one of those observations.
input:
id related_id type
1e  2e          desktop
2e  1e          mobile
3x  NaN        desktop
4w  6w          desktop
5m  NaN        mobile
6w  4w          mobile
7q  8q          mobile
8q  7q          mobile

output:
id related_id type
1e  2e          desktop
3x  NaN        desktop
4w  6w          desktop
5m  NaN        mobile
7q  8q          mobile

how can i do this in pandas?

A: You can np.sort the id and related_id on axis=1 and create a helper series for grouping, then calculate the idxmin with a helper dictionary for the weights:
s = pd.Series(map(tuple,np.sort(df[['id','related_id']].fillna(''),axis=1)))
d= {'desktop':1,'mobile':2}
out = df.loc[df['type'].map(d).groupby(s,sort=False).idxmin()]

print(out)

   id related_id     type
0  1e         2e  desktop
2  3x        NaN  desktop
3  4w         6w  desktop
4  5m        NaN   mobile
6  7q         8q   mobile


text:
Q: CXF and optional entity parameters I'm using Apache CXF as JAX-RS implementation and I have a problem with optional "entity parameters". Take a look at this piece of code:
@Path("/")
public class myClass {

    @PUT
    @Path("/{p1}/something/{p2}/something/{p3}/something/{p4}")
    @Consumes(MediaType.APPLICATION_XML)
    Response updateStuff(
                    @PathParam("p1") String p1,
                    @PathParam("p2") Long p2,
                    @PathParam("p3") String p3,
                    @PathParam("p4") Long p4,
                    MyEntity entity);
}

If entity is not null, everything works fine.
However I want to handle requests with empty body. I would expect, that in such case entity would be null. But it is not true. It seems that CXF can't find my method if body is null. In the logs I can find warning about empty message body (from AbstractJAXBProvider) and that's all.
I also tried to overload updateStuff method:
@Path("/")
public class myClass {

    @PUT
    @Path("/{p1}/something/{p2}/something/{p3}/something/{p4}")
    @Consumes(MediaType.APPLICATION_XML)
    Response updateStuff(
                    @PathParam("p1") String p1,
                    @PathParam("p2") Long p2,
                    @PathParam("p3") String p3,
                    @PathParam("p4") Long p4,
                    MyEntity entity);

    @PUT
    @Path("/{p1}/something/{p2}/something/{p3}/something/{p4}")
    Response updateStuff(
                    @PathParam("p1") String p1,
                    @PathParam("p2") Long p2,
                    @PathParam("p3") String p3,
                    @PathParam("p4") Long p4);
}

But it didn't work either.
Do you have any ideas how to handle null entites parameters?

A: I think, if you webservice @Consumes(MediaType.APPLICATION_XML) the body can't be null.
But you can handle this having a @Provider to read MyEntity object.
@Provider
@Consumes(MediaType.APPLICATION_XML)
public class XMLReader implements MessageBodyReader<MyEntity>{

}

A: Method overloading, as in your example, works (tested in Apache-cxf 3.0), but the client must not send a Content-Type: application/xml header when he wants to hit the method without the entity in the signature.
If another media type is already defined at the class level, annotate the method with @Consumes(MediaType.WILDCARD), see the example below.
@Path("/")
@Consumes(MediaType.APPLICATION_XML)
public class myClass {

    @PUT
    @Path("/{p1}/something/{p2}/something/{p3}/something/{p4}")
    Response updateStuff(
                    @PathParam("p1") String p1,
                    @PathParam("p2") Long p2,
                    @PathParam("p3") String p3,
                    @PathParam("p4") Long p4,
                    MyEntity entity);

    @PUT
    @Path("/{p1}/something/{p2}/something/{p3}/something/{p4}")
    @Consumes(MediaType.WILDCARD)
    Response updateStuff(
                    @PathParam("p1") String p1,
                    @PathParam("p2") Long p2,
                    @PathParam("p3") String p3,
                    @PathParam("p4") Long p4);
}


text:
Q: How do I find out the browser's proxy settings? I am writing a command-line tool for Windows that uses libcurl to download files from the internet.
Obviously, the downloading doesn't work when the user is behind a proxy server, because the proxy needs to be configured. I want to keep my tool as simple as possible however, and not have to burden the user with having to configure the proxy. My tool doesn't even have a config file, so the user would otherwise have to pass in the proxy settings on every command, or set an environment variable or somesuch -- way too much hassle.
So I thought, everyone's browser will usually already be set up properly, proxy configured and everything. This will be true for even the most basic user because otherwise "their internet wouldn't work".
So I figure that I can find out whether to use a proxy by looking at IE's proxy settings.
How do I go about this? More specifically:

*

*Is there one set of "proxy settings" in Windows, used by all browsers (probably IE's), or would I have to write different routines for IE, Firefox, Opera, etc?

*I know that I can probably read the values directly out of the appropriate registry locations if they are configured manually, but does this also work with "automatically detect proxy server?" Do I even have to bother with that option, or is it (almost) never used?

Before people start suggesting alternatives: I'm using C, so I'm limited to the Win32 API, and I really really want to keep using C and libcurl.

A: Here is a complete code sample how to call WinHttpGetIEProxyConfigForCurrentUser method from winhttp.dll library in C#
[TestClass]
public class UnitTest1
{
    [StructLayout(LayoutKind.Sequential)]
    public struct WinhttpCurrentUserIeProxyConfig
    {
        [MarshalAs(UnmanagedType.Bool)]
        public bool AutoDetect;
        [MarshalAs(UnmanagedType.LPWStr)]
        public string AutoConfigUrl;
        [MarshalAs(UnmanagedType.LPWStr)]
        public string Proxy;
        [MarshalAs(UnmanagedType.LPWStr)]
        public string ProxyBypass;

    }

    [DllImport("winhttp.dll", SetLastError = true)]
    static extern bool WinHttpGetIEProxyConfigForCurrentUser(ref WinhttpCurrentUserIeProxyConfig pProxyConfig);

    [TestMethod]
    public void TestMethod1()
    {
        var config = new WinhttpCurrentUserIeProxyConfig();

        WinHttpGetIEProxyConfigForCurrentUser(ref config);

        Console.WriteLine(config.Proxy);
        Console.WriteLine(config.AutoConfigUrl);
        Console.WriteLine(config.AutoDetect);
        Console.WriteLine(config.ProxyBypass);
    }
}

A: The function you're looking for is WinHttpGetIEProxyConfigForCurrentUser(), which is documented at http://msdn.microsoft.com/en-us/library/aa384096(VS.85).aspx. This function is used by Firefox and Opera to get their proxy settings by default, although you can override them per-browser. Don't do that, though. The right thing to do (which is what everybody else does) is to just get the IE settings and assume that they're correct, since they almost always are.
Here's a sample of the relevant logic, which you should adapt for your needs:
if( WinHttpGetIEProxyConfigForCurrentUser( &ieProxyConfig ) )
{
    if( ieProxyConfig.fAutoDetect )
    {
        fAutoProxy = TRUE;
    }

    if( ieProxyConfig.lpszAutoConfigUrl != NULL )
    {
        fAutoProxy = TRUE;
        autoProxyOptions.lpszAutoConfigUrl = ieProxyConfig.lpszAutoConfigUrl;
    }
}
else
{
    // use autoproxy
    fAutoProxy = TRUE;
}

if( fAutoProxy )
{
    if ( autoProxyOptions.lpszAutoConfigUrl != NULL )
    {
        autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;
    }
    else
    {
        autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT;
        autoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A;
    }

    // basic flags you almost always want
    autoProxyOptions.fAutoLogonIfChallenged = TRUE;

    // here we reset fAutoProxy in case an auto-proxy isn't actually
    // configured for this url
    fAutoProxy = WinHttpGetProxyForUrl( hiOpen, pwszUrl, &autoProxyOptions, &autoProxyInfo );
}

if ( fAutoProxy )
{
    // set proxy options for libcurl based on autoProxyInfo
}
else
{
    if( ieProxyConfig.lpszProxy != NULL )
    {
        // IE has an explicit proxy. set proxy options for libcurl here
        // based on ieProxyConfig
        //
        // note that sometimes IE gives just a single or double colon
        // for proxy or bypass list, which means "no proxy"
    }
    else
    {
        // there is no auto proxy and no manually configured proxy
    }
}

A: There are registry keys for these values that you could get to directly of course. You could also do this in .NET without much hassle at all. I believe the WebClient object negotiates the proxy settings for you based on the current settings. This would look like this in C#:
using System.Net;

string url = "http://www.example.com";
WebClient client = new WebClient();
byte[] fileBuffer = client.DownloadFile(url);

Or something close to that.

A: For Firefox/Seamonkey, the problem is a bit more tricky because of the existence of many profiles.
If you want to assume there is only one profile then you just need to find prefs.js. You parse the network.proxy.type, and then use it to decide, which related values to read.
I'm working on some documents for mozilla, so put your followup questions in here (checked wiki box), and I'll try to give you the info you need.


text:
Q: Recreate My Git Repo From this Commit Json file So I messed up, bit time. I force pushed a new git repo over my existing one. I never should have done that. I was able to recover this json file that has the text of all of my files in it. How can I recreate my git repo or get all the files out in a readable format?
commit.json
I am currently trying to regex my data out of the json fields. but the \n+ are getting in the way. I need to also convert the \n's to actual new lines. I will update this as I make progress. But an easy way to convert the json to a repo would be amazing.

A: It looks like all your data is here: https://github.com/MeadeRobert/PicoCTF2017/tree/0efa07574fd0568477c967a355b408c6f1bcfb08
I just followed a link on the JSON.


text:
Q: What are the drawbacks/weaknesses of using LOGO? I was wondering if there were any real drawbacks associated with using LOGO? I know it's meant for teaching kids, but it could theoretically be used for higher level projects. Are there any real drawbacks beside the many different versions of it?

A: Apart from the practical issues (cross platform support, libraries), I think the main issue is that it has dynamic scope (see this discussion). That tends to get confusing, particularly for a functional language, and leads to difficult-to-solve bugs.
But, other than that, I understand it's a pretty cool (lispish and underestimated) language (see link above, which has an interesting discussion).

A: Actually LOGO is quite broadly used: http://ccl.northwestern.edu/netlogo/
Mostly the issues are the same as any scripted language. Plus the user base (although not small) definitely isn't huge.

A: It depends on what you mean by "real". FMSLogo is very mature and stable. It has fast dictionary-like structures called "properties". It has arrays, lists, saves images to GIF, TCP-IP communication, triggers, exceptions, elimination of tail-end recursion. It even support a swiss-knife library that does a bunch of different useful things like HTML generation, date handling, polynomial factoring, numerical integration...

A: A big drawback would be lack of support for specific problems you may encounter using a site such as this. Just see how many logo related posts there are here compared to say java or c++.


text:
Q: Подскажите пожалуйста,Как реализовать вывод (1.2) на Promise?При этом не вытаскивать логику из функций

function one () {
    setTimeout(function () {
        console.log("1");
    },1000)
}
function two () {
        console.log("2")
}

A:

function one() {
  return new Promise(resolve => {
    setTimeout(function() {
      console.log("1");
      resolve();
    }, 1000)
  })
}

function two() {
  console.log("2")
}

one().then(two);