text:
Q: I decided / I thought I was writing to my supervisor today asking for a day off. Here is what I wrote "Dr, I had an accident yesterday. Luckily it wasn't major. But I am not feeling fully recovered today. So I decided to stay at home" but after sending the message it didn't sound write to me. since I was using WhatsApp I deleted the message before she read it. And this is what I wrote later which sounded better in my ears: "Dr, I had an accident yesterday. Luckily it wasn't major. But I am not feeling fully recovered today. So I thought I should stay at home".
The problem is I don't know why my first message didn't sound as good as the second one. Any help?

A: Both are fine. The reason why 'decided' sounds weird to you is that 'thought' makes it seem less planned. You didn't plan to stay at home, you thought maybe you should stay at home considering how physically unfit you feel. 'decided' places emphasis on your action thereafter and 'thought' places emphasis on what you previously explained.
Just comment if this doesn't make sense.


text:
Q: Create a function decorator that logs arguments I am using Python to write a function decorator that logs the arguments and returns value of the function when it is called
    def logfunc(prefix)

The output should be to sys.stderr in the format:
"{prefix}: {function name}({positional args}..., {keyword=args}, ...)"

and
"{prefix}: {function name} -> {return value}"

respectively for call and return.
This is how it is used:
@logfunc("test")
def f(arg)
    return arg

I dont quiet understand it? Can someone show me a pointer?

A: import logging

logger = logging.getLogger(__name__)

def logging_decorator(fn):
    def func(*a, **kw):
       logger.info('%s(%s, %s)', fn, a, kw)
       return fn(*a, **kw)
    return func

if you want to print to stderr instead you can use import sys and then sys.stderr.write('%s(%s, %s)' % (fn, a, kw))

A: I found the question to be interesting, even if it is badly asked :-(
The easy part, if that there are examples of decorators without arguments in Python documentation, but it took me some time to understand that a decorator taking arguments is in fact a function taking arguments and returning a decorator. Once this point is clear, the answer is almost evident :
def logger(prefix):
    def decorate(f):
        def wrapper(*args, **kwargs):
            print(prefix, f.__name__, "args", args, "kwargs", kwargs)
            cr = f(*args, **kwargs)
            print(prefix, f.__name__, "result", cr)
            return cr
        return wrapper
    return decorate

Usage :
>>> @logger("test")
def zut(a, b, foo='FOO'):
    return a+b

>>> zut(2,3)
test zut args (2, 3) kwargs {}
test zut cr 5
5
>>> zut(2,3, foo = 'FEE')
test zut args (2, 3) kwargs {'foo': 'FEE'}
test zut cr 5
5

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to implement oAuth2 on WordPress based website? I own a WordPress based website and trying to write an Android app for it.
I already tried to check out WordPress's open source Android app, but couldn't figure it out.
I want to implement oAuth-2.0 login for the app. Does WordPress have build-in support for oAuth-2.0? How can I implement it on client and server side? Do I need to use a 3rd-party plugin, and is it safe to use plugins?

A:
Is WordPress has build-in support for oAuth-2.0?

Yes, please refer this link: https://wordpress.org/plugins/oauth2-provider/

how can i implement it on client and server side?

For server side, please refer to: https://developer.wordpress.com/docs/oauth2/
For client side, you can use a well-known library like Retrofit to connect to your server. The link above also provided an examples what client sides should do.

do i need to use 3rd-party plugin and is it safe to use plugins?

Yes, Wordpress needs a plugin for this. Just pick a well-known plugin and you would be safe.

A: Your WordPress website needs an OAuth2 server plugin. This is our premium product: https://lana.codes/product/lana-passport/
You can try it with the demo, and there is also detailed documentation for it.
The OAuth2 server plugin provides the authentication server that is connected to the WordPress user system. It also provides the /authorize, /token and /resource endpoints, to which the client can connect and generate a token, and then use the token to access user data. The Android app will need to connect to these endpoints.
Basically, the Authorization Code grant type should be used for this purpose, because it also provides the WordPress login interface if you are not logged in and need to identify yourself. This is the most user-friendly and most popular grant type.
But it is possible that in the case of an Android app it is more beneficial to use the User Credentials grant type.
It is completely safe to use. We pay a lot of attention to security.

However, we also found serious vulnerabilities in several other OAuth plugins:
https://lana.codes/lanavdb/0bab7575-45fc-432d-945e-6100c35c574c/ (CVE-2022-2083)
https://lana.codes/lanavdb/12bb3c02-45f1-4ce8-8a5a-8b44352cf7fc/ (CVE-2022-2133)
https://lana.codes/lanavdb/6d794d65-d44b-4099-94c5-3dd2995b218c/ (CVE-2022-34149)


text:
Q: Project Reference format in a vcproj file(vs2008) Here I am again asking for help.
Can anyone please show me a sample of a vcproj file with a project reference(not assembly reference) or could at least show me the format how is it written in the file.
I have searched in the internet for samples but cant find one with project reference only assembly refs like these
<References>
    <AssemblyReference
        RelativePath="System.dll"
        AssemblyName="System, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL"
        MinFrameworkVersion="131072"
    />
    </References>

so can anyone please give me a sample, as i need to handle these references by reading them as an XML.
Thanks you very muchh
<ProjectReference
        ReferencedProjectIdentifier="{178A5D9D-1F3E-49B1-9190-916D0864BD5C}"
        RelativePathToProject=".\ReleaseNotes\ReleaseNotes.csproj"
    />

A: The references in the .vcproj concern only managed projects, so if you want to reference  native projects there are other ways to do it:

*

*reference project in libs added.

*in the .sln file reference that P1 is dependant to P2.

*in the source code use #pragma comment(lib,..)


text:
Q: Why only id column is shown in migration file when I create model in Python? from django.db import models
class Town(models.Model):

     name: models.CharField(max_length=70,unique=True)
     country: models.CharField(max_length=30,unique=True)

     class Meta:
         pass

This is my model Town whith two attributes: name and country. When I create a migration in the initial_0001.py file only id column is shown
from django.db import migrations, models
class Migration(migrations.Migration):

    initial = True

dependencies = [
]

operations = [
    migrations.CreateModel(
        name='Town',
        fields=[
            ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
        ],
    ),
]

What kind of problem could it be?

A: The ID-Field is always automatically generated by Django when making migrations. You can specifiy your own ID field aswell, but using an auto-incremented like this is fine for your use case.
You also might want to get rid of the unique=True, as it would prevent adding multiple towns from the same country.
Create your model like this and redo your migration process:
class Town(models.Model):

     name = models.CharField(max_length=70)
     country = models.CharField(max_length=30)

When you have 'no changes detected' when making migrations, I usually follow these steps:
First, Delete migrations folder in project.
Then delete django-migration entries in your Database with this query:
DELETE from django_migrations WHERE app='yourAppName'

Then, create new folder 'migrations" in app folder + init.py
Lastly, redo the migration process:
py manage.py makemigrations
py manage.py migrate --run-syncdb

A: I had the same problem, and this solved it. Hope it helps.

*

*Instead of : it should be =

*You also need to provide a default value for all the previous rows that were created

*Then run python manage.py makemigrations

*Run python manage.py migrate

    class Town(models.Model):

         name = models.CharField(max_length=70,unique=True, default='')
         country = models.CharField(max_length=30,unique=True, default='')

         class Meta:
             pass


text:
Q: How to use multiple AppendRow-commands in one sheet which work independent of each other I'm using a sheet where I can open a custom dialog which gives the entered data back to the sheet in a specific range and column. For every new entry I use "AppendRow".
My problem is that i want to use multiple dialogs in one sheet, which should work independent of each other.
What I mean is that I want to "restrict" the appendrow-method to a specific range in the sheet, so when I use another dialog - which gives the data back to another range in the sheet - the different appendRow-commands work independent of each other - so leaving no blank rows in the particular range.
Right now when I enter data in the first dialog and then in the second one, the data in the second range (linked to the second dialog) has a blank row. When I enter data in the first dialog after that, it will leave a blank row the first range and so on.
Can anybody help?
Here is my code which I'm using (it's the second dialog, but the first one works the same way just with different inputs):
function showDialogNOTIZ() {

  var widget = HtmlService.createHtmlOutputFromFile("formNOTIZ.html").setHeight(250).setWidth(700);
  SpreadsheetApp.getUi().showModalDialog(widget, "Neue Notiz / Neuen Zwischenstand anlegen");
}

function appendRowFromFormSubmitNOTIZ(formNOTIZ) {

    SpreadsheetApp.getActiveSheet().appendRow([,,,,,,,formNOTIZ.Datum, formNOTIZ.Inhalt, formNOTIZ.Erstelltvon]);

    SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("H9:H").setNumberFormat("dd.MM.yyyy");

    SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("H9:M").sort({column: 7, ascending: false});

    SpreadsheetApp.getActiveSpreadsheet().toast("Eintrag erfolgreich!","",3);

}

Here are some screenshots of a example spreadsheet:
What I have is this:

But what I want is this:

Here is the code for the example:


text:
Q: Бан аккаунта гугл плей Всем привет.
Помогите, пожалуйста, советом.
Была послана на публикацию в гугл плей моя первая игра. Через три дня приходит сообщение от гугла:
"This is a notification that your Google Play Publisher account has been terminated.
REASON FOR TERMINATION: Prior violations of the Developer Program Policies and Developer Distribution Agreement by this or associated accounts as outlined in previous emails sent to the registered email address(es) of the Publisher account(s).
Google Play Publisher suspensions are associated with developers, and may span multiple account registrations and related Google services.
You can visit the Developer Policy Center to better understand how we enforce Developer Program Policies. If you've reviewed the policy and feel this termination may have been in error, please reach out to our policy support team.
Do not attempt to register a new developer account. We will not be restoring your account at this time.
The Google Play Team"
Аккаунт новый, первая публикация, никаких предупреждений на почту не приходило, сразу вот то вот письмо и бан аккаунта. Написала в техподдержку с просьбой разъяснить, в чем проблема. Пока не ответили. Подскажите, пожалуйста, может быть бан за то, что в игре не были указаны авторы музыки? (К сожалению, я была невнимательна, подумав, что ресурсы бесплатные. Оказывается, музыка бесплатная, но обязательно нужно указать автора. Идиотка, сама виновата, но бан аккаунта?).


text:
Q: Implementation of arrays in F# I have a question:
type Diversion = Pile[]

// allPilesEmpty: Diversion -> bool

I'm new in F#, and I have such an implementation to do.
Could you help me how to implement allPilesEmpty function?
Thanks.

A:   type Diversion = Pile array

  let allPilesEmpty (diversion:Diversion) =
    diversion.Length = 0

Something like this maybe?


text:
Q: Boost Unit Test Framework dependencies execution order I am trying to set dependencies in the Boost Unit Testing Framework.
I have found this thread tbat has an example of how to use the test_unit::depends_on() method. So far so good, I can write some magickery around that to smooth it out.
However, the UTF doesn't honor test dependencies during execution.
Scenario: A BOOST_AUTO_TEST_CASE A is declared before another (B), and A depends_on() B
Excpected (desired) outcome: The framework detects the dependency and runs B first, and then A if B succeeded.
Actual Outcome: A is skipped because B, which has not run yet, has "failed" (i.e. no/false result yet).
Now, my idea was to do a topological sort on the test cases / suites and then run them in the sorted order.
For that, I created a test_tree_visitor to walk the suites and determine the order of the m_members test_suite member.
However, m_members is protected and not accessible via methods.
Since I can't change the headers, (would make upgrading to a newer version more difficult, etc, etc), and the BOOST_* macros "hardcode" the class as test_suite, I was thinking about the following hackery:
class member_accessible_test_suite : public test_suite
{
public:
    const std::vector<test_unit_id> *get_members() const { return &m_members; }
};

class dependency_order_visitor : public test_tree_visitor
{
public:
    virtual void visit( test_case const& tu)
    {}

    virtual bool test_suite_start( test_suite const& tu)
    {
        const member_accessible_test_suite *psuite(reinterpret_cast<const member_accessible_test_suite*>(&tu));
        const std::vector<test_unit_id> *pmembers(psuite->get_members());
        /* do something with pmembers */
        return true;
    }

    virtual void test_suite_finish( test_suite const& tu)
    {}

};

See a watered down version on Coliru
So now to my questions:

*

*The boost libraries are generally well designed - am I making a fundamental mistake due to a misunderstanding about unit testing design by requiring this feature?

*Since member_accessible_test_suite has no data and adds only functions, is the reinterpret_cast() safe or the fast lane into UB land?
Either way, I am worried to use such a ghastly hack in production.

*Is there a better way, and if so, at which point did this turn into an XY problem?

A: The following way seems the most proper when dealing with base class members that are not exposed via any mechanism (but must be accessed for some close functionality, and the base class must not be modified):
Link: Access to private member variables
The reasoning behind this idea as to why this works can be found in the 14.7.2p8 of the standard:

The usual access checking rules do not apply to names used to specify explicit instantiations.
            In particular, the template  arguments and names used in the function declarator
            (including parameter  types, return types and exception specifications) may be private types
            or objects which would normally not be accessible and the template may  be a member template
            or member function which would not normally be  accessible.]

I took the liberty to outsource this into two macros that may come in handy again one day.
As with all of these workarounds - use wisely!
/* The ROB_PRIVATE_MEMBER_INST() macro should be used for explicit instantiation of the template at the appropriate source/compilation unit
   The ROB_PRIVATE_MEMBER_ACCESS() macro should be used for access to the variable where required
*/
#define ROB_PRIVATE_MEMBER_INST(CLASS, TYPE, MEMBER)    \
template<typename T>                                    \
struct CLASS##_##MEMBER##_rob_tag {                     \
  typedef T CLASS::*type;                               \
  friend type get(CLASS##_##MEMBER##_rob_tag);          \
};                                                      \
template<typename Tag, typename Tag::type M>            \
struct CLASS##_##MEMBER##_rob_private                   \
{                                                       \
    friend typename Tag::type get(Tag) { return M; }    \
};                                                      \
template struct CLASS##_##MEMBER##_rob_private<         \
CLASS##_##MEMBER##_rob_tag<TYPE> , &CLASS::MEMBER>;     \
/**/

#define ROB_PRIVATE_MEMBER_ACCESS(CLASS, INSTANCE, TYPE, MEMBER) \
    (INSTANCE.*get(CLASS##_##MEMBER##_rob_tag<TYPE>()))          \
/**/


text:
Q: OpenCV - FAST+BRIEF: How to draw keypoints with DrawMatchesFlags::DRAW_RICH_KEYPOINTS? I have to implement a feature detector using FAST+BRIEF (which is the manual implementation of ORB if I understand correctly).
So, this is the code I have so far:
printf("Calculating FAST+BRIEF features...\n");

Ptr<FastFeatureDetector> FASTdetector = FastFeatureDetector::create();
Ptr<BriefDescriptorExtractor> BRIEFdescriptor = BriefDescriptorExtractor::create();
std::vector<cv::KeyPoint> FASTkeypoints_1, FASTkeypoints_2, FASTkeypoints_3;
Mat BRIEFdescriptors_1, BRIEFdescriptors_2, BRIEFdescriptors_3;

FASTdetector->detect(left08, FASTkeypoints_1);
FASTdetector->detect(right08, FASTkeypoints_2);
FASTdetector->detect(left10, FASTkeypoints_3);

BRIEFdescriptor->compute(left08, FASTkeypoints_1, BRIEFdescriptors_1);
BRIEFdescriptor->compute(right08, FASTkeypoints_2, BRIEFdescriptors_2);
BRIEFdescriptor->compute(left10, FASTkeypoints_3, BRIEFdescriptors_3);

Mat FAST_left08, FAST_right08, FAST_left10;

drawKeypoints(left08, FASTkeypoints_1, FAST_left08, FASTBRIEFfeatcol_YELLOW, DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
imwrite("../Results/FASTBRIEF_left08.png", FAST_left08);
drawKeypoints(right08, FASTkeypoints_2, FAST_right08, FASTBRIEFfeatcol_YELLOW, DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
imwrite("../Results/FASTBRIEF_right08.png", FAST_right08);
drawKeypoints(left10, FASTkeypoints_3, FAST_left10, FASTBRIEFfeatcol_YELLOW, DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
imwrite("../Results/FASTBRIEF_left10.png", FAST_left10);
printf("FAST+BRIEF done. \n");

The code so far works perfectly fine, however I don't get rich keypoints, but standard ones. If I understand correctly, this is because I need to somehow get the descriptor information to the keypoints first, right?
I have done the same implementation with SIFT, SURF and ORB before that, but there I use the computeanddetect function directly, which gives me keypoints, where I can draw with the DrawMatchesFlags::DRAW_RICH_KEYPOINTS flag.

A:
I have to implement a feature detector using FAST+BRIEF (which is the manual implementation of ORB if I understand correctly).

Yes, that is correct.

If I understand correctly, this is because I need to somehow get the descriptor information to the keypoints first, right?

No, keypoints are detected by using different methods. You can use SIFT, FAST, HarrisDetector, SURF etc. only to detect keypoints at first. Then there are different methods to describe the detected keypoints (e.g. a 128-bit float vector descriptor for SIFT) and match them afterwards.
A keypoint in OpenCV can be described by the different attributes angle, size, octave and so on https://docs.opencv.org/3.4.2/d2/d29/classcv_1_1KeyPoint.html
For SIFT every KeyPoint attribute is filled with a number that can later be drawn in the DRAW_RICH_KEYPOINTS flag. For FAST only standard values for the attributes are assigned so that they keypoints can be drawn with the mentioned flag but the size, octave and angle do not vary. Thus, every drawn KeyPoint looks similar.
Here a small code sample as a proof (I only use the ->detect functions):
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/xfeatures2d/nonfree.hpp>

int main(int argc, char** argv)
{

    // Load image
    cv::Mat img = cv::imread("MT189.jpg", CV_LOAD_IMAGE_GRAYSCALE);
    if (!img.data) {
        std::cout << "Error reading image" << std::endl;
        return EXIT_FAILURE;
    }
    cv::Mat output;

    // Detect FAST keypoints
    std::vector<cv::KeyPoint> keypoints_fast, keypoints_sift;
    cv::Ptr<cv::FastFeatureDetector> fast = cv::FastFeatureDetector::create();
    fast->detect(img, keypoints_fast);
    for (size_t i = 0; i < 100; ++i) {
        std::cout << "FAST Keypoint #:" << i;
        std::cout << " Size " << keypoints_fast[i].size << " Angle " << keypoints_fast[i].angle << " Response " << keypoints_fast[i].response << " Octave " << keypoints_fast[i].octave << std::endl;
    }

    // Detect SIFT keypoints
    cv::Ptr<cv::xfeatures2d::SiftFeatureDetector> sift = cv::xfeatures2d::SiftFeatureDetector::create();
    sift->detect(img, keypoints_sift);

    for (size_t i = 0; i < 100; ++i) {
        std::cout << "SIFT Keypoint #:" << i;
        std::cout << " Size " << keypoints_sift[i].size << " Angle " << keypoints_sift[i].angle << " Response " << keypoints_sift[i].response << " Octave " << keypoints_sift[i].octave << std::endl;
    }

    // Draw SIFT keypoints
    cv::drawKeypoints(img, keypoints_sift, output, cv::Scalar::all(-1), cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
    cv::imshow("Output", output);
    cv::waitKey(0);

}


text:
Q: Moving OneNote in sharepoint using files explorer breaks Get pages We moved OneNote hosted in SharePoint from one folder to other using file explorer (View in file explorer option). After the OneNote is moved it started looking like a folder instead of OneNote file and we don't get the notebook which we moved in Get Note books API call. Accessing the one note from client works normally. It is just that OneNote which is moved is not listed in Get Notebooks API call. How to fix it?

A: I work on OS X so I hope this answer is relevant to your situation.
Uploading a notebook to SharePoint results in it losing "special permissions" and becoming just a regular folder (I think this is what is happening to you too).
The workaround I use is to create a new OneNote notebook with the same name and then copy the files from the old notebook to the new one and it will work again in the API.
The actual pageIDs will change as the new notebook has a different ID and you will have to reload the notebook in the OneNote app.
It would be great if there was a function in the API to download and upload Notebooks to Sharepoint, I put a suggestion into the OneNote API's user voice.


text:
Q: Flutter - Overlay container height problem I am using Overlay to render a Container that contains a Listview inside. When the user press '@' I display mention panel using Overlay, the problem is Container takes the height of the whole screen even though I have explicitly set it to 100.0.
I don't know if its a bug with flutter or I am doing something wrong here's a screenshot. Here's a simple dartpad example

Here's the code that I using for the widget
  Widget _buildSuggestionList() {
    return selected != -1
        ? Container(
            color: Colors.purple,
            height: 100.0,
            constraints: BoxConstraints(maxHeight: 100.0, minHeight: 80.0),
            child: ListView.builder(
              itemCount: widget.mentions[selected].data.length,
              itemBuilder: (context, index) {
                final item = widget.mentions[selected].data[index];

                return GestureDetector(
                  onTap: () {
                    if (this._overlayEntry != null) {
                      this._overlayEntry.remove();

                      this._overlayEntry = null;
                    }

                    final newText = "${_controller.value.text}${item["name"]} ";

                    _controller.text = newText;

                    setState(() {
                      text = newText;
                      selected = -1;
                    });
                  },
                  child: Text(
                    item["name"],
                    style: TextStyle(fontSize: 24.0, color: Colors.amber),
                  ),
                );
              },
            ),
          )
        : null;
  }

Here's the overlay code:
this._overlayEntry = OverlayEntry(builder: (_) {
     return CompositedTransformFollower(
         link: _layerLink,
         offset: Offset(0, -(size.height + 730.0)),
         child: _buildSuggestionList(),
     );
}

Overlay.of(key.currentContext).insert(_overlayEntry);

Here's my build function:
  @override
  Widget build(BuildContext context) {
    return Container(
      key: key,
      width: MediaQuery.of(context).size.width,
      child: Stack(
        children: <Widget>[
          Positioned(
            child: Container(
              width: MediaQuery.of(context).size.width,
              padding: EdgeInsets.only(top: 12.0, left: 0.0),
              child: RichText(
                maxLines: 20,
                text: TextSpan(
                  text: text,
                  style: TextStyle(color: Colors.pink, fontSize: 16.0),
                ),
              ),
            ),
          ),
          CompositedTransformTarget(
            link: _layerLink,
            child: TextField(
              maxLines: 20,
              minLines: 1,
              controller: _controller,
              decoration: InputDecoration(hintText: widget.placeholder),
              style: TextStyle(
                color: Colors.transparent,
              ),
            ),
          ),
        ],
      ),
    );
  }

A: You have to restrict the CompositedTransformFollower itself from growing unconditionally, instead of applying the width/height only to the child (your Container), e.g. by using Positioned:
this._overlayEntry = OverlayEntry(builder: (_) {
  return Positioned(
    width: 100,
    height: 100,
    child: CompositedTransformFollower(
      link: _layerLink,
      offset: Offset(0, -(size.height + 730.0)),
      child: _buildSuggestionList(),
    )
  );
}

Instead of Positioned, you can basically use any other widget that restricts the size, the import thing is to wrap the CompositedTransformFollower and not the child.


text:
Q: Maps api android key for places api not work Google maps api for android v2 work with key i created using sha1, but when i put this key in the google places api search string my result is ACCESS DENIED.
Also in the google apis console report i see that i got called for places api.
Any suggestions?

A: No, Both the keys are different, get your places API key here


text:
Q: unmarshel from XML of hiearchy object I have follow XML structure:
A
  AAA
     CCC
     BBB
     CCC
     BBB
  DDD
     CCC
     BBB
     CCC

How to unmarshell such structure by JAXB, is it possible?

A: This structure works fine
    @XmlRootElement
    public class AAA {
       @XmlElements({
            @XmlElement(name = "BBB", type = AbstractBC.BBB.class),
            @XmlElement(name = "CCC", type = AbstractBC.CCC.class)
       })
       public List<AbstractBC> tables;
    }

A: Yes, it is possible to represent that XML structure with JAXB.
When you are unsure how to map something in JAXB, the easiest way to figure out the mapping is to create an XML schema for your XML representation and then run the XML Schema to Java (XJC) utility to see what the class model looks like.


text:
Q: Populating a database after "Sign Up" I would like to populate various tables in my database after a new customer signs up to use our web application. I'm wondering what the best way to do this is, the main requirement being that it should not require any intervention by me. Most of the data is static (but can be changed by the customer later (like preferences for example)), but will obviously need the customer's ID as a way of linking the created records to this customer.
I considered putting a few
Object.create(:customer_id => @customer.id, :yummy => "maybe", :etc => true)
statements in the controller that handles signups, but that annoying little alarm bell that tells me there's a better way is going off again!
Thanks in advance for any suggestions!
Gav

A: The problem with khelll's solution is that if you create a new Account using from outside of the register action (for example, in an admin module), it's database won't be populated.
So I'd prefer something like the following :
class Account < ActiveModel::Base
    def after_create
        populate
    end

    private
    def populate
        # Your logic
    end
end

The after_create callback will be called after any account creation.
That's more MVC and DRY compliant ;)

A: In your controller
class AccountController < ApplicationController
after_filter :populate_db  :only=>[:register]
  def populate_db
    # whatever stuff
    Account.populate
  end
end

And put the logic inside your model:
class Account < ActiveModel::Base
  def populate
  # your logic
  end
end

A: two ways

*

*a trigger function in your database that does this

*a callback in your user model on creation

A: Can you not just set defaults in your database?

A: I'm using a YAML file to populate more than ten tables in database during signup. This approach has some positive side-effects for me:

*

*I can easily change the contents of the seed data for new account

*It is very easy to add localized versions of initial content, i can let YAML files translated easily through 99translations.com

*I'm planning to add data import feature later on where new clients can import their data during or right after signup so they can just take the import file template and customize it for their own needs.

There have been some downsides too:

*

*Inevitably, when data schema changes, sometimes i have to modify all localized versions of these files.

*It is one piece of ugly code i have that maps the foreign keys between all the new records. Maybe i can use some schema descriptors here...

As i get around 300 new signups in a day, it's too early for me to worry about performance.

A: @Omar Qureshi
You shouldn't use trigger function in your database - there are many features that can be done by them, but ActiveRecord is database-agnostic and it has callbacks that handle such things that triggers can. Using something that links you to a specific DB system is wrong.
@dmathieu's answer seems to be the best. And you should consider using Factory girl - it's a great tool for populating the DB.


text:
Q: Definition of the circulation of a vector field and line integral of a scalar field : is there a connexion between them? If $f:\mathbb R^n\to \mathbb R$, and $\Gamma=\{\gamma (t)=(\gamma _1(t),...,\gamma _n(t))\mid t\in [a,b]\}$ then $$\int_\Gamma fd\gamma =\int_a^b f(\gamma(t))\|\gamma '(t)\|dt.$$
If $F:\mathbb R^n\to \mathbb R^n$, $F=(F_1,...,F_n)$ then $$\int_\Gamma F\cdot d\gamma =\int_a^b F(\gamma (t))\cdot \gamma '(t)dt.\tag{E}$$

Now, I would like to say :
$$\int_\Gamma F\cdot d\gamma =\int_\Gamma\sum_{i=1}^n F_id\gamma _i=\sum_{i=1}^n\int_a^b F_i(\gamma _i(t))\|\gamma _i'(t)\|dt,\tag{F}$$
but I don't really find $(E)$. So is there a way to find $(E)$ from $(F)$ ? It should be, no ?

A: if $(\gamma,\phi)$ is a regular curve with $\phi:[a,b]\to\mathbb{R}^3$, with $\phi\in C^1$ and $\phi([a,b])=\gamma$, the integral of a differential form $\omega=\sum a_i dx_i$ along $\gamma$ is (with $F=(a_1,a_2,a_3$)):
$$\int_\gamma\omega:=\int_a^b \sum_{i=0}^3 F_i(\phi(t))\phi_i'(t)dt=\int_a^b \langle F(\phi(t),\phi'(t)\rangle dt=\int_a^b\langle F(\phi(t)),\frac{\phi'(t)}{||\phi'(t)||}\rangle||\phi'(t)||dt=\int_a^b \langle F(\phi(t),T(t)\rangle ds$$
where $\langle\cdot,\cdot\rangle$ is the scalar product on $\mathbb{R}^3$, $T(t)=\frac{\phi'(t)}{||\phi'(t)||}$ and $ds=||\phi'(t)||dt$ is the curvilinear abscissa's differential. This is the correct formal procedure to find the integral of the 2nd kind.
Edit: forgot the i-th component in F in the first equality


text:
Q: llegal JSON value for key 'deviceProvisioningRealm': null while running wladm When running the Worklight Admin command line tool, version 6.3.0.00.20141127-1357, against same version server, I am receiving an error. This occurs when running the "list apps" command and a few other app-specific queries.
/app/IBM/MobileFirst_Platform_Server/shortcuts/wladm --configfile=/app/IBM/bldsrvwladmconfig.txt

Error accessing
  http://localhost:9080/worklightadmin/management-apis/1.0/runtimes/worklight/applications?pageSize=1000000000&locale=en_US:
  HTTP/1.1 500 Internal Server Error FWLSE3000E: A server error was
  detected. Illegal JSON value for key 'deviceProvisioningRealm': null

Getting the content of the URL directly successfully returns data.
APAR PI33197 references a similar error, but without explanation of the cause or solution.
authenticationConfig.xml:
     <?xml version="1.0" encoding="UTF-8"?>
    <tns:loginConfiguration xmlns:tns="http://www.worklight.com/auth/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <!-- Licensed Materials - Property of IBM 5725-G92 (C) Copyright IBM Corp.
                2006, 2013. All Rights Reserved. US Government Users Restricted Rights -
                Use, duplication or disclosure restricted by GSA ADP Schedule Contract with
                IBM Corp. -->
        <staticResources>
            <resource id="subscribeServlet" securityTest="SubscribeServlet">
                            <urlPatterns>/subscribeSMS*;/receiveSMS*;/ussd*</urlPatterns>
                    </resource>
        </staticResources>
        <securityTests>
            <customSecurityTest name="SubscribeServlet">
                <test realm="wl_directUpdateRealm" step="1"/>
                <test isInternalUserID="true" realm="SubscribeServlet"/>
            </customSecurityTest>
            <customSecurityTest name="ISAMforWorklight-web-securityTest">
                    <test realm="wl_antiXSRFRealm" />
                    <test realm="WASLTPARealm" isInternalUserID="true" step="1"/>
             </customSecurityTest>
            <customSecurityTest name="ISAMforWorklight-Step-up-securityTest">
                <test realm="wl_directUpdateRealm" step="1"/>
                <test isInternalDeviceID="false" isInternalUserID="true" realm="WASLTPARealm"/>
        </customSecurityTest>
        </securityTests>
        <realms>
             <realm loginModule="WASLTPAModule" name="WASLTPARealm">
                    <className>com.worklight.core.auth.ext.WebSphereFormBasedAuthenticator</className>
                    <parameter name="login-page" value="/login.html"/>
                    <parameter name="error-page" value="/loginError.html"/>
            </realm>
            <realm loginModule="rejectAll" name="SubscribeServlet">
                <className>com.worklight.core.auth.ext.HeaderAuthenticator</className>
            </realm>
            <realm name="WorklightConsole" loginModule="requireLogin">
                    <className>com.worklight.core.auth.ext.FormBasedAuthenticator</className>
                    <onLoginUrl>/console</onLoginUrl>
            </realm>
            <realm name="deviceProvisioningRealm" loginModule="rejectAll">
                    <className>com.worklight.core.auth.ext.HeaderAuthenticator</className>
            </realm>
        </realms>
        <loginModules>
            <loginModule name="rejectAll">
                <className>com.worklight.core.auth.ext.RejectingLoginModule</className>
            </loginModule>
            <loginModule name="WASLTPAModule">
                            <className>com.worklight.core.auth.ext.WebSphereLoginModule</className>
                    </loginModule>
        </loginModules>
    </tns:loginConfiguration>

A: This APAR has been fixed in version 6.3.0.00.20150305-1844.  Please download the latest fix available at Fix Central.  Our fixes are cumulative so the latest fix will include the fix for this APAR.


text:
Q: How to prevent visible gaps/joins between polygons in QPainter with antialiasing I'm drawing triangles/polygons in QPainter using antialiasing, which come from the rendering of 3D models. If two polygons are drawn immediately next to each other there is a gap between them.
Here is some code (in PyQt) to demonstrate the issue:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Window(QLabel):

    def __init__(self):
        QLabel.__init__(self)

        pixmap = QPixmap(300,300)
        pixmap.fill()
        painter = QPainter(pixmap)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setPen(QPen(Qt.NoPen))
        painter.setBrush(QBrush(QColor('black')))

        poly1 = QPolygonF()
        for x, y in ((0,0),(0,240.5),(210.3,0)):
            poly1 << QPointF(x,y)
        painter.drawPolygon(poly1)
        poly2 = QPolygonF()
        for x, y in ((210.3,0),(210.3,240),(0,240.5)):
            poly2 << QPointF(x,y)
        painter.drawPolygon(poly2)
        painter.end()

        self.setPixmap(pixmap)

app = QApplication(sys.argv)
win = Window()
win.show()
app.exec_()

How can I prevent this problem? As suggest below by vahancho, I could add borders to each polygon, or I could grow by half a pixel in each direction. Unfortunately this makes the joins visible if the fill/pen is partially transparent.

A: Try to do a Gaussian blur of 1 pixel radius while finalizing would avoid the problem.
If you were writing a game, you should turn off the anti-aliasing during the rendering, place the step to the end. Which means you should do something like SSAA in the end, once and for all, but not anti-aliasing in each drawing call.


text:
Q: Visualize SQL stored procedure relationships While I can find a number of tools capable of producing visualizations of table relationships, are there tools for generating vizual representations of PostgreSQL stored procedures/functions?
I have a large set these at hand and need to understand how and when they connect, both to each other and to the tables available.
Suggestions on how to quickly get an overview?

A: PowerDesigner visualizes functions' connections with tables that are used within them.


text:
Q: PyQt4 Installation on Windows 10 Right when I start to install PyQt4, I'm getting an error message: "Error opening file for writing:" "C:\Python27\Lib\site-packages\sip.pyd".  The file does exist, and it is not read only.
I have 64 bit Windows 10 and 32 bit Python2.7, so I chose to install this file PyQt4-4.11.4-gpl-Py2.7-Qt4.8.7-x32.exe.
Before this, I did install SIP by running python configure.py, make, and then make install without errors.
How can I fix this error?  Is it safe to hit the ignore button?


text:
Q: How do you compile a HTML Help Workshop project inside a Docker container? I get this error when I try to compile a HTML Help Workshop project, in a mcr.microsoft.com/windows/servercore:1809 container with Visual Studio Build Tools installed.
PS C:\> & 'C:\Program Files (x86)\HTML Help Workshop\hhc.exe' test.hhp
HHC5010: Error: Cannot open "c:\test.chm". Compilation stopped.

Even this minimal test project fails to compile, and outputs the same error.
[OPTIONS]
Compiled file=C:\test.chm

[FILES]

I noticed that Build Tools doesn't install all files ls 'C:\Program Files (x86)\HTML Help Workshop' so I also tried replacing that with my version of HTML Help Workshop on my desktop but this also did not work.
I want to know if there is a way to compile HTML Help Workshop projects in Docker.

A: I can't believe it!!!! I got it to work with mcr.microsoft.com/windows:1903! So in conclusion, HTML Help Workshop does not work in Windows Servercore but does work in a Windows container.
Here's an example of a dockerfile if you want to use HTML Help Workshop:
FROM mcr.microsoft.com/windows:1903

ADD https://aka.ms/vs/16/release/vs_buildtools.exe vs_buildtools.exe
RUN .\vs_buildtools.exe --quiet --norestart --nocache --wait \
    --add Microsoft.VisualStudio.Component.VC.ATLMFC
RUN del vs_buildtools.exe

Inside a container use this command to compile a help project:
"C:\Program Files (x86)\HTML Help Workshop\hhc.exe" path\toProject.hhp

Note: This only works for English language help files. Unlike Servercore, Microsoft does not publish containers with localized versions of Windows, and I haven't found a way to change system locale in a Docker container. Using the above method for help projects in other languages will result in incorrect encodings.

A: To get it working with servercore:1809 or ltsc2019 you have to add the dlls itss.dll and itircl.dll to the containers syswow64 folder and register it with regsrv32.
The files can be found on your windows-10 installation in the windows\syswow64 folder.
#add missing dlls to run html help workshop on ltsc2019 container
COPY .\itss.dll C:\Windows\SysWOW64\itss.dll
COPY .\itircl.dll C:\Windows\SysWOW64\itircl.dll

RUN C:\Windows\SysWOW64\regsvr32.exe C:\Windows\SysWOW64\itss.dll
RUN C:\Windows\SysWOW64\regsvr32.exe C:\Windows\SysWOW64\itircl.dll


text:
Q: How do I return the answer? public class BankAccount {
  private static final double annualInterestRate = 1.5;
  private static double accountBalance = 150;
  private static double MonthlyInterest;

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    calculateMonthlyInterest();
    System.out.println(MonthlyInterest);
  }

  public static double calculateMonthlyInterest()
  {
    double MonthlyInterest = (accountBalance * annualInterestRate);
    return MonthlyInterest;

  }
}

This is my code, I'm trying to return MonthlyInterest but when I print it out I get 0 instead of 225

A: The Problem
You're mixing static and non-static functionality in some pretty odd ways.  Here's what's happening in your code:
private static double MonthlyInterest;

You create a static variable on your class.  Since it's a primitive double, it defaults to storing 0.  Also, variable names should start with a lower-case letter.  This should be monthlyInterest.  It won't break anything, but it's a standard Java convention to distinguish class names from variable names.
calculateMonthlyInterest();

You call the calculateMonthlyInterest() method.
double MonthlyInterest = (accountBalance * annualInterestRate);
return MonthlyInterest;

You calculate the monthly interest, store it in a new variable, and return it.  Note that your static MonthlyInterest variable is not updated by this code.  Instead, the local variable that you created "shadows" the static variable, and takes precedent over it.
calculateMonthlyInterest();
System.out.println(MonthlyInterest)

Your throw away your return value having never used it, and then print out the static MonthlyInterest that was never changed from its initial value of zero.
Here are two different approaches that you can take to make your code work:

With static variables
public class BankAccount {
    private static final double annualInterestRate = 1.5;
    private static double accountBalance = 150;
    private static double monthlyInterest;

    public static void main(String[] args) {
        calculateMonthlyInterest();
        System.out.println(monthlyInterest);
    }

    public static void calculateMonthlyInterest() {
        monthlyInterest = (accountBalance * annualInterestRate);
    }
}

With local variables
public class BankAccount {
    private static final double annualInterestRate = 1.5;
    private static double accountBalance = 150;

    public static void main(String[] args) {
        double monthlyInterest = calculateMonthlyInterest();
        System.out.println(monthlyInterest);
    }

    public static double calculateMonthlyInterest() {
        return accountBalance * annualInterestRate;
    }
}

A: public class BankAccount {
private static final double annualInterestRate = 1.5;
private static double accountBalance = 150;
private static double MonthlyInterest;

public static void main(String[] args) {
    // TODO Auto-generated method stub
    calculateMonthlyInterest();

    System.out.println(MonthlyInterest);
}

public static void calculateMonthlyInterest()
{
    MonthlyInterest = accountBalance * annualInterestRate ;

}

}

A: You don't need to return any value since you are keeping it in a static variable. If you want your method to actually return a value, assign it directly to MonthlyInterest. You also don't need to declare MonthlyInterest inside your method, since then the value is assigned to the local variable, and the printline takes value from the class static variable.
private static final double annualInterestRate = 1.5;
private static double accountBalance = 150;
private static double MonthlyInterest;

public static void main(String[] args) {
    // TODO Auto-generated method stub
    MonthlyInterest = calculateMonthlyInterest();

    System.out.println(MonthlyInterest);
}

public static double calculateMonthlyInterest()
{
    return  (accountBalance * annualInterestRate);
}

A: public static void main(String[] args) {
  double d = calculateMonthlyInterest();
  System.out.println(d);
}

Does this work?

A: public static double calculateMonthlyInterest()
{
    MonthlyInterest = (accountBalance * annualInterestRate);
    return MonthlyInterest;
}

try this

A: You are creating a new double called 'MonthyInterest' inside your calculateMonthlyInterest method and setting your calculated value to that, instead of your static variable. You could fix this one of two ways: either don't create a new MonthlyInterest variable or return the value as you are now, and use that returned value in your main method (and delete the static MonthlyInterest variable). The code for both of those would look like this
public class BankAccount {
private static final double annualInterestRate = 1.5;
private static double accountBalance = 150;
private static double MonthlyInterest;

public static void main(String[] args) {
    // TODO Auto-generated method stub
    calculateMonthlyInterest();

    System.out.println(MonthlyInterest);
}

public static void calculateMonthlyInterest()
{
    this.MonthlyInterest = (this.accountBalance * this.annualInterestRate);

}

}

or
public class BankAccount {
private static final double annualInterestRate = 1.5;
private static double accountBalance = 150;

public static void main(String[] args) {
    // TODO Auto-generated method stub
    double MonthlyInterest = calculateMonthlyInterest();

    System.out.println(MonthlyInterest);
}

public static double calculateMonthlyInterest()
{
    return this.accountBalance * this.annualInterestRate;

}

}

A: You are defining MonthlyInterest 2 times:

*

*On the BankAccount class

*On the calculateMonthlyInterest method

these are two different variables with the same name becouse of the varable scope the one that you are assigning (accountBalance * annualInterestRate) is the one local to the calculateMonthlyInterest method so this doesn't affect the one defined on te BankAccount class
You can fix this assigning the returned value of  calculateMonthlyInterest to the MonthlyInterest on the class scope :
private static final double annualInterestRate = 1.5;
private static double accountBalance = 150;
private static double MonthlyInterest;

public static void main(String[] args) {
  MonthlyInterest = calculateMonthlyInterest();
  System.out.println(MonthlyInterest);
}

public static double calculateMonthlyInterest() {
  return  (accountBalance * annualInterestRate);
}

or not defining MonthlyInterest on the method:
private static final double annualInterestRate = 1.5;
private static double accountBalance = 150;
private static double MonthlyInterest;

public static void main(String[] args) {
  calculateMonthlyInterest();
  System.out.println(MonthlyInterest);
}

public static double calculateMonthlyInterest() {
  MonthlyInterest = (accountBalance * annualInterestRate);
}


text:
Q: About the definition of semiconcavity Is it true that a function f is semiconcave if and only if
$$
\exists K \;\; s.t. f((1-\lambda)x+\lambda y) \geq (1-\lambda) f(x)+\lambda f(y) + \dfrac{K}{2} \lambda(1-\lambda) |x-y|^2
$$
for any $x,y \in \mathbb{R}^n$ and $\lambda \in [0,1]$ ?
I have found a different definition in "partial differential equations" by Evans i.e.
$$ f(x) -\dfrac{C}{2}|x|^2 \;\; \text{concave}.$$
I can't figure it out if it fits to the one above or not.

A: oh... maybe I have got it right now:
$$
\dfrac{C}{2} |(1-\lambda)x+\lambda y|^2- \dfrac{C}{2}(1-\lambda)|x|^2- \dfrac{C}{2}\lambda|y|^2=\dfrac{C}{2} \left[ ((1-\lambda)x+\lambda y, (1-\lambda)x+\lambda y)-(1-\lambda)(x,x)-\lambda (y,y) \right]=\dfrac{C}{2}\left[(1-\lambda)^2(x,x)+ \lambda^2 (y,y)+ 2\lambda(1-\lambda)(x,y)-(1-\lambda)(x,x)-\lambda (y,y)\right]=\dfrac{C}{2}\left[-\lambda(1-\lambda)(x,x)- \lambda(1-\lambda) (y,y)+ 2\lambda(1-\lambda)(x,y)\right]= -\dfrac{C}{2}\lambda (1-\lambda)\left[(x,x)+(y,y)- 2(x,y)\right]= -\dfrac{C}{2}\lambda (1-\lambda)\left[(x-y,x-y)\right] =-\dfrac{C}{2}\lambda (1-\lambda)|x-y|^2
$$
so that K=-C...isn't it?


text:
Q: CSS remote contract I am signing a contract with someone remote in another country in regards with creating a new style sheet for their website. In our agreement the client pays 1/3 of the money first as deposit and the rest will be paid when I show the completed project online to him.
Now my question is, since I know CSS is viewable online and there is no way to encode it, apart from the fact that I need to trust him, is there any way that I can protect my work from being stolen before the final payment?
How do theme developers usually work remotely?
I would appreciate if you please share your experiences with me

A: Show screen shots only.  Send the style sheet when he pays.

A:
Is there any way that I can protect my work from being stolen before
  the final payment?

If he pretends to look at the website containing the CSS (or have the CSS code at hand directly) no, you cannot protect it.
The CSS file will be downloaded by the browser. He will be able to look at it and copy it entirely if he wishes.
I really see no point in having a CSS being copied. I used CSS for years and there are really no magic tricks or something only you can accomplish. All the things you can do with CSS can be freely available online somewhere.
The same applies for your HTML code and JS (though you can obfuscate your scripts, but the code will still be available to others).
The most you can do is minify your CSS to make it "harder" to read.
You may want to sign a contract with him which states this is your own work and cannot be copied or reused, etc., and appending a copyright notice on the top of your files.

A: Well, he is willing to pay 1/3 in advance, so I would show some good will and trust and wouldn't care about that.
But if you insist on some technical solution, then you could show him your work via some shared screen (Skype and others IM programs have this feature). Also with some shared desktop (such as LogMeIn) you could let him try application and watch him.
OTOH, as a client, I wouldn't be very happy about that, but I am good man throughout :)


text:
Q: rand with vector of strings in a multimap I have a vector of strings and it has three colors. My output only gives me one the first color 'red' where i want it to be random. vector<string> colors = {"red", "green", "yellow"}; there is something wrong with this code
Variety x= static_cast<Variety>(rand()%3);
fruit.insert(make_pair(x,colors[rand()%3]));
i tried doing +1 but that just makes it green.
enum class Variety {
    orange,
    pear,
    apple
};

vector<string> colors = {"red", "green", "yellow"};

struct Fruit {
    Variety v; string color; // red, green or orange
};

int main() {
    multimap<Variety,string> fruit;
    bool foundOrange;
    for (auto j = 0; j < (rand() % 100 + 1); ++j) {
        Variety x = static_cast<Variety>(rand() % 3);
        fruit.insert(make_pair(x, colors[rand() % 3]));
    }
    return EXIT_SUCCESS;
}

A: The right way of using rand() is to call srand() first. srand() will generate a series of random numbers, and rand() will simply iterate over them. If you don't call srand() you will get the same number every time you'll use 'rand()`.
srand example:
int main() {
    // Call this function once to generate the random numbers using the seed `time(NULL)`
    srand(time(NULL));

    for (size_t i = 0; i < 10; i++) {
        std::cout << rand() % 5 << std::endl; // Go through the random numbers series
    }

    return EXIT_SUCCESS;
}

However, in C++ there is the <random> library, that will make your life way more easier in the task of generate random numbers (and will work really better then using srand & rand).
// Function to generate random numbers between `min` and `max` params
size_t get_random(size_t min, size_t max) {
    // the generator will only be seeded once since it's static (Equivalent to calling `srand` once)
    static std::mt19937 gen(std::random_device{}());
    std::uniform_int_distribution<size_t> dist(min, max);
    return dist(gen); // generate random number
}

Credit for function idea: @TedLyngmo.
See more delails: All objects made through constructor have the same vectors


text:
Q: How do I retrieve a versions at a certain versions with Paper Trails? I'm working on switching from vestal_version to paper_trail.
I know vestal versions use versions number while paper_trails use timestamps.
paper_trails has a method called version_at(timestamp), but I found a lot of versions in my table with the same exact date so that method will not work as expected.
I need to achieve the following.
widget1 = widget.paper_trail.version(4)
widget2 = widget.paper_trail.version(10)
# there are a couple of way to get the diff
# using active record diff ( I prefer this to Jeremy Weiskotten's PaperTrail)
changes = widget1.diff(widget2)
# I know I can do
versions = widget.versions[4]
# that only returns versions model instead of widget

Thanks for the help

A: you will have to do reify to get the widget object
widget.versions[4].reify

Find documentation and examples here


text:
Q: Categorical way of making monos commute Is there a categorical way (in terms of diagrams, limits, lifting properties etc) to formulate the requirement that for every pair of monos $f,g:C \to D$ there should be an endomorphism $h:D \to D$, s.t. $h\circ f = g$? I found a couple of specific monos (regular, strict,strong,orthogonal..) but nothing seems to fit for my problem..

A: This is not a condition on monomorphisms at all; as formulated it's a condition on $C$ and $D$. Here is the most closely related thing I know.
A topological space $X$ is sometimes said to be homogeneous if for every $x, y \in X$ there is a homeomorphism $f : X \to X$ such that $f(x) = y$. This is the special case of your situation in $\text{Top}$ where $C$ is a point and $h$ is required to be an isomorphism. Most spaces are not homogeneous but, for example, all connected manifolds without boundary are.
In general this condition seems hard to satisfy. I don't expect there's anything particularly nice to say about it.


text:
Q: Programming Data Types I am trying to learn C and have come up with the following small program.
#include "stdafx.h"

void main()
{
    double height = 0;
    double weight = 0;
    double bmi = 0;

    printf("Please enter your height in metres\n");
    scanf_s("%f", &height);
    printf("\nPlease enter your weight in kilograms\n");
    scanf_s("%f", &weight);
    bmi = weight/(height * height);
    printf("\nYour Body Mass Index stands at %f\n", bmi);
    printf("\n\n");
    printf("Thank you for using this small program.  Press any key to exit");
    getchar();
    getchar();
}

The program compiles perfectly, however the answer returned by the program does not make sense.  If I enter 1.8 for height and 80 for weight, the bmi is like 1.#NF00 which does not make sense.
What am I doing wrong?

A: I think issue in scanf_s syntaxis, you ommited 3-rd argument, which is size of buffer in bytes. Try following:
scanf_s("%lf", &valueToGet, sizeof(double));

A: the drawback of the scanf() and printf() is that it requires very strict format, any mismatch between the control string and the argument can cause drastic error which makes your input or output make no sense at all.  And that mistake is often made by beginners.

A: If you're using %f format specifier, then you must use float data type instead of double.

A: When using scanf with a double, you must use the %lf specifier, as pointers are not promoted with scanf.
For more info, read the following question:
Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

A: scanf (and scanf_s) format %f expects pointer to type float.
Simply change the type of your height and weight variables to float to fix this.

A: The problem is because:
format '%f' expects argument of type 'float*', but argument 2 has type 'double*'

There are two ways to handle this:

*

*Either the variables should be float:
double height = 0;    -->    float height = 0;
double weight = 0;    -->    float weight = 0;
double bmi = 0;       -->    float bmi = 0;

*or the format specifier should correspond to double.
scanf_s("%f", &height);   -->    scanf_s("%lf", &height);

scanf_s("%f", &weight);   -->    scanf_s("%lf", &weight);

printf("\nYour Body Mass Index stands at %f\n", bmi);
                                          |
                                          V
printf("\nYour Body Mass Index stands at %lf\n", bmi);


text:
Q: Using key file in ansible for a particular task What I need to achieve:
I need to copy file from one remote server to another. I am using the yml below.
 - name: fetching file to localhost
   synchronize:
     src: /lcaope01/lca/lst1/logs/{{ inventory_hostname }}
     dest: /lcaope01/lca/FETCHEDLOG/
     mode: pull
   delegate_to: serverX

now  I have 5(A,B,C,D,E) servers from which files are copied to  serverX. If i create a password less connection between serverX and this servers it copies easily.
But the problem is I cant create a password less connection for this.
Is there any way i can use a private key file for the same specifying it in playbook or tasks.
NOTE: Ansible is not running in serverX it is in a different server.
NOTE: I have a private key for serverX


text:
Q: Write to table without primary key using Entity Framework I have a table and I want to insert entries with entity framework. By design, the table cannot have a meaningful primary key.
CREATE TABLE dbo.ChargeCarrier_Storage
(
    ID_ChargeCarrier INT NOT NULL,
    ID_Storage INT NULL,
    PickedUpOn DATETIME2(2) NULL,
    UnloadedOn DATETIME2(2) NULL,
    TransportedByDevice NVARCHAR(50) NOT NULL,

    CONSTRAINT FK_ChargeCarrier_Storage_to_Storage FOREIGN KEY (ID_Storage) REFERENCES Storage(ID) ON DELETE CASCADE,
    CONSTRAINT FK_ChargeCarrier_Storage_to_ChargeCarrier FOREIGN KEY (ID_ChargeCarrier) REFERENCES ChargeCarrier(ID) ON DELETE CASCADE,
    CONSTRAINT CCS_OneNotNull CHECK (PickedUpOn IS NOT NULL OR UnloadedOn IS NOT NULL),
    CONSTRAINT CCS_OnForklift CHECK (ID_Storage IS NULL AND PickedUpOn IS NOT NULL OR ID_Storage IS NOT NULL)
)
GO

CREATE CLUSTERED INDEX IX_ChargeCarrier_Storage ON dbo.ChargeCarrier_Storage (ID_ChargeCarrier)
GO

CREATE UNIQUE INDEX IX_OnForklift ON dbo.ChargeCarrier_Storage (ID_ChargeCarrier, ID_Storage) WHERE ID_Storage IS NULL
GO

The table contains a track list of charge carriers and storage locations. The three non-id fields contain information about which forklift moved the charge carrier, and when. The initial entry for each charge carrier, created by the system, only contains an unload date and both IDs. When a forklift picks up something, a new entry should be created with only the three fields ID_ChargeCarrier, PickedUpOn and TransportedByDevice being set. As the forklift unloads the charge carrier, the entry should be updated with the unload date and the ID of the storage location where the piece was transported to.
ID_ChargeCarrier must always be filled. For each of those IDs, there can only be one single entry with ID_Storage set to NULL, as defined by IX_OnForklift. A charge carrier can appear on the same storage multiple times.
I could make the combination of ID_ChargeCarrier, ID_Storage and PickedUpOn the primary key, but that also doesn't work, because MS-SQL doesn't allow PKs with a nullable column.
As you can see, there is no other meaningful primary key. I strictly don't want to introduce an otherwise-superfluous ID column just to make EF happy.
How can I make the insert work anyways through Entity Framework?

A: From the comments I see this is dealing with a legacy system.
What code would be considered the "owner" of this data, and how many other places (code, systems, reports, etc.) "touch" this data?  Do you foresee needing to ever be querying against this data via EF?
If you just need to insert rows based on an event and don't care to ever query against this data via EF (at least for the foreseeable future) then I'd suggest merely inserting via a raw SQL statement and being done with it. New code for other areas may be starting to leverage EF, but "being consistent for consistency's sake" is never an argument I make. :)
The table design is poor. If this re-factoring needs to rely on this table, and the other touch-points are manageable then I would be arguing to re-design the table into something like:
ID_ChargeCarrier INT NOT NULL,
ID_Storage INT NULL,
EventTypeId INT,
EventOn DATETIME2(2) NOT NULL,
TransportedByDevice NVARCHAR(50) NOT NULL,

Where EventTypeId reflects a Pickup or DropOff and EventOn is the Date. This would accommodate a PK/unique constraint across ID_ChargeCarrier, EventTypeId, and EventOn.
Heck, throw a PK column in, and re-factor TransportedByDevice to a FK to save space as I'm guessing this table will house a significant # of records. Porting existing data into a new structure shouldn't pose any issue other than processing time.
Or at a minimum keeping the same compatible structure, appending a proper PK into the table. For example you can use:
ID_ChargeCarrier INT NOT NULL,
ID_Storage INT NULL,
PickedUpOn DATETIME2(2) NULL,
UnloadedOn DATETIME2(2) NULL,
TransportedByDevice NVARCHAR(50) NOT NULL,
ID_ChargeCarrierStorage INT IDENTITY(1,1) NOT NULL

/w a PK constraint on the new identity column. This should be able to be appended without a table re-create. However, I expect that this table could be quite large so this would reflect a rather expensive operation that should be tested and scheduled accordingly.
EF needs a key defined to determine a unique row identifier. It doesn't even need to be declared as a PK in the database, though it is still restricted to using non-nullable fields. If these are records that you will be going to throughout the life of the system I would strongly recommend using a DB structure that accommodates a legal PK. I have had tables bound to entities that did not have PKs defined, but these were strictly transient staging tables where I loaded data from an external source like Excel, wired up some entities to the table to process the data and move relevant bits along to a permanent table.

A: EF just needs an Entity Key.  It doesn't have to map to a real database Primary Key.
And you should put an unique index on the mapped fields in the database (or risk poor performance and wierd behavior).
In SQL Server unique indexes can have nullable columns.  And you can map non-nullable Entity Properties to nullable database columns.
Here's an example using that table definition:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;

namespace Ef6Test
{
    class ChargeCarrier_Storage
    {
        [Key()]
        [Column(Order =0)]
        public int ID_ChargeCarrier { get; set; }
        [Key()]
        [Column(Order = 1)]
        public int ID_Storage { get; set; }
        [Key()]
        [Column(Order = 2)]
        public DateTime PickedUpOn { get; set; }
        public DateTime UnloadedOn { get; set; }
        public string TransportedByDevice { get; set; }
    }
    class Db : DbContext
    {
        public Db(string constr) : base(constr) { }

        public DbSet<ChargeCarrier_Storage> ChargeCarrier_Storage { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

        }
    }

    class MyDbInitializer : IDatabaseInitializer<Db>
    {
        public void InitializeDatabase(Db context)
        {
            var sql = @"
 drop table if exists dbo.ChargeCarrier_Storage;

 CREATE TABLE dbo.ChargeCarrier_Storage
 (
     ID_ChargeCarrier INT NOT NULL,
     ID_Storage INT NULL,
     PickedUpOn DATETIME2(2) NULL,
     UnloadedOn DATETIME2(2) NULL,
     TransportedByDevice NVARCHAR(50) NOT NULL,

     --CONSTRAINT FK_ChargeCarrier_Storage_to_Storage FOREIGN KEY (ID_Storage) REFERENCES Storage(ID) ON DELETE CASCADE,
     --CONSTRAINT FK_ChargeCarrier_Storage_to_ChargeCarrier FOREIGN KEY (ID_ChargeCarrier) REFERENCES ChargeCarrier(ID) ON DELETE CASCADE,
     CONSTRAINT CCS_OneNotNull CHECK (PickedUpOn IS NOT NULL OR UnloadedOn IS NOT NULL),
     CONSTRAINT CCS_OnForklift CHECK (ID_Storage IS NULL AND PickedUpOn IS NOT NULL OR ID_Storage IS NOT NULL)
 )

 CREATE CLUSTERED INDEX IX_ChargeCarrier_Storage ON dbo.ChargeCarrier_Storage (ID_ChargeCarrier)

 CREATE UNIQUE INDEX IX_OnForklift ON dbo.ChargeCarrier_Storage (ID_ChargeCarrier, ID_Storage) WHERE ID_Storage IS NULL

";
            context.Database.ExecuteSqlCommand(sql);
        }
    }

    class Program
    {

        static string constr = "server=.;database=ef6test;integrated security=true";

        static void Main(string[] args)
        {

            Database.SetInitializer<Db>( new MyDbInitializer());
            using (var db = new Db(constr))
            {
                var f = new ChargeCarrier_Storage();
                f.ID_ChargeCarrier = 2;
                f.ID_Storage = 2;
                f.PickedUpOn = DateTime.Now;
                f.TransportedByDevice = "SomeDevice";

                db.ChargeCarrier_Storage.Add(f);

                db.SaveChanges();
            }
            using (var db = new Db(constr))
            {
                var c = db.ChargeCarrier_Storage.First();

            }

            Console.WriteLine("Hit any key to exit");
            Console.ReadKey();

        }

    }
}

A: Eventually I "solved" the problem by completely re-doing the table. I removed a lot of the clutter and added a primary key.
CREATE TABLE dbo.ChargeCarrier_Storage
(
    ID_ChargeCarrier INT NOT NULL,
    ID_Storage INT NOT NULL,
    ID_User INT NULL,
    StoredOn DATETIME2(2) NOT NULL DEFAULT GetDate(),

    CONSTRAINT PK_ChargeCarrier_Storage PRIMARY KEY (ID_ChargeCarrier, ID_Storage, StoredOn),
    CONSTRAINT FK_ChargeCarrier_Storage_to_Storage FOREIGN KEY (ID_Storage) REFERENCES Storage(ID),
    CONSTRAINT FK_ChargeCarrier_Storage_to_ChargeCarrier FOREIGN KEY (ID_ChargeCarrier) REFERENCES ChargeCarrier(ID)
)
GO

I consider a forklift to be it's own "storage", so the loading and unloading is fully abstracted away now.


text:
Q: C# Can Multiple Classes LOCK the Same Object using multiple References? I want to make multiple instances of this class.
public class Worker
{
    private object _lockObject;
    private Thread _workerThread;
    private string _name;

    public Worker(object lockObject, string name)
    {
        _name = name;
        _lockObject = lockObject;
        _workerThread = new Thread(new ThreadStart(DoWork));
        _workerThread.Start();
    }
    private void DoWork()
    {
        while(true)
        {
            lock(_lockObject)
            {
                Console.WriteLine(_name + "Doing Work");
            }
        }
    }
}

If I pass the same lock object to multiple instances of the class, will a lock in one class instance result in the other class instance waiting on that lock to be free?
static void Main()
{
    private readonly object sharedLockObject = new object();
    Worker a = new Worker(sharedLockObject,"a");
    Worker b = new Worker(sharedLockObject,"b");
    Console.ReadLine();
}

I think that in the above case, Workers will never be :
   Console.WriteLine(_name + "Doing Work");
at the same time?
I just would like some confirmation, as I am unsure as to whether the lock() will lock the reference, or the object that is referenced.
Thanks!

A: The lock statement will mark the object instance, not the referencing variable.
lock(x) {
   ...
}

Is precisely equivalent to:
System.Threading.Monitor.Enter(x);
try {
   ...
}
finally {
   System.Threading.Monitor.Exit(x);
}

where x is an object instance of a reference type.
So yes :-)

A: I would recommend you not to pass a shared object that you use for locking or you could get into some nasty deadlocks. Use a static private member of the class to lock on:
public class Worker
{
    private static object _syncRoot = new object();
    private Thread _workerThread;
    private string _name;

    public Worker(string name)
    {
        _name = name;
        _workerThread = new Thread(new ThreadStart(DoWork));
        _workerThread.Start();
    }
    private void DoWork()
    {
        while(true)
        {
            lock(_syncRoot)
            {
                Console.WriteLine(_name + "Doing Work");
            }
        }
    }
}

A: What you are doing will work, but why not make the _lockObject member of the Worker class static?  It will achieve the same effect but is more object-oriented.
public class Worker
{
    private static object _lockObject = new object();
    private Thread _workerThread;
    private string _name;

    public Worker(string name)
    {
        _name = name;
        _workerThread = new Thread(new ThreadStart(DoWork));
        _workerThread.Start();
    }
    private void DoWork()
    {
        while(true)
        {
            lock(_lockObject)
            {
                Console.WriteLine(_name + "Doing Work");
            }
        }
    }
}

EDIT:  Oops!  I didn't see @Darin Dimitrov's response, which is identical to what I've posted here.  +1 to you, Darin.

A: Yes, object is a reference type so you are passing a reference to the same object, so that same object would be used by each Worker. The object is used for locking, not the reference.


text:
Q: obtaining record id after double clicking DataGridvView row Is there any other concise way to get the record id from a DataGridView row double click event? Is that the event to use?
   private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        var databaseRecordId = dataGridView1.Rows[e.RowIndex].Cells[0].Value;
        //...
    }

A: To be precise
private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        var databaseRecordId = dataGridView1.Rows[e.RowIndex].Cells[0].Value;
    }

CellDoubleClick event better suits than CellContentDoubleClick or CellMouseDoubleClick.

A: I don't know if this is necessarily "easier" but it would be a bit safer in case you don't want to display the id or change the column order in the gridview..
var databaseRecordId = ((MyBoundObjectType)dataGridView1.Rows[e.RowIndex].DataBoundItem).MyRecordId;

Where MyBoundObjectType and MyRecordId are the type that is bound to the row and corresponding Id property.


text:
Q: Apache: Address already in use Every time I try to start httpd on CentOS 7 on my Google VPS, the following message always appears. can you help me?
● httpd.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
Active: failed (Result: exit-code) since Sun 2019-09-08 13:12:27 UTC; 1min 21s ago
Docs: man:httpd(8)
man:apachectl(8)
Process: 2019 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=1/FAILURE)
Process: 2018 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
Main PID: 2018 (code=exited, status=1/FAILURE)
Sep 08 13:12:27 centos-web systemd[1]: Starting The Apache HTTP Server…
Sep 08 13:12:27 centos-web httpd[2018]: (98)Address already in use: AH00072: make_sock: could not bind to address [::]:443
Sep 08 13:12:27 centos-web systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
Sep 08 13:12:27 centos-web kill[2019]: kill: cannot find process ""
Sep 08 13:12:27 centos-web systemd[1]: httpd.service: control process exited, code=exited status=1
Sep 08 13:12:27 centos-web systemd[1]: Failed to start The Apache HTTP Server.
Sep 08 13:12:27 centos-web systemd[1]: Unit httpd.service entered failed state.
Sep 08 13:12:27 centos-web systemd[1]: httpd.service failed.

A: There is already a server running on port 443. Check what other services you have running (e.g. nginx).


text:
Q: Parallel.Foreach with ExecuteQuerySegmentedAsync function is not improving the performance(Asp.net core) Fetching records from Azure table with different criteria condition need to be executed 10 times. I am using Parallel.Foreach method to execute the ExecuteQuerySegmentedAsync in parallel. But with or without Parallel.Foreach, the code execution time is the same.
Below is the sample code I am using:
List<T> result = new List<T>();

var stopWatch = Stopwatch.StartNew();

Parallel.ForEach(List, (item) => // source collection
{
  var temp = filter(pos, item.no, table, from, till);
  if (temp != null) { result.AddRange(temp); }
});
stopWatch.Stop();
Console.WriteLine("thread", stopWatch.ElapsedMilliseconds);

public List<T> filterByTail(List<string> engPos, string tail, CloudTable table, string filterFromDate, string filterTillDate)
    {
        try
        { do
            {
                var queryResult = table.ExecuteQuerySegmentedAsync(rangeQuery, token, null, null).Result;
                dataset.AddRange(queryResult.Results);
                token = queryResult.ContinuationToken;
            }
            while (token != null);
return dataset;
}}

How to improve the performance of fetching data from Azure using parallel processing?

A: I'd recommend checking out this external blog: https://martincarlsen.com/boost-your-azure-table-storage-performance/
The author discusses increasing performance using parallelism, which you have mentioned. He uses a combination of batch and ExecuteBatchAsync for better performance processing.


text:
Q: How to execute javascript on a URL programmatically I would like to use Readability's javascript to clean up news articles, then download the generated article. What this entails is being able to execute their js code:
window.baseUrl          = 'https://www.readability.com';
window.readabilityToken = '';

var s = document.createElement('script');

s.setAttribute('type','text/javascript');
s.setAttribute('charset','UTF-8');
s.setAttribute('src', baseUrl + '/bookmarklet/read.js');

document.documentElement.appendChild(s);

in an environment different from a traditional web browser. For example, this is possible to do by executing the above code on a site using Firebug; I would like to emulate that functionality through Java (without a browser).  One of the problems I see here is the "window" object, which may not be present when accessing pages programmatically.
Any hints on whether this is possible and how to implement?

A: Take a look at a headless browser, such as EnvJS.


text:
Q: amazon sdk android sample code showing exception I am trying to run sample code in aws-android-sdk-1.4.4. I have edited the secret key and access key as specified in the document. But its showing the following error:
11-15 17:22:09.835: I/AmazonHttpClient(2141): Unable to execute HTTP request: Unable to resolve host "s3.amazonaws.com": No address associated with hostname
Could ny one pls help me to solve this issue.

A: Make sure you included following permissions in your manifest.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

A: I help maintain the AWS SDK for Android.  Our samples should work out of the box, so please make sure your device/simulator is able to connect to the internet by launching the web browser or using another application.  You may want to restart the emulator if it is unable to make outbound connections.
Also, please make sure that you don't enter in any additional spaces when entering your access or secret key.
Update 2014-10-07: With the update to version 2 of the AWS SDK for Android, we've made the decision to require importing of the SDK jar files into all samples instead of including them in the repo. All samples have README files that should indicate all the necessary steps to get started with that particular sample.


text:
Q: pdf creation on Android: what is the difference between PdfDocument and PdfPrintedDocument I want to create a pdf file in my Android app.
What is the difference between these two classes ?
https://developer.android.com/reference/android/graphics/pdf/PdfDocument
https://developer.android.com/reference/android/print/pdf/PrintedPdfDocument.html
Thanks !


text:
Q: how to compile multi-folder Fortran Project having interfaces, modules and subroutines I am new to Fortran. I am working on a research project where I am using an open source project that has several files distributed in multiple folders. i found the dependency of each programs but could not figure out how to compile them.
I have source code distributed in three folders.
a)modules
b)interfaces
c)subroutines
I would like to run a program named as 'Main.f90' in subroutines folder, this program has dependency of source codes from modules and interfaces folders.
I am using eclipse for folder structure and makefile to compile.
Any help with this is appreciated.
UPDATE:
I followed the answer posted by @MBR and @Stefan, for some reason VPATH did not able to find programs in source code so I explicitly gave path to those source folder in my Makefile.  below is my make file script.
    .PHONY: Mopac_exe clean

    # Change this line if you are using a different Fortran compiler
    FORTRAN_COMPILER = gfortran
    SRC = src

    #make main program
    Mopac_exe: subroutines mopac.o
        $(FORTRAN_COMPILER) mopac.o *.o -O2 -g  -o bin/Mopac_exe  -I Modules/

    #compile all the subroutines
    subroutines: interfaces
        $(FORTRAN_COMPILER) -c $(SRC)/subroutines/*.F90 -J Modules/Subroutines/ -I Modules/

    #compiles all the interfaces
    interfaces: modules
        $(FORTRAN_COMPILER) -c $(SRC)/interfaces/*.f90 -J Modules/

     # build all the modules and generate .mod file in Modules directory
     modules: build_vast_kind
        $(FORTRAN_COMPILER) -c $(SRC)/modules/*.f90 -J Modules/
        $(FORTRAN_COMPILER) -c $(SRC)/modules/*.F90 -J Modules/

    # compile vastkind.f90 files and generates the .mod file in Modules directory.Every other Modules and interfaces are dependent on this.
    build_vast_kind:clean
       $(FORTRAN_COMPILER) -c $(SRC)/modules/vastkind.f90 -J Modules/

    clean:
       rm -f bin/Mopac_exe *.mod
       rm -f Modules/*.mod
       rm -f *.o

I compiled all the modules and placed in Modules directory of root Folder.
All compilation goes well. I get error when I build the executable. I get following error.
    gfortran mopac.o *.o -O2 -g     -o bin/Mopac_exe  -I Modules/
    mopac.o: In function `main':
    mopac.F90:(.text+0x27c1): multiple definition of `main'
    mopac.o:mopac.F90:(.text+0x27c1): first defined here
    getdat.o: In function `getdat_':
    getdat.F90:(.text+0x22): undefined reference to `iargc_'
    getdat.F90:(.text+0xf2): undefined reference to `getarg_'
    symr.o: In function `symr_':
    symr.F90:(.text+0xd3f): undefined reference to `symp_'
    writmo.o: In function `writmo_':
    writmo.F90:(.text+0x20c2): undefined reference to `volume_'
    collect2: error: ld returned 1 exit status
    make: *** [Mopac_exe] Error 1

`iargc_' is being used in 'getdat file and iargc is already compiled. why there is error while making the executable saying undefined reference? what am I missing?

A: You can do a Makefile which looks like that
F90=gfortran
FFLAGS = -O0
VPATH = modules:interfaces:subroutines:
MODOBJ = module1.o module2.o ...

your_executable: $(MODOBJ) main.o
        $(F90) main.o -o your_executable
%.o:%.f90
        $(F90) $(FFLAGS) -c $^ -o $@

VPATH is the paths of the directories where your Makefile will look for source files, so if you compile your source in the root directory of modules/, interfaces/ and subroutines/, you just have to set up VPATH like that.
If you have many objects and you don't want to write everything by hand, you can retrieve them using the following trick
F90 = gfortran
FFLAGS = -O0
VPATH = modules:interfaces:subroutines
SRCOBJ = $(wildcard modules/*f90)
MODOBJ = $(SRCOBJ:.f90=.o)

your_executable: $(MODOBJ) main.o
        $(F90) main.o -o your_executable
%.o:%.f90
        $(F90) $(FFLAGS) -c $^ -o $@

The wildcard command in a Makefile allows you to use a joker *; then you just have to say that in the strings you will retrieve in $(SRCOBJ), you want to substitute .f90 by .o to get the filenames of your modules.

A: You can create your Makefiles as usual. The biggest problem should be the .mod files. The easiest solution to this problem is to create a separate folder, where these files are stored and searched for.
This can be achieved with the -J and the -module flags for gfortran and ifort, respectively.


text:
Q: Copying block of data in SpreadsheetView to a bigger block does not work I am using the SpreadsheetView from ControlsFX. When I select multiple cells, copy them and paste them to a bigger block it does not work.
My code:
int rowCount = 5;
int columnCount = 3;
GridBase grid = new GridBase(rowCount, columnCount);

ObservableList<ObservableList<SpreadsheetCell>> rows = FXCollections.observableArrayList();

for (int row = 0; row < grid.getRowCount(); ++row) {
    final ObservableList<SpreadsheetCell> list = FXCollections.observableArrayList();
    for (int column = 0; column < grid.getColumnCount(); ++column) {
        list.add(SpreadsheetCellType.STRING.createCell(row, column, 1, 1,"value"));
    }
    rows.add(list);
}

grid.setRows(rows);
spreadsheet.setGrid(grid);

A: It is not well explained in the SpreadsheetView documentation what is exactly supported in copy pasting. I will modify that.
To answer your question, if you copy one value towards several cells, the same value will be pasted everywhere in the selection.
If you copy several cells into one cell, the whole block will be pasted starting from the selected cell.
Now if you have a selection and you try to paste it in another selection (your case), it will fail unless your selection is a multiple of the original selection.
Selection a 2x3 can be pasted in a 4x6 selection. It can also be pasted into a 2x6 selection. But it will not be pasted into a 3x5 selection.
If you want a very specific behavior when pasting, you can override the pasteClipboard method (see https://controlsfx.bitbucket.io/)


text:
Q: apache poi maximum number of rows I would like to know what is maximum number of row you can create with apache poi 3.8 and what is the maximum number you can create with apache poi 3.0 for generating excel files.

A: These limit values are provided by POI:
https://poi.apache.org/apidocs/org/apache/poi/ss/SpreadsheetVersion.html
Specifically: SpreadsheetVersion.EXCEL97.getMaxRows() and SpreadsheetVersion.EXCEL2007.getMaxRows().

A: Another SO user has provided a method to create many rows with POI 3.8. The maximum number of rows are limited by the maximum in the version of Excel you try to open the file in, as well. The int data type is returned by getRowNum (see API), so that could provide your "maximum", but going beyond the number of rows specified in the Excel version (~65k in 2003, 1,048,576 in 2007+) will mean data is lost and potential errors.

A: just in case you want to catch it, this is the Exception that gets thrown.
java.lang.IllegalArgumentException: Invalid row number (65536) outside allowable range (0..65535)


text:
Q: Kotlin - Get Maximum value in ArrayList of Ints I have this ArrayList
var amplititudes: ArrayList<Int> = ArrayList()
amplititudes.add(1)
amplititudes.add(2)
amplititudes.add(3)
amplititudes.add(4)
amplititudes.add(3)
amplititudes.add(2)
amplititudes.add(1)

I want to get the maximum value i.e 4. What will be the easiest way to find the max element? I know about the max() method , but it will forces me to use ? with the return value since it could be null. Is there any solution which is better than this?

A: You can use built-in functionality with maxOrNull (docs):
val amplitudes = listOf(1,2,3,4,3,2,1)
val max = amplitudes.maxOrNull() ?: 0

A: You can use max(), if you want to use the default comparison (as in your case with ints), or maxBy, if you want to use a custom selector (i.e., algorithm) to compare values.
Note that both return int? (in your case), since the collection might be empty (i.e., no maximum value is present)

A: max() deprecated in Kotlin 1.4.
But it was reintroduced in 1.7 . More details here
Both max() and maxOrNull() can be used.
The difference is,
max() returns non null values.If the collection is empty it will throw NoSuchElementException.
maxOrNull() returns a nullable value, so if element not present in collection it would return null.
If you are sure that collection will not be empty or you have handled exception, you can use max().Otherwise it is recommended is to use maxOrNull() and have default value if it returns null.
val amplitudes = listOf(10,8,20,15,30,90)

//Here it returns non-null int
val max:Int = amplitudes.max()
println(max) //90

//Here it returns nullable int
val max :Int? = amplitudes.maxOrNull()
println(max) //90

//Here we can make it as non-nullable type using elvis operator.
val max1 :Int = amplitudes.maxOrNull()?:0
println(max) //90

val amplitudes1 = listOf<Int>()
val max2 :Int? = amplitudes1.maxOrNull()
println(max2) //prints null
val max3:Int = amplitudes1.max()
println(max3) // Throws NoSuchElementException

Playground Link

A: max() becomes deprecated starting from Kotlin 1.4, please use maxOrNull()
val list = listOf(10, 2, 33)
val max: Int = list.maxOrNull() ?: 0


text:
Q: Could not find the sitemap node with URL '/login' in sitefinity Iam trying to creating a multi-language site. After enabling the 2nd language, I tried to load the page using the pages section in sitefinity, at that time this error is triggering. Can you please help me to overcome this.
enter image description here

A: Looks like a permission-related issue. Check this KB article and see if the resolution/workaround sections would help: https://knowledgebase.progress.com/articles/Article/could-not-find-the-sitemap-node-with-url
Resolution:

Change permissions for all pages to add the "Authenticated" Role Then
assign permissions to each individual page separately where needed.
For example, for pages which should be accessed only by Authors or
Editors

Workaround:

Change the permissions for all users to have the Editor role.


text:
Q: Popular word in Array I'm trying to get the most popular/common word from an Array, I've tried the following but instead of it just saying 'Rain' it displays this inside the console instead [rain: 2, hot: 1].
What am I doing wrong? I only want to display the number one most popular words without the number.
Any help/advice would be helpful, thank you.
  var defaultArray = [{age:"25-35",country:"united kingdom",sex:"male",word:"rain"},{age:"25-35",country:"united arab emirates",sex:"male",word:"hot"},{age:"25-35",country:"zimbabwe",sex:"female",word:"rain"}];

  /* Popular */
  function popular() {
    var words = [];
    for(var p = 0; p < defaultArray.length; p++){
      var word = defaultArray[p].word;
      words.push(word);
      console.log(words);
    }
    var count = [];
    for (var i = 0, j = words.length; i < j; i++) {
      if (count[words[i]]) {
        count[words[i]]++;
      }
      else {
        count[words[i]] = 1;
      }
    }
    console.log(count);
  }
  popular();

A: You just need to loop through the count array and find the word with the highest count:
var mostCommonWordCount = 0;
var mostCommonWord = "";
for (var key in count) {
    if (count[key] > mostCommonWordCount) {
        mostCommonWordCount = count[key]
        mostCommonWord = key;
    }
}
console.log(mostCommonWord);

After this runs, mostCommonWord will contain the word with the highest count.  The only caveat is that if there are multiple words with 3 occurrences, for example, then the first one in the count array is the one that will be assigned to mostCommonWord.  So if you're wanting something that will return multiple words if they all have the same count, you'd need to modify this a bit.
Disclaimer: There is likely a better way to do this, but this is the first thing I came up with.

A: in keeping with the original functionality you had. you could just tweak it a bit to get the most popular word. NB: this does not account for ties.
var defaultArray = [
  {age:"25-35",country:"united arab emirates",sex:"male",word:"hot"},
  {age:"25-35",country:"united kingdom",sex:"male",word:"rain"},
  {age:"25-35",country:"united arabemirates",sex:"male",word:"hot"}];

/* Popular */
function popular() {
  var count = 0
  var max=0;
  var currentword="";
  var words = [];

  for(var p = 0; p < defaultArray.length; p++){
    var word = defaultArray[p].word;
    words.push(word);
  }

  for (var i = 0; i<words.length; i++) {
    if (max<=count){
      max=count;
    }
    count=0;
    for (var x=0; x<words.length; x++)
    {
      if (words[i]==words[x] ){
        count++;
      }
      if (count>max)currentword=words[i];
    }
  }
  console.log(currentword);
}

A: You can remove almost everything after you create an array of words and instead add this function:
function mostPopularWord(arr){
  return arr.sort(function(a,b){
    return arr.filter(function(v){ return v===a }).length -
        arr.filter(function(v){ return v===b }).length
  }).pop();
}

Then pass it your array of words like:
mostPopularWord(words) // Returns rain

Here is a jsFiddle
I did not write that function, I found it when searching for a way to help. You can read more about what you were trying to do here: Get the element with the highest occurrence in an array

A: for counting and groupping you can use reduce function, like this:

var defaultArray = [{
    age: "25-35",
    country: "united kingdom",
    sex: "male",
    word: "rain"
  }, {
    age: "25-35",
    country: "united arab emirates",
    sex: "male",
    word: "hot"
  }, {
    age: "25-35",
    country: "zimbabwe",
    sex: "female",
    word: "rain"
  }];

  /* Popular */
  function popular(arr) {
    return arr.reduce(function(acc, cur) {
      if (!acc[cur.word]) acc[cur.word] = 0;
      acc[cur.word] += 1;
      if (acc.MaxCount < acc[cur.word]) {
        acc.MaxCount = acc[cur.word];
        acc.PopularWord = cur.word;
      }
      return acc;
    }, {
      MaxCount: 0
    }).PopularWord;
  }
  document.write('Max popular word: ',popular(defaultArray));

A: I would highly recommend a JavaScript utility library like lodash, in which case you could do something like this:
var obj = _.countBy(_.map(defaultArray, 'word'));
console.log(obj); // Object {rain: 2, hot: 1}

var word = _.keys(obj).reduce(function (a,b) { return obj[a] > obj[b] ? a : b });
console.log(word); // "rain"

Note: See other answers for plain JavaScript functionality


text:
Q: L'Hôpital or L'Hospital? This may be a stupid question but I just want clarification about the use of the name of this rule. Well, most of the time what I see is L'Hospital's Rule, like in Baby Rudin and many other places. Occasionally, though, I do see what seems to be the "more correct" form L'Hôpital's Rule (like in Wikipedia). I believe the latter is the correct version, because the rule was indeed named after Guillaume de l'Hôpital. (see the wikipedia link).
But why is the former version so commonly used (much more than the latter I think)?  The only reason I can imagine is the popularity of the English language. However, though hôpital does mean hospital in English, isn't it totally ridiculous to translate Règle de L'Hôpital into L'Hospital's Rule (just because the corresponding English word hospital happens to make sense)? What's more, how are we supposed to pronounce L'Hospital? In an English way or in a French way? In the first place, I think it is confusing to combine a French article with an English word, and in the second, it is even more confusing to use l' in place of le/la since in English the h in hospital isn't even mute. Anyway L'Hospital makes little sense to me..

A: In the 17th and 18th centuries, the name was commonly spelled l'Hospital, and, as far as I learned when I was a student, even himself used to spell his name that way. However, with time going, many French spellings have been altered: in particular, the silent s has been removed and replaced with the circumflex over the preceding o making l'Hôpital. The former spelling is still used in English with no circumflex.

A: I know you problem! I live in a city where English is popular, but people are not so good at it. I know for sure that it is pronounced without the 's', (L'Hôpital's Rule). But whenever I ask a question related to it to my teacher, instead of saying "lop-it-als" I say "eL-Hos-pi-tals", and then only he understands. So I don't think it will be a problem, just ensure that when you are speaking in front of knowledgeable mathematicians, speak the right way. But if you encounter a situation like mine, the shorter way is better! (y)
Those who are saying that in English you have to pronounce is like "L Hospital", I don't think it is legitimate, because suppose you were born in Spain, and (just for an example), your name was "Jalapeno", then in England, if people call you "Jai-le-peeno", will it seem good? Now rest is in your hands.


text:
Q: Python Reportlab VerticalBarChart - add chart title I'm using VerticalBarChart  from reportlab.graphics.charts.barcharts, and I can't find a documentation to simply add to a title to the chart's bottom. Please help!
chart = VerticalBarChart()

A: According to the user guide the axis title attribute is not implemented yet, so no there is no quick solution for this.

title
Not Implemented Yet. This needs to be like a label, but also
  lets you set the text directly. It would have a default
  location below the axis.
(From the user guide Table 11-5 - XCategoryAxis properties)

The next best solution is probably to add a paragraph under the chart and use a KeepTogether to make sure they will always be on the same page. Like this:
combined_flowable = KeepTogether([chart_flowable, bottom_title_paragraph])


text:
Q: Python3 regex findall Here is my issue. Given below list:
a = ['COP' , '\t\t\t', 'Basis', 'Notl', 'dv01', '6m', '9m', '1y',
     '18m', '2y', '3y', "15.6", 'mm', '4.6', '4y', '5y', '10', 'mm',
     '4.6', '6y', '7y', '8y', '9y', '10y', '20y', 'TOTAL', '\t\t9.2' ]

I'm trying to get some outputs like this one. The most important note is the rows
After the first number ended on "y" or "m" will come a number only if it is there in the list
Example : ('3y', '15.6', '')
SAMPLE OUTPUT ( forget about the structure that is a tuple, jsut want teh values)
('6m', '', '')
('9m', '', '')
('1y', '', '')
('18m', '', '')
('2y', '', '')
('3y', '15.6', '')
('4y', '', '')
('5y', '10', '')
('6y', '', '')
('7y', '', '')
('8y', '', '')
('9y', '', '')
('10y', '', '')
('20y', '', '')

I used the following regex that should have returned :

*

*all numbers followed by "y" or "m" => (\b\d+[ym]\b)

*and then any number (integer or not) if it appears (meaning  zero or more times)=>
(\b[0-9]+.[0-9]\b)

Here is what I did, using Python3 regex and re.findall(), but still got no result
rule2 = re.compile(r"(\b\d+[ym]\b)(\b[0-9]+.*[0-9]*\b)+")
a_str = " ".join(a)
OUT2 = re.findall(rule2, a_str)
print(OUT2)
# OUT2 >>[]

Why I'm not getting the correct result?

A: You cannot use word boundary twice. Since data is separated by non-letter/digits use \W+ instead.
Then, escape the dot, and make it optional, or you're not going to match 10. Don't use .* as it will match too much (regex greediness)
that yields more or less what you're looking for (note that matching strict numbers, integers or floats, is trickier than that, so this isn't perfect):
rule2 = re.compile(r"\b(\d+[ym])\W+([0-9]+\.?[0-9]*)\b")
a_str = " ".join(a)
OUT2 = re.findall(rule2, a_str)
print(OUT2)

[('3y', '15.6'), ('5y', '10')]


text:
Q: Asymptotic notations and inequalities Suppose that we have two implicit functions
$$f(t)=\log\frac{t}{2}+O\left(\frac{1}{t}\right),\,
g(t)=\log t+O\left(\frac{1}{t}\right).$$
Let $z(t)$ be a function such that $f(t)< z(t) < g(t)$, when $t$ is sufficiently large.
Can the last inequalities be replaced by any known asymptotic notations?
A bit more general version of my question could be "Let $g(t)-f(t)=constant+o(1)$ and $f(t)< z(t) < g(t)$, as $t\to\infty$. Can the last inequalities be expressed by any known asymptotic notations?"
The idea of my question is that the constants implied by $O$ might be different and it is confusing to write $\log\frac{t}{2}+O\left(\frac{1}{t}\right)<z(t)<\log t+O\left(\frac{1}{t}\right)$ or $\log\frac{t}{2}<z(t)+O\left(\frac{1}{t}\right)<\log t$, as $t \to \infty$.


text:
Q: how the html tag is placed outside the query while or foreach I show my sql data in the horizontalTab.
The Groups and subgroups from the database on the left and far right.
But I do not know why html tags just show my query.
Please help how the html tag is placed outside the query while or foreach

sample

                  sample

and my query

    <?php
      $sql = "SELECT * FROM category";
      $query = $db->prepare($sql);
      $query->execute();
      $row = $query->fetchAll(PDO::FETCH_ASSOC);

      foreach ($row as $rs) { ?>

<?php echo $rs['name'] ?>
            <?php
            $sql = "SELECT *
                    FROM `sub-category`
                    WHERE catid = '".$rs['id']."'";
            $query = $db->prepare($sql);
            $query->execute();
            $subcat = $query->fetchAll(PDO::FETCH_ASSOC);

            foreach ($subcat as $row2) { ?>

                  <?php echo $row2['name'] ?>

            <?php } ?>

      <?php } ?>


text:
Q: Login with Curl on this website I try to log on this website with curl but I got a problem (or much more) nothing happen, I don't get any data...
$urlRef ='grossiste-informatique.com/grossiste/detail_article_popup.php?code_article='. $s['reference'];

$urlLogin = 'grossiste-informatique.com/grossiste/auth_process.php';

$username = 'xxxxxx';
$password = 'xxxxxx';

$ch = curl_init($urlRef);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);

$cl = utf8_encode(curl_exec($ch));


text:
Q: Font Face Issue in IE9 I am using font face "Rockwell Regular". Every browser shows it fine but IE9 is not showing it. I converted the font face here http://www.font2web.com/.
Here is the demo link http://jsfiddle.net/daLQ3/
Please help me.

A: I solved it, Here is the demo link http://jsfiddle.net/daLQ3/1/