text:
Q: How do I get C to exit the program if any of these three statements are true?But after all three statements have been processed? Trying to get the program to exit if any of the three if statements are true, but only after all three have been processed. I have formatted this a number of ways but I can only get it to exit after each statement, not after all three. So basically it will continue on with the rest of the functions even if two of the if statements are true.
 int getValues(float* loan, float* rate, int* years)
 {

//Prompt the user for the loan amount, the yearly interest rate, and the loan length in years, then make sure each value is large enough

  printf("Enter a loan amount (dollars and cents):         ");
  scanf("%f", loan);
  printf("Enter a yearly interest rate (ex. 2.5 for 2.5%): ");
  scanf("%f", rate);
  printf("Enter the loan length in years (integer number): ");
  scanf("%d", years);
   if (*loan < 1)
       printf("\nStarting amount must be at least one dollar.\n");

   if (*rate < .1)
       printf("Interest rate must be at least .1%.\n");

   if (*years < 1)
   {   printf("Number of years must be at least 1.\n");
       exit (100);
   }

  return(0);
}

This is just the most recent attempt. I am extremely new to programming and am spending countless hours on this one little program.

A: You need to add a flag variable that you would set in the body of each if.  Then you would check the flag and exit if it is set.
   int flag = 0;
   if (*loan < 1) {
       printf("\nStarting amount must be at least one dollar.\n");
       flag = 1;
   }
   if (*rate < .1) {
       printf("Interest rate must be at least .1%.\n");
       flag = 1;
   }
   if (*years < 1) {
       printf("Number of years must be at least 1.\n");
       flag = 1;
   }
   if (flag) {
        exit(100);
   }

A: Use a flag for this, it's an easy way to keep track of a specific condition being met, when you don't want to immediately act on it.
int flag = 0;
if (*loan < 1)
{
    printf("\nStarting amount must be at least one dollar.\n");
    flag = 1;
}

if (*rate < .1)
{
    printf("Interest rate must be at least .1%.\n");
    flag = 1;
}

if (*years < 1)
{
    printf("Number of years must be at least 1.\n");
    flag = 1;
}

if(flag == 1)
{
    exit(100)
}

A: I would have a boolean variable that initializes to false, and then when a condition is hit, set to true.  Then it's a simple boolean check at the end.
int getValues(float* loan, float* rate, int* years)
{
  int shouldExit = 0;
  //Prompt the user for the loan amount, the yearly interest rate, and the loan length in years, then make sure each value is large enough

  printf("Enter a loan amount (dollars and cents):         ");
  scanf("%f", loan);
  printf("Enter a yearly interest rate (ex. 2.5 for 2.5%): ");
  scanf("%f", rate);
  printf("Enter the loan length in years (integer number): ");
  scanf("%d", years);
  if (*loan < 1){
   shouldExit = 1;
   printf("\nStarting amount must be at least one dollar.\n");
  }
  if (*rate < .1){
   shouldExit = 1;
   printf("Interest rate must be at least .1%.\n");
  }
  if (*years < 1)
  {   printf("Number of years must be at least 1.\n");
      shouldExit = 1;
  }

  if (shouldExit == 1){
      exit (100);
  }

  return(0);
}

A: int errors = 0;
if (*loan < 1) {
       printf("\nStarting amount must be at least one dollar.\n");
       errors = 1;
}
..

like the above set variable errors or anything to become 1. later check and exit.
..


text:
Q: Calculate running balance I found below query to calculate running balance.
SELECT intId, varName, decAmt, charCrDr,
       SUM(CASE WHEN charCrDr = 'c' THEN
               decAmt
           ELSE
              decAmt * -1
           END )
           OVER (PARTITION BY varName ORDER BY intId) As decTotal
FROM #Temp;

I would like to know what it means by else condition

A: This is a crude way of doing the SUM OR DIFFERENCE operation:
Here what you are trying to do is to find the difference for decAmt like below:
decAmt(where charCrDr = 'c') - decAmt

A: decAmt * -1 multiplies the value of decAmt by -1 so that if it is positive it becomes negative number if it is negative it becomes positive number

A: Actually it's about the Credit(Cr) and Debit(Dr). The running balance is:
sum of Credits - (sum of Debits)

So the decAmt for debit records (in the ELSE part, that is WHEN charCrDr != 'c') are multiplied by -1 to maintain the above formula.
Good Luck.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How could you manually add write permissions in Android manifest if visual studio generates it? I have came up with an issue where my phone used Android 10 OS and the API 29 doesn't grant permission with current runtime method for writing in from in the internal storage
So I have found that there is a   need to use an old permission for writing in the storage,but since visual studio automatically generated the manifest file I can't really enable it,also tried using the attributes in the Main activity but it doesn't seem to work

A: As documented in Working with the Android Manifest,
you create an AndroidManifest.xml in your Android project's Property folder.
Visual Studio merges what you put there, into the final AndroidManifest.xml that it creates in bin/Debug or Release folder.


text:
Q: Is it possible to set different screen resolutions for users in Win7? I have a htpc connected to the TV at a 1920x1080 resolution. When I connect to it via vnc or remote desktop from my main computer (1680x1050), the window is too big. Is it possible to create a user on the HTPC with this resolution, and use that one for the connections?

A: With RDP, you can specify the resolution in the program itself.
When you open RDP, click on the "Show Options" button, then navigate to the 'Display' tab.
Once there, you can set the resolution when you connect to the other computer.
This won't require a separate user account.
As for VNC, I don't use it myself so I don't know specifically, but this seems to be pretty simple and easy: https://pods.iplantcollaborative.org/wiki/display/atmman/Changing+Screen+Resolution+for+the+VNC+Viewer


text:
Q: How to convert empty list to None value I need to check if list is empty or Not if empty i need to pass None . I need to extract values from the dictionary
Below is my output of dictionary
    d = {
        'Business': []
    }

I am extracting the values from the dictionary for so many ids. I just need None to added to list if list is Null
Expected out is is like below since I could not find any values corresponds to Business Key
    d = {
        'Business': [None],
    }

A: You can use dict comprehension like this -
{ k: v or [None]  for k, v in d.items()}

O/P: {'Business': [None]}

A: parsed_dict = {key : None if not value else value for key, value in output_dict.items()}

A: You can convert like this:
if d['Business']==[]:
   d['Business'].append(None)

A: for key, value in d.iteritems():
    if value == []:
        d[key] = None


text:
Q: Silverlight: Can't force update of binding to collection via INPC? Say I have a ListBox that is bound to an observable collection on my view model, where the data item is a simple class that has a Name and a Value property.
When I add or remove items from the view model collection, the ListBox updates automatically as I would expect.
However, if I change the name of a data item, I want the ListBox to refresh as well, so I raise a property change for the view model property that exposes the observable collection after I've updated the name in code. The ListBox won't update however.
It's as if the binding is saying, well, the object you're giving me (the collection itself) is the same as the last one I had, so it hasn't really changed, has it? Silly programmer, telling me to refresh when I don't need to!
There are only a couple of ways I have found to work around this issue:

*

*Raise an explicit Reset notification from the collection itself (requires subclassing of ObservableCollection to do this)

*Recreate the list using a new observable collection, then raise the property change - the collection object is different now so the binding updates

Neither of these two ways are ideal, although the first method is definitely preferable - it really shouldn't be this hard to get a listbox to update!
Can anyone explain why bindings work this way, and if there is any way to change the behaviour so that the binding will always update on a property change notification, regardless of whether the source has changed or not?

A: It sounds to me like the items within your ObservableCollection do not implement INotifyPropertyChanged. You need to do this, so that when you change the Name property of an item in the collection, the UI is updated. From your description, the framework and your bound collection are working exactly as the should.


text:
Q: CKAN Filedownload with API ive set up a ckan-server with all necessary plugins.
There is some content on the server (.csv-files).
Now id like to download a specific .csv-file to change it locally and upload it again.
But I dont have an idea how to download the complete file with the ckan-API.
Can someone help me?

A: The package_show API call will tell you the URL for the CSV so that you can download it.
e.g. this dataset: http://data.gov.uk/dataset/uk-open-access-non-vosa-sites
is available on the API at: http://data.gov.uk/api/action/package_show?id=uk-open-access-non-vosa-sites
which results in something like:
{
  "help": "http://data.gov.uk/api/3/action/help_show?name=package_show",
  "success": true,
  "result":
  {
    "name": "uk-open-access-non-vosa-sites",
    "license_title": "UK Open Government Licence (OGL)",
    "resources": [
        {
            "description": "A list of Authorised Testing Facilities (ATFs) and DVSA test stations ",
            "format": "CSV",
            "url": "http://dft.gov.uk/vosa/images/Find%20your%20nearest%20ATF%20or%20VOSA%20test%20station.csv",
            "id": "bd9aaa9f-2a9c-45f8-8246-6b99dd78208a",
            "resource_type": "file",
        }
    ]
  }
}

from which you can see the url is http://dft.gov.uk/vosa/images/Find%20your%20nearest%20ATF%20or%20VOSA%20test%20station.csv which you can download e.g. using wget:
wget http://dft.gov.uk/vosa/images/Find%20your%20nearest%20ATF%20or%20VOSA%20test%20station.csv


text:
Q: Webgrid disappear while clicking pagination in MVC3 I have a grid as a partialview in my main cshtml.When i click page number in the gird,the grid is disappearing. any suggestion?
Devices.csthml(partialview)
Even i have div my-grid in the partial view.

    @{

        var grid = new WebGrid(
                               canPage: true,
                               canSort: true,
                             rowsPerPage: 3,
                             ajaxUpdateContainerId: "my-grid");

            grid.Bind(Model, rowCount: Model.Count(), autoSortAndPage: true);

        @grid.GetHtml(
        htmlAttributes: new { id = "my-grid" },
        tableStyle: "grid1",
        headerStyle: "header",
        rowStyle: "row",
        footerStyle: "footer",
        alternatingRowStyle: "altRow",
        columns: grid.Columns(
                                grid.Column("ObjectOfServiceName", "Device Name", style: "textCol"),
                                grid.Column("SerialNumber", "Serial Number", style: "textCol"),
                                grid.Column("ContractIdentifier", "Contract Identifier", style: "textCol"),
                                grid.Column("ServiceLevelCode", "Service Level", style: "textCol"),
                                grid.Column("UserDeviceDescription", "Device Grouping", style: "textCol"),
                                grid.Column(header: "", format: @<text>@Html.ActionLink("Upgrade", "DeviceUpgradePartial", new { objectOfServiceId = item.ObjectOfServiceId, serviceContractId = item.ServiceContractId, serialNumber = item.SerialNumber, objectOfServiceName = item.ObjectOfServiceName, serviceLevelId = item.ServiceLevelId, deviceGroupingId = item.DeviceGroupingId }, new { @class = "upgradeLink", title = "Upgrade Device" })" </text>, style: "colOperation"),
                                grid.Column(header: "", format: @<text>@Html.ActionLink("Update", "DeviceUpdatePartial", new { objectOfServiceId = item.ObjectOfServiceId, serviceContractId = item.ServiceContractId, serialNumber = item.SerialNumber, objectOfServiceName = item.ObjectOfServiceName, serviceLevelId = item.ServiceLevelId, deviceGroupingId = item.DeviceGroupingId }, new { @class = "updateLink", title = "Update Device" })" </text>, style: "colOperation"),
                                grid.Column(header: "", format: @<text>@Html.ActionLink("ReassignDeviceGroup", "ReassingDeviceGroupingPartial", new { objectOfServiceId = item.ObjectOfServiceId, serviceContractId = item.ServiceContractId, serialNumber = item.SerialNumber, objectOfServiceName = item.ObjectOfServiceName, serviceLevelId = item.ServiceLevelId, deviceGroupingId = item.DeviceGroupingId }, new { @class = "reassingDeviceGroupLink", title = "Update Device" })" </text>, style: "colOperation")

                            ), mode: WebGridPagerModes.All)

    }

Main.cshtml:

                @using (Html.BeginForm())
                {

                    Select customer Name

                        @Html.DropDownListFor(m => m.customer_id, new SelectList(Model.customerList, "customer_id", "customer_business_name"))
                        <input type="hidden" id="hdnCustomerName" name="hdnCustomerName" />
                        <input type="hidden" id="hdnShowHideCustInfo" name="hdnShowHideCustInfo" />
                        <input type="submit" value="Go" name="Go" id="Go" />

                }

        @if (Model.objectOfServiceListDevice != null)
        {
            @Html.Partial("Devices", Model.objectOfServiceListDevice)
        }

A: I would try replacing this:
@if (Model.objectOfServiceListDevice != null)
{
    @Html.Partial("Devices", Model.objectOfServiceListDevice)
}

With this:

    @Html.Partial("Devices", Model.objectOfServiceListDevice)


text:
Q: Map or flattenMap in ReactiveCocoa I'm new to ReactiveCocoa. How do I know when should I use map: or flattenMap: ? And How do I know whether it is a stream-of-streams or a regular stream? Here I got some code which I can't understand:
- (RACSignal *)signInSignal {
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [self.signInService signInWithUsername:self.usernameTextField.text
                                      password:self.passwordTextField.text
                                      complete:^(BOOL success) {
                                          [subscriber sendNext:@(success)];
                                          [subscriber sendCompleted];
                                      }];
        return nil;
    }];
}

This method return a stream-of-streams. But why? Can anyone explain it for me? Thanks!

A: Use the map operator when you want to intercept whenever a Signal sends a value and have the opportunity to alter that value or send a completely different value. A way to think about this is a production line that passes partially completed products down the line. There are various points on the production line where a line operator will pick the product and screw something in or alter it in some way.
Flatten map is for when you might want to inject another Signal into some other signal that depends on the initial signal. You can therefor use the initial signal to effect or determine the signal returned. This is one of the ways you can take one or more signals and join them in a way that results in one signal. Hence the terminology: flatten. The other slightly different ways you can do this in RAC is merge: and switchToLatest() to name a few. Imaging you had a signal that did a network fetch based on a particular search query. Then imagine you had another signal for text typed into a search box. In order to do a search request based on the current search query in the searchText signal you could use a flatten map.
self.searchTextSignal.flattenMap({(object: AnyObject!) -> RACSignal! in
    if let searchQuery: String = object as? String {
        return self.networkFetchSignal(query: searchQuery)
    }
    return RACSignal.empty()
}).subscribeNext({(object: AnyObject) -> Void in
   //the results
})

A: For the map or flattenMap question, I would like to quote the comment from this:
https://github.com/ReactiveCocoa/ReactiveCocoa/issues/448#issuecomment-34977600


text:
Q: PL/SQL Oracle Package error when executing functions The package compiles well, but when executing the functions, it gives the following error "'SEARCH FOR_EMP_NO' is not a procedure or has not been defined" what is the problem? I think I am committing some problem with the ver_emple procedure. I have to pass the record to it to display an output text as in the example and I don't know how to do it.
/* Cabecera o especificación del paquete */
CREATE OR REPLACE PACKAGE buscar_emple2
  AS
  TYPE t_reg_emple IS RECORD(emp_no emple.emp_no%TYPE,
                              apellido emple.apellido%TYPE,
                              oficio emple.oficio%TYPE,
                              salario emple.salario%TYPE,
                              dept_no emple.dept_no%TYPE
                              );

  FUNCTION busca_por_emp_no(v_num_emple emple.emp_no%TYPE)
  RETURN t_reg_emple;

  FUNCTION busca_por_ape(v_apellido emple.apellido%TYPE)
  RETURN t_reg_emple;

  PROCEDURE ver_emple;
END buscar_emple2;

/* Cuerpo del paquete */
CREATE OR REPLACE PACKAGE BODY buscar_emple2
AS
vg_emple t_reg_emple;

FUNCTION busca_por_emp_no(v_num_emple emple.emp_no%TYPE)
RETURN t_reg_emple
  IS
  BEGIN
    SELECT emp_no, apellido, oficio, salario, dept_no
    INTO vg_emple
    FROM emple
    WHERE emp_no = v_num_emple;
    RETURN vg_emple;
    ver_emple;
END busca_por_emp_no;

FUNCTION busca_por_ape(v_apellido emple.apellido%TYPE)
RETURN t_reg_emple
  IS
  BEGIN
    SELECT emp_no, apellido, oficio, salario, dept_no
    INTO vg_emple
    FROM emple
    WHERE apellido = v_apellido;
    RETURN vg_emple;
    ver_emple;
END busca_por_ape;

  PROCEDURE ver_emple
    IS
    BEGIN
    DBMS_OUTPUT.PUT_LINE(vg_emple.emp_no|| '=======' ||vg_emple.apellido|| '=======' ||
                         vg_emple.oficio|| '=======' ||vg_emple.salario|| '=======' ||vg_emple.dept_no);
    END ver_emple;

END buscar_emple2;

EXECUTE buscar_emple2.busca_por_emp_no(7839);

EXECUTE buscar_emple2.busca_por_ape('SALA');

A: The output you have shared is the desired output, not the actual one you got. Running error messages through a translator is fine but note that some of it won't make any sense if you translate names of thing that haven't been translated in your actual code.

Edit- Second attempt at guessing from your translated error.
You have defined busca_por_emp_no as a FUNCTION not a procedure. In order to execute it you have to return it into something. You've defined it so that it returns a custom type. You would either change it's definition to be a procedure (with no return clause) or call it like you would a function:
declare
  myVar buscar_emple2.t_reg_emple;
begin
  myVar := buscar_emple2.busca_por_emp_no(7839);
end;
/

(This was my first guess as this was most striking about your code)
Your problem is you didn't actually send the PL/SQL packages to the databases to compile, you must end both the package specification and the package body definitions with a /
e.g
CREATE OR REPLACE PACKAGE buscar_emple2
  AS
  TYPE t_reg_emple IS RECORD(emp_no emple.emp_no%TYPE,
                              apellido emple.apellido%TYPE,
                              oficio emple.oficio%TYPE,
                              salario emple.salario%TYPE,
                              dept_no emple.dept_no%TYPE
                              );

  FUNCTION busca_por_emp_no(v_num_emple emple.emp_no%TYPE)
  RETURN t_reg_emple;

  FUNCTION busca_por_ape(v_apellido emple.apellido%TYPE)
  RETURN t_reg_emple;

  PROCEDURE ver_emple;
END buscar_emple2;
/

/* Cuerpo del paquete */
CREATE OR REPLACE PACKAGE BODY buscar_emple2
AS
vg_emple t_reg_emple;

FUNCTION busca_por_emp_no(v_num_emple emple.emp_no%TYPE)
RETURN t_reg_emple
  IS
  BEGIN
    SELECT emp_no, apellido, oficio, salario, dept_no
    INTO vg_emple
    FROM emple
    WHERE emp_no = v_num_emple;
    RETURN vg_emple;
    ver_emple;
END busca_por_emp_no;

FUNCTION busca_por_ape(v_apellido emple.apellido%TYPE)
RETURN t_reg_emple
  IS
  BEGIN
    SELECT emp_no, apellido, oficio, salario, dept_no
    INTO vg_emple
    FROM emple
    WHERE apellido = v_apellido;
    RETURN vg_emple;
    ver_emple;
END busca_por_ape;

  PROCEDURE ver_emple
    IS
    BEGIN
    DBMS_OUTPUT.PUT_LINE(vg_emple.emp_no|| '=======' ||vg_emple.apellido|| '=======' ||
                         vg_emple.oficio|| '=======' ||vg_emple.salario|| '=======' ||vg_emple.dept_no);
    END ver_emple;

END buscar_emple2;
/

You should receive a message if they were able to be compiled successfully, if it errored then check the compilation error and fix that.
show errors

Is the command to get errors if you receive a compilation error. I'm not going to create my own tables just to check if you don't have other typos in your code.


text:
Q: Maven: getting jar file with merged name In my web application, I got 2 jars whose name is merged with group id, artifact id and version as below.
org.springframework.security-spring-security-core-4.0.2.RELEASE.jar
org.springframework-spring-security-core-4.0.2.RELEASE.jar
I tried to find it using dependency:tree, but could not find why it is happening.
How to resolve this, how can I find how this jar coming to my target\web-x.x.x\WEB-INF\lib folder.
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T13:28:13+05:30)
Java version: 1.8.0_152, vendor: Oracle Corporation
OS name: "windows 7", version: "6.1", arch: "amd64", family: "windows"


text:
Q: mysqldump issues with DreamHost Background:

*

*I sought to rename a database on Dreamhost web hosting VPS account.

*I also wanted to rename a database user for the database to be created above.

*I followed the approached detailed at ServerFault

*I used mysqldump to create a backup of the old database (<1MB) as a *.sql file.

*I created a new database with a desired name within the DreamHost CPanel.

*I created a new database user within the DreamHost CPanel (not via the linux command console) to have access to the new database.

*I imported (via linux command console) the *.sql (from mysqldump) as the new desired database.

*I did not drop the old database - as I wanted to be sure that everything was alright before I drop the old database (and edit related scripts pointing to that old database).

Yet upon checking my DreamHost CPanel,

*

*the size of the new database was not recognised.

*the new database user had access to the new database as expected (this was tested via phpMyAdmin).

Furthermore

*

*As expected phpMyAdmin does not show me the new database when I logged in with old user details.

*As expected phpMyAdmin recognises the new database when I logged in with the new user details.

*phpMyAdmin recognises the size of the new database.

*phpMyAdmin shows that there is difference in size between the old and new database (I thought this is supposed to be the same size since its a backup).

*I briefly checked the database structure (in phpMyAdmin) and noticed that the difference is coming from the table property "column" known as "Overhead".

*The Old database has Overheads in a few tables while the mysqldump file does not have any overheads.

Question:

*

*How come the difference in size

*Home come the DreamHost CPanel reports that size is unavailable

*What does Overhead even mean

Any help would be appreciated


text:
Q: Как правильно оформить запрос Mysql? Есть запрос, он вытаскивает из таблички данные по двум условиям, по дате  и по коду абонента:
$query = "SELECT * FROM selling WHERE DATE_FORMAT(TransactionDatetime, '%Y-%m') = '2012-$mons' AND CardGroupMemberKey='$enum'"; (РАБОТАЕТ)

Как правильно добавить третье условие? Например, я хочу выбирать по дате, по коду, и по адресу.
Пробовал так:
$query = "SELECT * FROM selling WHERE DATE_FORMAT(TransactionDatetime, '%Y-%m') = '2012-$mons' AND CardGroupMemberKey='$enum' AND CardType='$org'";(НЕ РАБОТАЕТ)

A: вынесено из комментариев.

возможно, в значении $org есть кавычки, которые и «портят» запрос.
вообще значение переменных желательно обернуть чем-нибудь типа mysql_real_escape_string().


text:
Q: Webservice Design - intermediate webservice between a external webservice and clients My requirement is to develop a webservice that will act as middle man between a external webservice and clients.
I know, I can design a wsdl for my service and then map the external wsdl to my wsdl in the code. My question is there a open source api/tool out there to do this mapping.
This way it will be easier switch to different webservice in the future
will appreciate your thougts

A: A simple mapping may not be the most appropriate. An abstraction of the external web service may be more appropriate.
For instance:

*

*Your internal consumers may not need to use all of the functions of the external web service. Your internal service can hide the additional functions from them.

*The external service may require operations to be called in a particular order, or may require that a session identifier be passed from one call to another. There is no reason for your internal callers to know about this.

*Your internal callers have particular business requirements in mind. Your intermediate service could have a WSDL written in terms of these business requirements, and could then call the external service as necessary to satisfy these business requirements. Your internal callers would have the complexities and oddities of the external service hidden from them.

*The external service might use different naming conventions from your internal standards.  It can be annoying at best for your internal callers to need to understand the abbreviations, terminology and even upper/lower-case patterns of the external service. You can hide all of this from your internal callers.


text:
Q: Why I don't get conflict when switching branch with uncommitted changes? Let's say I'm working on a master branch that has file colors.txt:
blue
red
yellow

From there I create and switch to a new branch warm and edit the same file colors.txt to:
red
yellow
orange

I don't add those changes to Staging Area, but rather switch back to master branch => GIT doesn't complain.
What I expected instead is message: "Please commit your stages or stash them before you switch branches".
Can someone tell me how did this example succeed and why am I not getting that error message I just described?

A: The message you expect would only occur if your changes could not be applied to the master branch because it conflicts.
Otherwise uncommited changes do are kept when switching branches.
The important thing is you will never loose the changes, either you will be asked to commit/stash them before switching branch or they will be kept in the branch you switch to.


text:
Q: Could not find X11 fonts in R when plot
the question is that when I tried to
plot(1,1)
it returns

Error in axis(side = side, at = at, labels = labels, ...): could not find any X11 fonts
Check that the Font Path is correct.
Traceback:
1. plot(1, 1)
2. plot.default(1, 1)
3. localAxis(if (is.null(y)) xy$x else x, side = 1, gap.axis = xgap.axis, ...)
4. Axis(...)
5. Axis.default(...)
6. axis(side = side, at = at, labels = labels, ...)

So I checked the following information:
sessionInfo()
R version 4.0.3 (2020-10-10)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: CentOS Linux 7 (Core)

Matrix products: default
BLAS:   /newdatc/home/*/bin/r_base/lib64/R/lib/libRblas.so
LAPACK: /newdatc/home/*/bin/r_base/lib64/R/lib/libRlapack.so

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] dplyr_1.0.7               patchwork_1.1.1
[3] ggplot2_3.3.5             stxBrain.SeuratData_0.1.1
[5] SeuratData_0.2.1          SeuratObject_4.0.2
[7] Seurat_4.0.4

loaded via a namespace (and not attached):
  [1] nlme_3.1-152          spatstat.sparse_2.0-0 matrixStats_0.60.1
  [4] RcppAnnoy_0.0.19      RColorBrewer_1.1-2    httr_1.4.2
  [7] repr_1.1.3            sctransform_0.3.2     tools_4.0.3
 [10] utf8_1.2.2            R6_2.5.0              irlba_2.3.3

capabilities("X11")
X11: TRUE

names(X11Fonts())
'serif'
'sans'
'mono'
'Times'
'Helvetica'
'CyrTimes'
'CyrHelvetica'
'Arial'
'Mincho'

getOption('X11fonts')
NULL
names('X11fonts')
NULL
And in fact I also tried add export LC_ALL=en_US.UTF-8
but did not work.
So any advice is appreciated!!!

A: I chose to write
library(showtext)
showtext_auto()
before every script.


text:
Q: Why does my counting sort algorithm not sort at all? #include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void SortCount(vector<int>& vec){
    int max_el = *max_element(vec.begin(), vec.end());

    vector<int> C(max_el+1, 0);
    vector<int> B(vec.size(), 0);

    for(int i = 0; i < vec.size(); i++){
        C[vec[i]] = C[vec[i]] + 1;
    }
    for(int i = 1; i <= vec.size(); i++){
        C[i] = C[i] + C[i - 1];
    }
    for(int i = 0; i < vec.size(); i++ ) {
        B[C[vec[i]] - 1] = vec[i];
        C[vec[i]] = C[vec[i]] - 1;
    }
    for(int i=0; i<vec.size(); i++){
        vec[i] = B[i];
    }
}

int main() {

    vector<int> vec {5,2,43,31,67,311};
    SortCount(vec);

    for (size_t i=0;  i <vec.size();  i++) {
        cout<<vec[i]<<" ";
    }

    return 0;
}

I did exactly by the book but for some reason it just prints out the values in the same orders they were placed in. Where did I mess up?
Edit: I added the main function

A: Your iteration over the count array has the wrong bounds:
//for(int i = 1; i <= vec.size(); i++) { <--wrong
for(int i = 1; i < C.size(); i++) {
    C[i] = C[i] + C[i - 1];
}

Also you should get in the habit of using std::size_t as a type for an index instead of int. int is both too small and also is signed, so it is unsuited for indices.


text:
Q: PHP CURL shows no "content_type" with Basic Auth The same code works ok in two enviroments (localhost and local develop) but not in the 3rd (prod). The 3rd is a VPS. I have to use basic auth with the API that I'm connecting.
This is my code:
$curl = curl_init();
//For basic auth
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "SomeUsername:AndItPass");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
));
$result = curl_exec($curl);
dump($curl);die();

The output of dump($curl);die(); when works ok (like in localhost) is:
curl resource @61 ▼
  url: "http://XXXXX:8089/api/usuarios/login?perfil=2&rutPoem=76279543&rut=18863583"
  content_type: "application/json; charset=utf-8"
  http_code: 200
  header_size: 259
  request_size: 194
  filetime: -1
  ssl_verify_result: 0
  redirect_count: 0
  total_time: 0.022104
  namelookup_time: 3.9E-5
  connect_time: 0.008342
  pretransfer_time: 0.008463
  size_upload: 0.0
  size_download: 251.0
  speed_download: 11355.0
  speed_upload: 0.0
  download_content_length: 251.0
  upload_content_length: -1.0
  starttransfer_time: 0.022072
  redirect_time: 0.0
  redirect_url: ""
  primary_ip: "XXXXXXXX"
  certinfo: []
  primary_port: 8089
  local_ip: "192.168.4.108"
  local_port: 64594
}

But in the VPS I got this:
curl resource @345 ▼
  url: "http://XXXXX:8089/api/usuarios/login?perfil=2&rutPoem=76279543&rut=18863583"
  content_type: null
  http_code: 0
  header_size: 0
  request_size: 0
  filetime: -1
  ssl_verify_result: 0
  redirect_count: 0
  total_time: 0.200986
  namelookup_time: 0.000126
  connect_time: 0.0
  pretransfer_time: 0.0
  size_upload: 0.0
  size_download: 0.0
  speed_download: 0.0
  speed_upload: 0.0
  download_content_length: -1.0
  upload_content_length: -1.0
  starttransfer_time: 0.0
  redirect_time: 0.0
  redirect_url: ""
  primary_ip: ""
  certinfo: []
  primary_port: 0
  local_ip: ""
  local_port: 0
}

What is happening? I have "null" if I do a dump(curl_error($curl));

A: As discussed in the comments of your question, looks to me like your IP is blocked. You can check that with loading a proxy inside your cURL request. If the request is not blocked then that means your server IP is blacklisted by the server firewall. You can ask the API owner to unblock your IP but also make sure you understand how you got blacklisted in the first place in order to make your app compliant with the remote server rules.


text:
Q: Fixing .lnk files in Windows 8 How can I fix .lnk file association in Windows 8?
I can see how to do it for Windows 7 (How to reset shortcuts (.lnk file)  in Windows 7?), but am not sure if the solution will be the same. I don't want to mess with the registry unless I know it's going to work!

A: Here you can find the fix damaged file association in Windows 8. Open the zip and import the .reg file for the lnk.


text:
Q: How to transfer a save in candy box 1 from the iPad to the PC? I took some advice from someone and I can't figure out how to transfer a save from my iPad to my PC to beat the hell level.

A: From your ipad, on the main page, click the save button and take note of the given code.
Then browse to: http://candies.aniwey.net/index.php?pass=[your_code] -- where you replace the the insides of the brackets with the code you received.
e.g. http://candies.aniwey.net/index.php?pass=12345


text:
Q: Minimum size that matches aspect ratio I need to find the minimum size that has an aspect ratio of exactly (or within 0.001) some value. Are there any quick math tricks or framework tricks for doing this?
Here's the pseudo code for the current bad idea I had running in O(n^2):
epsilon = 0.001;

from x = 1 to MAX_X
{
  from y = 1 to MAX_Y
  {
    if(Abs(x / y - aspectRatio) <= epsilon)
    {
      return new Size(x, y);
    }
  }
}
return Size.Empty;

A: Unusual.  You need to find the greatest common divisor and divide width and height by it.  The algorithm is by Euclid and is two thousand three hundred years old.  Details are here.

A: You can write aspectRatio as a fraction (if you want it up to a presicion of 0.001, than you can use round(aspectRatio,3)/1000 )
Then, simplify this fraction. The resulting fraction is the x/y you're looking for.

A: A quicker way, but still not formulaic would be to only look at possible y values instead of iterating up to MAX_Y.  e.g.:
    static Size FindMinSize(double requiredRatio, double epsilon)
    {
        int x = 1;
        do
        {
            int y = (int)(x * requiredRatio);
            if (Test(x, y, requiredRatio, epsilon))
            {
                return new Size(x, y);
            }

            y = (int)((x + 1) * requiredRatio);
            if (Test(x, y, requiredRatio, epsilon))
            {
                return new Size(x, y);
            }
            x++;
        } while (x != int.MaxValue);

        return new Size(0, 0);
    }

    static bool Test(int x, int y, double requiredRatio, double epsilon)
    {
        double aspectRatio = ((double)y)/x;
        return Math.Abs(aspectRatio - requiredRatio) < epsilon;
    }

A: Instead of testing all possible combinations, just increase the side that gets you closer to the aspect ratio:
public static Size GetSizeFromAspectRatio(double aspectRatio) {
  double epsilon = 0.001;
  int x = 1;
  int y = 1;
  while (true) {
    double a = (double)x / (double)y;
    if (Math.Abs(aspectRatio - a) < epsilon) break;
    if (a < aspectRatio) {
      x++;
    } else {
      y++;
    }
  }
  return new Size(x, y);
}

A: The aspect ratio is the ratio between x and y.  You can define the aspect ratio as x / y or y / x.
The minimum aspect ratio is 0 / 0.
Some other minimum has to be defined, either a minimum x or a minimum y.
min x = (min y * x) / y
min y = (min x * y) / x


text:
Q: how to make an .jsp invoke a method using eclipse Google app engine hello iam having problem invoking function in my project ![enter image description here]
<form action="register" method="post">

        UserID:	<input type="text" name="Id">

        Name :	<input type="text" name="name">

        Password	<input type="password" name="pass">

         <input type="button"  value="sumbitk">

    </form>

$
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
                    throws IOException {
            resp.setContentType("text/plain");
            resp.getWriter().println("Hello, world");
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                    throws IOException, ServletException {
        //RequestDispatcher dispatcher;
        String id=req.getParameter("id");
        String name=req.getParameter("name");
        String password=req.getParameter("pass");
        System.out.println("user id : "+id+" name    "+name+" pass "+password);
        resp.sendRedirect("/index.html");
        //dispatcher=getServletContext().getRequestDispatcher("/index.html");
        //dispatcher.forward(req, resp);
    }

}
i made form action on register and calls function post but it not seems to work when i click sumbit i dont know why .

A: First try write "submit" correctly in last input, if don't work try chage the type of last input to "submit" instead "button"


text:
Q: Form in Delphi DLL causes access violations and/or crashes when updated in a loop I'm writing a DLL (Delphi 2010) which contains a form with a Stringgrid and a RichView component. The DLL obtains data from a host app, which is actually a script running inside a paxCompiler engine.
The Stringgrid and RichView inside the DLL are constantly refreshed in a loop.
The problem is that, if we update the components on a DLL form too often (or just wait for a while), an access violation (c0000005) will happen and/or the app will crash.
I.e. if we write
if MilliSecondsBetween(Now, MyStart) > 10

istead of
if MilliSecondsBetween(Now, MyStart) > 500

the app will crash instantly. With 500 ms delay it will work for some time, from several minutes to several hours.
If we use the RichView component, the app will crash much faster. (I know it's my code, not RichView.) It usually says 'canvas does not allow drawing' and 'invalid pointer operation' before it crashes.
If we move mouse over the RichView for a while we will almost definitely get a crash/AV. This may be somehow related to repainting of the form and mouse cursor.
Most of my code (both in host app and inside dll) is wrapped in try...except clauses, but the host app crashes anyway.
Here's some code. Some parts of the code are omitted to simplify reading.
Any help will be highly appreciated.
Host app:
uses Forms, StdCtrls, SysUtils, Classes;

type
  TMyEvents = class(tobject)
    procedure MyButtonClick (Sender : tobject);
  end;

type
  TMyForm = class(TForm)
  private
  protected
  public
  end;

type
  TDataInfo = packed record
    Data1 : string[16];
    Data2: string[16];
    Data3: string[16];
  end;

type
  TDataArray = Array [0..1999] of TDataInfo;
type
  PDataArray = ^TDataArray;

var MyForm : TForm;
  MyButton : TButton;
  MyEvents : TMyEvents;
  initForm : boolean;

  A : TDataArray;
  PA : PDataArray;

procedure CreateDllForm; register; external 'FormDLL.dll';
procedure ShowDllForm; register; external 'FormDLL.dll';
procedure WriteHandle (S : PCardinal); register; external 'FormDLL.dll';
procedure ExportedProc1 (X1 : PDataArray; Y1 : Cardinal); register; external 'FormDLL.dll';
procedure ExportedProc2; register; external 'FormDLL.dll';
procedure DestroyDllForm; register; external 'FormDLL.dll';

procedure MainProc;
  begin

    MyEvents := TMyEvents.Create;

       // ********************************************
       // THIS FORM IS AUXILARY AND WE DON'T ACTUALLY USE IT.
       // IT IS NEEDED ONLY TO PROVIDE CORRECT BEHAVIOUR OF THE MAIN DLL FORM,
       // ********************************************

    MyForm := TMyForm.Create (nil);
    MyForm.Caption := 'Form from script';

    MyButton := TButton.Create (MyForm);
    MyButton.Show;
    MyButton.Top := 50;
    MyButton.left := 50;
    MyButton.Width := 200;
    MyButton.Height := 21;
    MyButton.Parent := MyForm;
    MyButton.Caption := 'Press me';
    MyButton.OnClick := MyEvents.MyButtonClick;

    MyForm.Show;
  end;

       // ********************************************
       // THE AUXILARY FORM CONTAINS ONLY 1 BUTTON,
       // WHICH TRIGGERS THE MAIN DLL FORM.

       // AFAIK, THIS WAS DONE TO GUARANTEE THAT
       // THE MAIN DLL FORM RUNS FROM THE MAIN THREAD.
       // ********************************************

procedure TMyEvents.MyButtonClick (Sender : tobject);
  var hWnd : PCardinal;
  begin
    try
      CreateDllForm;
      ShowDllForm;

      initForm := true;

      hWnd := PCardinal (MyForm.Handle);
      WriteHandle (hWnd);
     except
      print ('error');
    end;
  end;

procedure OnFree; //Free all objects we've created
  begin
    if assigned (MyButton) then
    begin MyButton.Free end;
    if assigned (MyForm) then
    begin MyForm.Free end;
    if assigned (MyEvents) then
    begin MyEvents.Free end;

    DestroyDllForm;
  end;

procedure UpdateGrid;
var i, CurrentCount, iCounter : integer;
  begin
    while (true) do
    begin
      Delay (100);
      if (initForm = true) then
      begin
        for i := 0 to CurrentCount do
        begin
           // some code
        end;
        iCounter := i;
        try
        ExportedProc1(@A[0], iCounter);
        except
          print ('error writing to grid');
        end;
      end;
    end;
  end;

procedure UpdateRV;
var i: integer;
begin
  try
    while (true) do
    begin
      Delay (100);
      if (initForm = true) then
        begin
         ExportedProc2;
        end;
    end;
  except
    print ('error writing rv');
  end;
end;

begin
  initForm := false;
  Script.MainProc (@MainProc);
  Script.NewThread (UpdateGrid);
  Script.NewThread (UpdateRV);
  Delay (-1);
end.

DLL:
library FormDll;

uses
  DateUtils,
  Dialogs,
  Windows,
  Forms,
  SysUtils,
  Classes,
  Grids,
  Controls,
  FormDllUnit in 'FormDllUnit.pas' {CustomForm};

{$R *.res}

type
  MyMessage = packed record
    Msg: Cardinal;
    MsgText: Widestring ;
    Result : LongInt;
  end;

type
  TDataInfo = packed record
    Data1 : string[16];
    Data2: string[16];
    Data3: string[16];
  end;

type
  TDataArray = Array [0..1999] of TDataInfo;
type
  PDataArray = ^TDataArray;

var
A: TDataArray;
MyStart: TDateTime;
MyTargetersStart: TDateTime;
myCount : integer;

procedure CreateDllForm; register; export;
begin
  CustomForm := TCustomForm.Create(nil);
  SetThreadLocale(GetSystemDefaultLCID);
  GetFormatSettings;
end;

procedure ShowDllForm; register; export;
begin

  CustomForm.Show;

// we initialize some variables here
// initializing stringgrid
end;

procedure WriteHandle(S: PCardinal); register; export;
begin
  AppHandle:=Cardinal(S);
end;

procedure ExportedProc1(myArray: PDataArray; iCount: Cardinal); register; export;
var
   i : cardinal;
   //some more variables
begin

if MilliSecondsBetween(Now, MyStart) > 500 then begin

myCount := iCount;
MyStart := Now;

  CustomForm.PlayersGrid.Rows[1].BeginUpdate;

    for i := 0 to CustomForm.PlayersGrid.ColCount - 1 do  begin
      CustomForm.PlayersGrid.Cols[i].Clear;
    end;

     // filling array A with PDataArray data from host application
     // QuickSort(A, 0, iCount -1);

   for i := 0 to iCount - 1 do begin
     //filling stringgrid with values from array A
  end;

//some code

CustomForm.PlayersGrid.Rows[1].EndUpdate;

end;

end;

procedure DestroyDllForm; register; export;
begin
  FreeAndNil(CustomForm);
end;

procedure ExportedProc2; register; export;
var x: integer;

begin
if MilliSecondsBetween(Now, MyTargetersStart) > 500 then
begin
  MyTargetersStart := Now;
  CustomForm.RichView1.Clear;
    for x := 0 to myCount-1 do
    begin
      //filling RichView1 with values from array A
    end;
  CustomForm.RichView1.Format;
end;
end;

exports
CreateDllForm,
ShowDllForm,
WriteHandle,
ExportedProc1,
ExportedProc2,
DestroyDllForm;

end.

DLL unit:
unit FormDllUnit;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, AppEvnts, ComCtrls, ExtCtrls,
  RVScroll, RichView, RVStyle, DateUtils, Grids;

type
  TCustomForm = class(TForm)
    RVStyle1: TRVStyle;
    RichView1: TRichView;
    PlayersGrid: TStringGrid;

    procedure FormClose(Sender: TObject; var Action: TCloseAction);

    procedure PlayersGridMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure PlayersGridDrawCell(Sender: TObject; ACol, ARow: Integer;
      Rect: TRect; State: TGridDrawState);
    procedure PlayersGridSelectCell(Sender: TObject; ACol, ARow: Integer;
      var CanSelect: Boolean);

  private
  public
    { Public declarations }
  end;

var
  CustomForm: TCustomForm;
  AppHandle: HWND;

implementation

{$R *.dfm}

procedure TCustomForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  SendMessage(AppHandle,WM_CLOSE,0,0);
end;

procedure TCustomForm.PlayersGridDrawCell(Sender: TObject; ACol,
  ARow: Integer; Rect: TRect; State: TGridDrawState);
var r: TRect;

begin
With TStringGrid(Sender),TStringGrid(Sender).Canvas Do
Begin
  //drawing cells with custom colors etc.
End;
end;

procedure TCustomForm.PlayersGridMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  //some code
end;

procedure TCustomForm.PlayersGridSelectCell(Sender: TObject; ACol,
  ARow: Integer; var CanSelect: Boolean);
begin
  //some code
end;

end.

A: You are breaking VCL threading rules by accessing VCL components outside the main thread. That's the first thing to fix.
There may well be more problems but you presented a lot of code and I for one don't want to debug it all. It does seem plausible that you have data races. And the data types and casting look a bit dubious.

A: Ok, I've finally found out the solution. Special thanks to David Heffernan. The following code works perfectly for me:
DLL:
procedure ShowDllForm; stdcall; export;
begin
  if CustomForm = nil then
  CustomForm := TCustomForm.Create(nil);
  CustomForm.Show;
end;

procedure ProcessFormMessages; stdcall; export;
begin
  Application.ProcessMessages;
end;

function FormShowing: Boolean; stdcall; export;
begin
  if CustomForm <> nil then
    Result := CustomForm.Showing
  else
    Result := False;
end;

procedure DestroyDllForm; stdcall; export;
begin
  FreeAndNil(CustomForm);
end;

exports
 ShowDllForm,
 ProcessFormMessages,
 FormShowing,
 DestroyDllForm;
end.

Host application:
procedure ShowDllForm; stdcall; external 'FormDLL.dll';
procedure DestroyDllForm; stdcall; external 'FormDLL.dll';
procedure ProcessFormMessages; stdcall; external 'FormDLL.dll';
function FormShowing: Boolean; stdcall; external 'FormDLL.dll';

procedure MainProc;
begin
  ShowDllForm;
  try
    repeat
      begin
        Delay(100);
        ProcessFormMessages;
      end;
    until not FormShowing;
  except
    print('error');
  end;
end;

procedure OnFree;
  begin
    DestroyDllForm;
  end;

begin
  Script.MainProc(@MainProc);
  Delay (-1);
end.


text:
Q: Execute Deployed SSIS Package from Asp.net c# I have deployed a SSIS Package. I'm executing it with a procedure.
Exec PushMannualData '0619','Jagri Pharmaceuticals','Yes','INTERNAL\Shaidar';

In SSMS, it is getting executed successfully.
I am trying to connect this with ASP.NET to execute. I have written below code in C#:
using (SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsAuthenticationSQLConnection"].ToString()))
{
    using (SqlCommand cmd = new SqlCommand("PushMannualData", Con))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@Date", SqlDbType.VarChar).Value = TextBoxDate.Text;
        cmd.Parameters.Add("@ProjectName", SqlDbType.VarChar).Value = DropDownListCompany.Text;
        cmd.Parameters.Add("@PushProduct", SqlDbType.VarChar).Value = DropDownList2.Text;
        cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = Session["LoginName"];

        Con.Open();
        cmd.ExecuteNonQuery();
    }
}

Connection string is
<add name="WindowsAuthenticationSQLConnection"
     connectionString="Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DATA1;Data Source=SQLSERVER" />

But I am facing issue with connection.
The Error is : System.ArgumentException: 'Keyword not supported: 'provider'.'

A: As suggested by @Nick.McDermaid in comment I removed Provider=SQLOLEDB.1; From the connection string and it worked.


text:
Q: How to slice Planck Data? (BinTableHDU) I was trying to slice Planck Data (Healpix to smaller Healpix (only some part)), but with no luck. The below method resulted in bad-number of pixels error, when I was trying to visually show it.
If anyone has methods to do it properly, can you share it with us? Ideally, I want to slice it while keeping all the Stokes parameters (I need them).
What I was trying to do below is: (Doesn't work)

*

*I have already sliced Stokes fits (Not in Healpix Format)

*Using reproject_to_healpix, I was trying to convert these fits to Healpix Format

But, it would be better, if I could slice it directly from Planck data(Healpix) to smaller Healpix, while keeping all Stokes.
from reproject import reproject_from_healpix, reproject_to_healpix
from astropy.io import fits
from astropy.wcs import WCS
import matplotlib.pyplot as plt
from astropy.visualization.wcsaxes.frame import EllipticalFrame
from astropy_healpix import HEALPix
from astropy.table import Table
import healpy as hp
from astropy.table import Table

filename = "planckData/HFI_SkyMap_353-psb-field-IQU_2048_R3.00_full.fits"
file_name = "slicedStokesPlanck/U.fits"
file1 = fits.open(file_name)
u_map = "slicedStokesPlanck/U.fits"

hdu = fits.open(filename)[1]
print(hdu)

target_header = fits.Header.fromstring("""
NAXIS   =                    2
NAXIS1  =                  710
NAXIS2  =                  710
CTYPE1  = 'RA---MOL'
CRPIX1  =                355.5
CRVAL1  =                314.8542781
CDELT1  =                1
CUNIT1  = 'deg     '
CTYPE2  = 'DEC--MOL'
CRPIX2  =                355.5
CRVAL2  =                -21.9709794
CDELT2  =                1
CUNIT2  = 'deg     '
COORDSYS= 'icrs    '
""", sep='\n')

hdu1 = fits.open(filename)[1]
array, footprint = reproject_to_healpix(file1, target_header)

t = Table()
t['flux'] = array
t.meta['ORDERING'] = 'RING'
t.meta['COORDSYS'] = 'G'
t.meta['NSIDE'] = 128
t.meta['INDXSCHM'] = 'IMPLICIT'
t.write('U_healpix_map(TEST).fits')


text:
Q: Tagging the first entry for each user in a db entity without querying I have a db entity which creates a record an event for each login. Now i want to tag the first event of a user with FIRST_LOGIN. But i dont want to check in each and every login event if this is a first_login. is there any other way to acheive this ?
Below is the DB(Using mongodb) entity fields for reference:
String id;
long creationTime;
long userId;
long startTime;
long endTime;
String loginType; // This is the field i want to update
long loggedOutTime;


text:
Q: On Linux, why does the destructor run twice on shared instance of global variable in C++? On Linux I have some generated C++ code from a static library that defines a global variable.  A single instance of this global variable is shared between two shared libraries that refer to its symbol.
When the process shuts down and the static termination phase is run, I see that the destructor on this shared instance is run twice!  Presumably once per library as each unloads.
This question is closely related to another I saw recently here: related question.  This sounds like the same behavior, but there is no discussion about why it is happening.
Does anybody know the theoretical explanation behind this behavior?

A: If you take a naked pointer and place it in a smart pointer (twice), it will destruct twice, once for each container refcount falling to zero.
So, if you pass the naked pointer into both libraries, that would do it.  Each one puts it in a shared pointer object and each of those does the destruction.  If you can see the stack backtrace during the dtor, that should show it happening in both of the libraries.

A: C++ has a rule called the "One Definition Rule":

Every program shall contain exactly one definition of every non-inline function or object that is used in that program; no diagnostic required. The definition can appear explicitly in the program, it can be found in the standard or a user-defined library, or (when appropriate) it is implicitly defined (see 12.1, 12.4 and 12.8).

Wikipedia has an article that explains this in more detail.
You haven't posted code in your question, so I can't be sure about your case, but in the question you linked to, the example in the question was defining the same variable in two shared libraries. This violated the "One Definition Rule", which apparently the dynamic linker's finalization strategy depends on, causing the destructor to be called twice.


text:
Q: bind one of 2 screens to one virtual desktop i will do a workshop. i'd like the audience see all the time only one desktop. there will be one application visible
i, on my laptop, want to be able to switch between what audience see and what they don't see. without changing what audience see in the meantime.
so my first idea is to bind audience view to one virtual desktop. is it possible? or maybe there are other ways of doing this?
i'm on ubuntu 14.04, mate 1.8.2, nvidia, dell precision


text:
Q: Installing specific apt version with ansible I used an ansible playbook to install git:
---
- hosts: "www"
  tasks:
  - name: Update apt repo
    apt: update_cache=yes
  - name: Install dependencies
    apt: name={{item}} state=installed
    with_items:
      - git

I checked the installed versions:
$ git --version
git version 1.9.1

But adding these to the ansible playbook: apt: name=git=1.9.1 state=installed
and rerunning results in the following error:

fatal: [46.101.94.110]: FAILED! => {"cache_update_time": 0,
"cache_updated": false, "changed": false, "failed": true, "msg":
"'/usr/bin/apt-get -y -o "Dpkg::Options::=--force-confdef" -o
"Dpkg::Options::=--force-confold"     install 'git=1.9.1'' failed:
E: Version '1.9.1' for 'git' was not found\n", "stderr": "E: Version
'1.9.1' for 'git' was not found\n", "stdout": "Reading package
lists...\nBuilding dependency tree...\nReading state
information...\n", "stdout_lines": ["Reading package lists...",
"Building dependency tree...", "Reading state information..."]}

A: You don't need two tasks for updating cache and installing. Your playbook should look like:
---
- hosts: "www"
  tasks:
  - name: Install dependencies
    apt:
      name:
        - git=1:1.9.1-1ubuntu0.2
      state: installed
      update_cache: yes

note that Ansible supports wildcarding so you don't necessarily need the full version string

A: Git package with that specific version is as follows:
git=1:1.9.1-1ubuntu0.2

Your task should be:
apt: name=git=1:1.9.1-1ubuntu0.2 state=present

Regards


text:
Q: Black and Yellow edges and Shortest path Given directed and weighted graph $G=(V,E)$ .
There is no negative weighted edge .
Each edge is colored (black or yellow).
I need to find an algorythm the find the shortest path for a given $s\in V$ while every path must be by this rule: $color(v_i\rightarrow v_{i+1}))=color(v_{i+3}\rightarrow v_{i+4})$  ,$\forall i :1\leq i\leq k-4$ while the path is $v_1 \rightarrow ... \rightarrow v_k$.
The algorythm need to be in $O(|V|+E\cdot \log(|V|))$

A: From the conditions on the colours in path, you can see that fixing the first $3$ colours fixes colours in entire path. Now consider $8$ different shortest path problems, one for each way to colour first $3$ edges in a path. In each shortest path problem, the paths have to follow that fixed colouring sequence. This can be handled in Dijkstra's algorithm. At each stage, you know the colour of next edge in the path, so consider only edges of that colour from that node. Once all $8$ problems are solved, for each node, you can just take minimum path length among these $8$. Complexity will be same as that of Dijkstra's, $O(|E|+|V|\log|V|)$. It might be faster to solve all 8 sub-problems in one pass of the nodes.


text:
Q: How do I diagnose problems with serial port communication between a PC and a Blackboard? I am trying to write an application that runs on a Blackboard and it is supposed to send/receive characters to/from the PC COM port. The application on the PC is Xilinx 'Visits Serial Terminal'.
In Xilinx on the PC, I've written a C program that is using UART1 addresses to configure the baud rate, parity, etc and then sends a character. Then, I build/deploy/run this program to the board through the USB cable.
Then, in Windows Device Manager, I make sure that the COM4 port is configured to match the settings in my C program.
Finally, I use Xilinx 'Vitis Serial Terminal' to connect to the same COM4 using the same settings as well.
The problem is that I do not see any data in the 'Vitis Serial Terminal'.
My question is: how do I narrow/debug such problems?
There are many points of failures:

*

*My C program might be doing the wrong things.

*My Windows driver is acting weird/is misconfigured.

*My expectations/configurations of 'Vitis Serial Terminal' are wrong.

If there's a working sample that would be ideal and I can go from there.
I've found this Real Digital article and have similar code in my C program. I've also tried to follow their `Backboard - Basic Zynq Programmers Reference - Rev B'. The data in there is accurate when used to access other functions of that board (leds, 7-segment, etc), so I think I'm using the right reference.
Below is my C program:

#define UART1_CONTROL_REGISTER   0xE0001000
#define UART1_MODE               0xE0001004
#define UART1_BAUD_GEN           0xE0001018
#define UART1_BAUD_RATE_DIVIDER  0xE0001034
#define UART1_RXTOUT             0xE000101C
#define IDR_REGISTER             0xE0005028

#define UART1_SR                 0xE000102C
#define UART1_DATA               0xE0001030

void ConfigureUART1()
{
    // https://www.realdigital.org/doc/ef3498f424aaa1b20b5199907ba12b4c

    // Reset the UART Controller
    //      bit 0: 1 -> receiver logic is reset/data discarded.
    //      bit 1: 1 -> transmitted logic is reset/data discarded.
    //      bit 2: 1 -> enable receive.
    //      bit 3: 0 -> don't disable receive.
    //      bit 4: 1 -> enable transmit.
    //      bit 5: 0 -> don't disable receive.
    //      bit 6: 1 -> restart timerout counter.
    //      bit 7: 0 -> no effect (else, start transmitting a 'break'.)
    //      bit 8: 0 -> no effect (else, stop transmitting a 'break'.)
    //               -> 0 0101 0111

    // Reset...
    * ((uint32_t*)UART1_CONTROL_REGISTER) = 0x3;

    // Wait till they clear again
    while (*((uint32_t*)UART1_CONTROL_REGISTER) == 0x3){};

    // The following divider values we given by the instructor.
    // Based on this post https://electronics.stackexchange.com/questions/442404/baud-rate-generator,
    // the values might be incorrect when our board's clock is 333MHz.

    // Set the BAUDGEN clock divider (115200 baud works well; 0x7C divider value)
    *((uint32_t*)UART1_BAUD_GEN) = 0x7C;

    // Set the Baud_Rate_Divider for bit-clock (again for 115200, 0x6 works)
    *((uint32_t*)UART1_BAUD_RATE_DIVIDER) = 0x6;

    // Channel mode to normal, 1 stop bit, no parity, character length 8-bit, clock source to UART reference clock (Mode Register)
    //      bit 0    : 0   -> clock source is uart_ref_clk
    //      bit 1-2  : 0x  -> 8 bits
    //      bit 3-5  : 1xx -> no parity
    //      bit 6-7  : 00  -> 1 stop bit
    //      bit 8-9  : 00  -> normal
    //      bit 10-11: reserved, do not modify.
    //           0b   dddd-rr 00--00 100 00 0
    //           0x      0c     --     20
    //               0x00000c00 reserved
    //               0x00000020
    uint32_t v0 = *((uint32_t*)UART1_MODE);
    uint32_t v1 = 0x00000c00 & v0;
    *((uint32_t*)UART1_MODE) = v1 | 0x20;

    // Configure the UART Controller
    // Enable software resets, transmitter & receiver, stop transmitter break (Control Register)
    //      bit 0: 0 -> receiver logic is reset/data discarded.
    //      bit 1: 0 -> transmitted logic is reset/data discarded.
    //      bit 2: 1 -> enable receive.
    //      bit 3: 0 -> don't disable receive.
    //      bit 4: 1 -> enable transmit.
    //      bit 5: 0 -> don't disable receive.
    //      bit 6: 0 -> restart timerout counter.
    //      bit 7: 0 -> no effect (else, start transmitting a 'break'.)
    //      bit 8: 0 -> no effect (else, stop transmitting a 'break'.)
    //               -> 0 0001 0100
    *((uint32_t*)UART1_CONTROL_REGISTER) = 0x14;

    // Set timeout to 1 (RXTOUT register)
    //      bit 0-7: 1-255 timeout in number ob baud_samples clocks.
    *((uint32_t*)UART1_RXTOUT) = 0x1;

    // Disable all interrupts (IDR register)
    //      bit 0-9: 1 -> disable this interrupt.
    *((uint32_t*)IDR_REGISTER) = 0xFFFFFFFF;
}

int IsTxFull()
{
    //Check SR register bit4, return 1 if fifo full
    return (*((uint32_t*)UART1_SR) & 0x10) != 0;
}

void Uart1PutChar(char dat)
{
    // Wait for room in FIFO
    while (IsTxFull());

    // Write to TX FIFO
    *((uint32_t*)UART1_DATA) = dat;
}

int main()
{
    ConfigureUART1();
    while (1)
        Uart1PutChar('A');
    return 0;
}


text:
Q: monotouch ios - audioplayer returns nil when initializing Okay, I have this problem for almost a month now. Some audio files are not playing. It just returns an error like this:

Could not initialize an instance of the type 'AVFoundation.AVAudioPlayer': the native 'initWithContentsOfURL:error:' method returned nil.

Here's the code initialising the AudioPlayer:
    NSData data = new NSData();
    if (AppSession.IsConnected ()) {/*Just a checker if connection is available or not*/
        if (uri != null && uri.ToString().Length > 0) {
            data = await LoadData (uri);
        }
    } else { data = null; }

    string saveFile = FolderPath(uri, "playthrough");
    data.Save(saveFile, false);
    NSUrl fileUrl = NSUrl.FromString(saveFile);
    audioplayer = AVAudioPlayer.FromUrl(fileUrl);
    audioplayer.NumberOfLoops = 0;
    audioplayer.Volume = 1.5f;
    audioplayer.PrepareToPlay();
    audioplayer.Play();

For LoadData:
    public static async Task<NSData> LoadData (NSUrl url)
    {
        NSData data = new NSData ();
        if (url.ToString ().Contains ("http")) {
            var httpClient = new HttpClient ();
            Task<byte[]> contentsTask = httpClient.GetByteArrayAsync (url.ToString ());
            var contents = await contentsTask;
            data = NSData.FromArray(contents);
        } else { data = NSData.FromUrl (url); }
        return data;
    }

For FolderPath:
    public static string FolderPath(NSUrl url, string fileName)
    {
        string[] dotSplitter = url.ToString ().Split (new char[]{ '.' }, 4);
        string ext = "";
        if (dotSplitter.Length == 4) {
            switch (dotSplitter [3]) {
            case "wav": ext = ".wav"; break;
            case "mp3": ext = ".mp3"; break;
            case "3gpp": ext = ".3gpp"; break;
            case "mp4": ext = ".mp4"; break;
            }
        } else {
            switch (dotSplitter [0]) {
            case "wav": ext = ".wav"; break;
            case "mp3": ext = ".mp3"; break;
            case "3gpp": ext = ".3gpp"; break;
            case "mp4": ext = ".mp4"; break;
            }
        }

        return Path.Combine(TMPDir(), fileName + ext);
    }

And here are the files I'm using to test the audio:

*

*http://files.parsetfss.com/6ea4a3c5-a4e2-463f-8374-247d5db0fbd5/tfss-c7db3001-b7b0-465d-b59b-233c1fe568ec-filtered_427201531308PM_song.wav

*http://files.parsetfss.com/6ea4a3c5-a4e2-463f-8374-247d5db0fbd5/tfss-c4426fba-ea52-4764-9fb6-6b9f10aba89f-filtered_27042015154318_song.wav
So, yeah. I've done dozens of research, google, experiment and tears for this, but I ended up with no result at all. Any solutions for this?

A: The full exception you should get is:

System.Exception : Could not initialize an instance of the type 'MonoTouch.AVFoundation.AVAudioPlayer': the native 'initWithContentsOfURL:error:' method returned nil.
  It is possible to ignore this condition by setting MonoTouch.ObjCRuntime.Class.ThrowOnInitFailure to false.

Following the above advice (use the overload accepting an NSError) and the one from the exception message you get something like:
MonoTouch.ObjCRuntime.Class.ThrowOnInitFailure = false;
NSError error;
using (var url = NSUrl.FromString ("http://files.parsetfss.com/6ea4a3c5-a4e2-463f-8374-247d5db0fbd5/tfss-c7db3001-b7b0-465d-b59b-233c1fe568ec-filtered_427201531308PM_song.wav"))
using (var player = AVAudioPlayer.FromUrl (url, out error)) {
    Console.WriteLine (error);
}

You'll get:

The operation couldn't be completed. (OSStatus error 2003334207.)

which is a very common error for AVAudioPlayer. I also get the same error if you use an NSData (local file). However AVPlayer loads the URL just fine...


text:
Q: c++ will `map::key_comp` hamper performance if called as a way to compare a number with existing key? i have a type defined as below,
using BookMapT = std::map<long long int, long long int, std::function<bool(long long int,long long int)>>;
BookMapT greater_map(greater<long long int>{});
BookMapT less_map(less<long long int>{});

So if have a number and I want to compare with the beginning of a BookMapT
int compare(BookMapT& book, long long int number_to_compare){
    return book.key_comp()(number_to_compare, book.begin()->first);
}

From http://www.cplusplus.com/reference/map/map/key_comp/ I can see key_comp return a copy of the comparison object, will this copy action somehow hamper performance?
What confuse me most is how much cost is this copying of std::function ?
Thanks.

A: #include <chrono>
#include <functional>
#include <iostream>
#include <random>

typedef std::function<bool(long long int,long long int)> TF;

TF cp(const TF & f) { return f; }

int cp1(TF f, int times, int n) {
    int c = 0;

    for(int i = times; --i >= 0;) {
        c += cp(f)(i, n);
    }

    return n;
}

int cp2(TF f, int times, int n) {
    int c = 0;

    for(int i = times; --i >= 0;) {
        c += TF(f)(i, n);
    }

    return n;
}

int no_cp(TF f, int times, int n) {
    int c = 0;

    for(int i = times; --i >= 0;) {
        c += f(i, n);
    }

    return n;
}

typedef int(*TP)(TF, int, int);

void test(TP p, int n)
{
    double s = 0;
    int c = 0;
    for(int i = 10; --i >= 0;) {;
        auto t = std::chrono::steady_clock::now();
        c += (*p)(std::less<long long int>{}, 50000000, n);
        std::chrono::duration<double> d = std::chrono::steady_clock::now() - t;
        s += d.count();
    }
    std::cout << s / 10 << "(" << c << ")" <<  std::endl;
}

int main() {
    int n = static_cast<int>(std::random_device()());
    std::cout << "cp1: ";
    test(&cp1, n);
    std::cout << "cp2: ";
    test(&cp2, n);
    std::cout << "no_cp: ";
    test(&no_cp, n);
}

Results with -O0 flag:
cp1: 2.24382
cp2: 2.10708
no_cp: 0.833974
Results with -O3 flag:
cp1: 0.20065
cp2: 0.199159
no_cp: 0.0643156

CPU: Intel Core i7 (Comet Lake)


text:
Q: Crossover algorithm for Travelling Salesman? I am looking for a crossover algorithm for a genetic algorithm for the Travelling Salesman Problem.
However, my TSP problem is a variation of the traditional problem:
Instead of only being given a list of points that we need to visit, we are given a list points that we need to visit and a list of points we need to start at and end at. In other words, any route must start and end at any point belonging to the second list, but must visit all the points in the first list.
So in other words, not every permutation of points is valid. Because of this, I'm not sure if traditional crossover algorithms will work well (for instance, I tried ordered crossover and the children it created were generally worse than its parents).
Can anyone suggest a crossover algorithm?

A: In order to maintain your crossover and mutation operators, you can add a repair operator that checks if the position of your starting and ending locations are correct and if they aren't, swap them into their valid positions (initial and ending).


text:
Q: Migrating from http to https in android with Volley I have a service running without SSL right now and I'm using Volley to consume the APIs. If at some point I do enable SSL, how do I ensure that people can continue using older versions of the app which have a SSL disabled url.

A: On the server side, add the SSL enabled endpoints you need, but keep the old ones for the transition period until it's "safe" to phase them out.
There's nothing special to be done on the client side.


text:
Q: what does it mean for `new` to be no-throw guaranteed when bad_alloc is not thrown From the documentation of new:

The first version (1) throws bad_alloc if it fails to allocate
  storage. Otherwise, it throws no exceptions (no-throw guarantee).

To me, this should mean that this code
#include <new>

struct A{
    A(){
        throw 0;
    }
};

int main(){
    try{
        A* a = new A;
    }
    catch(std::bad_alloc&){}
}

is perfectly fine. However, when compiling it with gcc (see here), the program terminates after throwing an int.

A: The expression new A normally does two things:

*

*Call operator new to get some storage.

*Call a constructor of A to create an A object within that storage.

The quote you pasted only describes the behavior of the function ::operator new(std::size_t).  Here step 2 throws an int after operator new has already succeeded and exited.
(In this example, C++ does make sure the allocated memory is passed to operator delete before you get to any catch handler.)

A: The keywordnew is no-throw guarenteed, not the class you're allocating (A). You've explicitly defined the constructor for A as throwing an exception; when an A is allocated, A throws the exception, not new.

A: That's the documentation of operator new, which is not the same as the new expression. A new expression calls operator new to obtain memory and then calls the constructor requested on that memory. operator new does not throw anything other than std::bad_alloc, but the later call to the constructor can throw whatever the user code wants.
Compare new expression with operator new.


text:
Q: Ruby - Create Google Slideshow Is there a Ruby gem which can be used to create a Google Slideshow / Powerpoint using plain text? I've searched all over and can't find anything I'm looking for.

A: I haven't been able to find any that exports to Google or PowerPoint, but you might try ShowOff.


text:
Q: Infinite and Finite Square Wells For the infinite square well in the first region, outside the well:
$$\frac{-\hbar^2}{2m}\frac{d^2 \psi}{dx^2} + V(x) \psi (x) = E \psi (x),$$
where you set $V = 0$. Rearranging gives $$\frac{d^2 \psi}{dx^2} = -\frac{2mE}{\hbar^2} \psi.$$
We identify $$k = \sqrt{\frac{2mE}{\hbar^2}}.$$
For the finite square well we have the same situation (for bound solutions) but we set:
$$\alpha = \sqrt{\frac{-2mE}{\hbar^2}}.$$
Why do we absorb the minus sign into the square root now and not before?  How does this tie in with bound/unbound solutions and parity?

A: Short version:
In the infinite potential well, $E \geq 0$ (because $V_{min}=0$, and $E \geq V_{min}$). In your finite potential well, it sounds like you are looking for bound states, in which case $E < 0$, so you absorb the negative into the square root.
Long version:
When you are tackling a QM problem, first you should figure out the admissibility of bound states and scattering states. If the energy of the particle is less than the potential at $-\infty$ and $+\infty$, then you have bound states. For example, the infinite square well only admits bound state solutions. The finite potential well can admit both scattering states and bound states depending on the energy (typically, $V(\pm \infty) = 0$ in a finite potential well, so if $E < 0$ it is a bound state and if $E > 0$ it is a scattering state).
Once you declare whether you are seeking bound or scattering states, you will have an idea of where your energy is. In the finite square well with $V(\pm \infty) = 0$, if you are seeking bound states, then you know $E < 0$. Therefore, to keep the math as straightforward as possible, it makes sense to place the negative in the square root so the argument will be positive.
In the infinite square well, you know that all states are bound because $V(\pm\infty)=\infty$. So we must appeal elsewhere to get a constraint on the energy. We know that $E \geq V_{min}$ (otherwise the wave function cannot be normalized, see Problem 2.2 of Griffith's QM). Since $V_{min}=0$, then $E \geq 0$. Therefore, we should not absorb a negative into the square root to keep the argument positive.

A: The only thing that's really important is the differential eqaution. The situation is, outside the well, in both cases:
$\dfrac{d^2 \psi}{dx^2}= -  \frac{2mE}{\hbar^2} \psi$
Now it's foundamental notice that for bound states E<0 so we can write: $E=-|E|$ and Sc. equation become:
$\dfrac{d^2 \psi}{dx^2}= +  \frac{2m|E|}{\hbar^2} \psi$
So the usual way to conclude this problem is setting $k= \sqrt{\frac{2m|E|}{\hbar^2}}>0$ , now the roots of differential equation are $\pm k$ and general solution is:
$\psi=Ae^{+kx}+Be^{-kx}$
Intead of that you can resolve the problem in this way:
$\dfrac{d^2 \psi}{dx^2}= -  \frac{2mE}{\hbar^2} \psi$
(without explicity absolute value)
now put $\alpha= \sqrt{- \frac{2mE}{\hbar^2}}$ so:
$\dfrac{d^2 \psi}{dx^2}= \alpha^2 \psi$
Solution is (as above):
$\psi=Ae^{+\alpha x}+Be^{-\alpha x}$
And you can now put in the exponent $E=-|E|$ (bound states):
$\alpha= \sqrt{- \frac{2mE}{\hbar^2}}=\sqrt{+ \frac{2m|E|}{\hbar^2}}=k$
Finally: $\psi=Ae^{+\alpha x}+Be^{-\alpha x}=Ae^{+k x}+Be^{-k x}$
The solutions are (obviously) the same in the two different ways (the idea is only in a case to explicit the absolute value immidiately and in the other case to do that at the end).


text:
Q: What conditions are sufficient for "Basically disconnectedness implies Extremally disconnectedness"? Recall the definition of basically disconnected:

A space is basically disconnected if every cozero-set has an open closure.

There exists a Basically disconnected space which is not extremally disconnected; the one-point Lindelöfization of an uncountable discrete space is such a space.
But with what conditions basically disconnectedness does imply extremally disconnectedness?
Thanks.

A: Completely regular plus basically disconnected gives extremely disconnectedness, since then all open sets are cozero sets. From the counterexamples given, it sounds like second countability and some separtion axiom may be a requirement (which would imply being normal), so I'm not sure that you can get anything sharper than that while being as general.
Edit: I realized I was wrong in the comments. I wanted to find conditions for all open sets to be cozero sets; however, if there are functions $f,g$ that are zero precisely on $A$ and $B$, then $f/(f+g)$ gives a function that is $0$ precisely on $A$ and 1 precisely on $B$, so we have to have normality. Also, such sets must be $G_{\delta}$'s, since they are the intersection of preimages of open sets in the interval. So a space must in fact be $T_6$ for all open sets to be cozero sets, so my approach won't work.


text:
Q: mostrar los datos en un formulario antes de que sean actualizados estoy intentando mostrar los datos del usuario que pretendo actualizar.
En mi estructura introduzco un dni que se extrae al consultar una lista, para luego mostrar los datos del usuario en concreto en otro formulario. Cuando este formulario sea mandado los datos quedarán actualizados definitivamente.
El problema que tengo es que no se como mostrar los datos del usuario que previamente he buscado.
P.E: Busco un usuario called Jhon Doe with DNI 11111111E, in the second form i will have a new form with name and surname  juan nadie, ahora escribo en esos campos del formulario miguel nadie y presiono subbmit.
El problema: no sé como mostrar el nombre antiguo en mi formulario( es decir, no se como mostrar a juan Nadie)
Estoy atascado en esta parte, la actualización es correcta, pero no logro mostrar los campos.
Os adjunto el código
1º-Aquí mi primera página del formulario, de donde saco el DNI previa muestra de un listado.
    <%@page import="java.util.List"%>
<%@page import="Entidades.Usuario"%>
<%@page import="DAO.DAOUsuario"%>
<%@page import="Conexion.DBConnection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="usuario" class="Entidades.Usuario" />
<jsp:setProperty name="usuario" property="*"/>

<%
String message = "";
List<Usuario> usuarios = null;
DAOUsuario dao = new DAOUsuario();

try {
    //usuarios = dao.selectUsuario("si","nombre");
    usuarios = dao.selectAllUsuarios();
} catch (Exception ex) {
    message = ex.toString();
}
%>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>V2formListarUsuariosAltaNombre</title>
    <link href="../css/estilos.css" rel="stylesheet" type="text/css"/>

BIBLIOTECA - LISTADOS USUARIOS

Menu inicial

Atras

            <form id="formulario" action="V2formModificarUsuario2(en obras).jsp" method="POST">
                Intruduzca DNI del usuario

                DNI: <input type="text" name="DNI" required="">
                <input type="submit" value="buscar">
            </form>
            <form>
                <%if (!message.isEmpty()) {%>
                <input name="status_initial" type="text" style="width:400px" value="<%=message%>"/>
                <%} else { %>

                        DNI
                        nombre
                        apellidos
                        de alta

                    <%for (int i = 0; i < usuarios.size(); i++) {%>

                        <%=usuarios.get(i).getDNI()%>
                        <%=usuarios.get(i).getNombre()%>
                        <%=usuarios.get(i).getApellidos()%>
                        <%=usuarios.get(i).getDeAlta()%>

                    <%}%>

                <%}%>
            </form>

2º-Aquí la segunda hoja del formulario, donde actualizo los datos al completar un formulario que debería tener en sus campos los datos del usuario que he seleccionado (y que es donde está mi pregunta)
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="Entidades.Usuario"%>
<%@page import="DAO.DAOUsuario"%>
<%@page import="Conexion.DBConnection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="usuario" class="Entidades.Usuario"></jsp:useBean>
<jsp:setProperty name="usuario" property="*"/>

<%
String message = "";

// String nameToChange = "";
String surnameToChange = "";

try {
    if ((usuario.getDNI() != null) && (!usuario.getDNI().isEmpty())) {
        DAOUsuario dao = new DAOUsuario();

       // nameToChange=dao.selectByDNI(request.getParameter("DNI")).getNombre(); comentado por ahora
        surnameToChange=dao.selectByDNI(request.getParameter("DNI")).getApellidos();
        Usuario usuarios = dao.selectByDNI(usuario.getDNI());

        if (usuarios != null) {
            if ((usuario.getNombre() != null) && (!usuario.getNombre().isEmpty())
                    && (usuario.getApellidos() != null) && (!usuario.getApellidos().isEmpty())) {

                dao.update(usuario.getDNI(), usuario.getNombre(), usuario.getApellidos());
                message = "User correctly updated.";
            } else {
                if (request.getParameter("updating") == "1") {
                    message = "Los campos name, surname and deAlta are required .";
                }
            }
        } else {
            message = "user do not exists.";
        }
    } else {
        message = "DNI must not be null.";
    }
} catch (Exception ex) {
    message = ex.getMessage();
}
%>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSPformModificarUsuario2(en obras)</title>
    <link href="css/estilos.css" rel="stylesheet" type="text/css"/>

BIBLIOTECA - USUARIO

Inicio

            <form method="POST" action="V2formModificarUsuario2(en obras).jsp">
                <input name="updating" type="hidden" value="1"/>

                <%if (!message.isEmpty()) {%>
                <input name="message" type="text" style="width:400px" value="<%=message%>"/>
                <%} else { %>

                DNI:
                <input name="DNI" type="text" style="width:200px" value="<jsp:getProperty property="DNI" name="usuario"/>" readonly=""/>

                nombre:
                <input name="nombre" type="text" style="width:200px" placeholder="<%=apellidoActualizar%>" value="<jsp:getProperty property="nombre" name="usuario"/>"/>

                apellidos:
                <input name="apellidos" type="text" style="width:200px" value="<jsp:getProperty property="apellidos" name="usuario"/>"/>

                <input type="submit" value="Actualizar"/>

                <%}%>
            </form>

3º-Y aquí los DAO que he empleado, están correctos.
 public Usuario update(String DNI, String nombre, String apellidos) throws Exception {
    if ((DNI == null) || (DNI.isEmpty())) {
        throw new Exception("DNI must not be null");
    }
    if ((nombre == null) || (nombre.isEmpty())) {
        throw new Exception("name must not be null");
    }
    if ((apellidos == null) || (apellidos.isEmpty())) {
        throw new Exception("surname must not be null");
    }

    Usuario usuario = selectByDNI(DNI);
    if (usuario == null) {
        throw new Exception("user do not exist");
    }
    try (Connection connection = DBConnection.get()) {
        if (connection == null) {
            throw new Exception("Connection is null");
        }

        String query = "UPDATE usuario SET nombre=?, apellidos=? WHERE DNI=?";

        PreparedStatement statement = connection.prepareStatement(query);
        statement.setString(1, nombre);
        statement.setString(2, apellidos);
        statement.setString(3, DNI);
        statement.execute();
    } catch (Exception ex) {
        throw ex;
    } finally {
        DBConnection.close();
    }
    usuario = selectByDNI(DNI);
    return usuario;
}

public Usuario selectByDNI(String DNI) throws Exception {
    if ((DNI == null) || (DNI.isEmpty())) {
        return null;
    }
    Usuario usuario = null;
    try (Connection connection = DBConnection.get()) {
        if (connection == null) {
            throw new Exception("Connection is null");
        }
        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery("SELECT * FROM usuario WHERE DNI = '" + DNI + "'");

        if (rs.next()) {
            usuario = new Usuario(rs.getString("DNI"), rs.getString("nombre"),
                    rs.getString("apellidos"), rs.getString("deAlta"));
        }
    } catch (Exception ex) {
        throw ex;
    } finally {
        DBConnection.close();
    }
    return usuario;
}

A: lo he resuelto, hacía falta una hoja más de formulario, en la primera creo el objeto con el DNI buscado, extraigo sus valores y muestro en placeholder el valor y también en el value, conecto este formulario con otro por post y le paso los valores, comprobando si esos valores están o no vacios o son nulos.
Luego doy a varias variables los valores del formulario anterior con getParameters y creo un objeto con un DAOUpdate que tengo preparado y que modifica los usuarios en la bbdd independientemente de su alta o baja,y finalmente se manda mensaje informando.
formulario 2
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="Entidades.Usuario"%>
<%@page import="DAO.DAOUsuario"%>
<%@page import="Conexion.DBConnection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="usuario" class="Entidades.Usuario"></jsp:useBean>
<jsp:setProperty name="usuario" property="*"/>

<%
String message = "";
String nombreActualizar = "";
String apellidoActualizar = "";

try {
    if ((usuario.getDNI() != null) && (!usuario.getDNI().isEmpty())) {
        DAOUsuario dao = new DAOUsuario();
        nombreActualizar = dao.selectByDNI(request.getParameter("DNI")).getNombre();
        apellidoActualizar = dao.selectByDNI(request.getParameter("DNI")).getApellidos();
    } else {
        message = "El DNI  de actualización no puede ser nulo.";
    }
} catch (Exception ex) {
    message = ex.getMessage();
}
%>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSPformModificarUsuario2(en obras)</title>
    <link href="../css/estilos.css" rel="stylesheet" type="text/css"/>

BIBLIOTECA - USUARIO

Menu inicial

Atras

            <form method="POST" action="V2formModificarUsuario3.jsp">
                <input name="updating" type="hidden" value="1"/>

                <%if (!message.isEmpty()) {%>
                <input name="message" type="text" style="width:400px" value="<%=message%>"/>
                <%} else {%>

                DNI:
                <input name="DNI" type="text" style="width:200px" value="<jsp:getProperty property="DNI" name="usuario"/>" readonly=""/>

                nombre:

                <input name="nombre" type="text" style="width:400px" placeholder="<%=nombreActualizar%>" value="<%=nombreActualizar%>"/>

                apellidos:

                <input name="apellidos" type="text" style="width:400px" placeholder="<%=apellidoActualizar%>" value="<%=apellidoActualizar%>"/>

                <input type="submit" value="Actualizar"/>

                <%}%>
            </form>

formulario 3
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="Entidades.Usuario"%>
<%@page import="DAO.DAOUsuario"%>
<%@page import="Conexion.DBConnection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="usuario" class="Entidades.Usuario"></jsp:useBean>
<jsp:setProperty name="usuario" property="*"/>

<%
String message = "";
DAOUsuario dao = new DAOUsuario();
String DNIActualizado="";
String nombreActualizado ="";
String apellidoActualizado = "";

if (
        ((request.getParameter("DNI") == null) || (request.getParameter("DNI").isEmpty()))
     || ((request.getParameter("nombre") == null) || (request.getParameter("nombre").isEmpty()))
     || ((request.getParameter("apellidos") == null) ||(request.getParameter("apellidos").isEmpty()))
        ) {
    message = "Ningún campo del formulario debe estar vacio.";
}else{

DNIActualizado=request.getParameter("DNI");
nombreActualizado=request.getParameter("nombre");
apellidoActualizado=request.getParameter("apellidos");

usuario=dao.update(DNIActualizado, nombreActualizado, apellidoActualizado);
message = "usuario con DNI "+request.getParameter("DNI")+" actualizado";
}

%>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSPformModificarUsuario3(en obras)</title>
    <link href="../css/estilos.css" rel="stylesheet" type="text/css"/>

BIBLIOTECA - USUARIO

Menu inicial

Atras

            <form method="POST" action="V2formModificarUsuario3(en obras).jsp">
                <input name="updating" type="hidden" value="1"/>

                <%if (!message.isEmpty()) {%>
                <input name="message" type="text" style="width:400px" value="<%=message%>"/>
                <%} else {%>

                DNI:
                <input name="DNI" type="text" style="width:200px" value="<jsp:getProperty property="DNI" name="usuario"/>" readonly=""/>

                <%}%>
            </form>


text:
Q: For loop with 2 if statements - Error: Missing value where TRUE/FALSE needed I am writing a "for loop" in r Programming With 2 if conditions in a row (not a Chain, one "if" is separate and subsequent to the first "if").
I run this loop on a "test" vector (numeric vector). This "test" variable can go above the value of "Limit" (numeric vector). However, if, at time [i], "test" goes back down below "Limit", this is interpreted as a "remakepoint", and "Limit" is increased by 5 at time [i+1].
This is my code:
testLimit<-function(test){
Limit<-vector()
remake<-vector()
remakepoint<-vector()
Limit[1]<-test[1]
remakepoint[1]<-0
for(i in 2:length(test)){
  Limit[i]=Limit[i-1]
  if(test[i]<=Limit[i]){
    remake[i]<-0
  } else {
    remake[i]<-1
  }
  remakepoint[i]=remake[i]-remake[i-1]
  if(remakepoint[i]==-1){
    Limit[i+1]=Limit[i]+5
  } else {
    Limit[i+1]=Limit[i]
  }
}
return(data.frame(test,Limit,remake,remakepoint))
}

However, it Returns the following error:
Error in if (remakepoint[i] == -1) { : missing value where TRUE/FALSE needed

I don't understand why it doesn't get the remakepoint[i]==-1, this has just been calculated in the row above: remakepoint[i]=remake[i]-remake[i-1]
Can someone help me?
Thanks in advance! :)

A: you never gave remake a value at 1, so the first remakepoint[i]=remake[i]-remake[i-1] call gives an NA:
remakepoint[2]=remake[2]-remake[1]

to fix it, try setting:
remake <- c(0)

instead of:
remake<-vector()

EDIT: There are several other errors in the code, maybe include a desired input and output for trouble shooting purposes.
You also have an error if your last value is larger than the limit - it sets the next limit, and breaks as the limit column has more rows than the rest. You can fix this by trimming the end off in the return function:
return(data.frame(test,Limit[1:length(test)],remake,remakepoint))


text:
Q: How to calculate similarity between two signature images I have signature images like this one:

Both of these signatures are similar and I need to print if they are similar or not.
I have tried SSIM, MSE, SIFT and Cosine similarity.
SSIM gives almost more than 0.7 index for both similar and dissimilar images.
MSE gives a very large distance once these are cleaned and compared
SIFT gave 66 features matches
And cosine similarity gave 0.08
Here is the code that helps clean the images
image = cv2.imread('test2.png')
image = cv2.resize(image, (680, 460))
image = cv2.detailEnhance(image)

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (1,1), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Filter using contour area and remove small noise
cnts = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    if area < 5500:
        cv2.drawContours(thresh, [c], -1, (0,0,0), -1)

        # Morph close and invert image
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,1))
close = 255 - cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=1)
cv2.imshow('thresh', close) ###for showing
cv2.waitKey()
kernel = np.ones((1,1),np.uint8)
# sign2 = cv2.dilate(close,kernel,iterations = 1)
sign2= close

# cv2.imshow('thresh', sign2) ###for showing
# cv2.waitKey()

I clean both images and then compare.
Is there any other way to compare them. All I want is if they are similar then just say yes :p


text:
Q: Values in pandas dataframe not getting sorted I have a dataframe as shown below:
    Category    1   2   3   4   5   6   7   8   9   10  11  12  13
    A   424 377 161 133 2   81  141 169 297 153 53  50  197
    B   231 121 111 106 4   79  68  70  92  93  71  65  66
    C   480 379 159 139 2   116 148 175 308 150 98  82  195
    D   88  56  38  40  0   25  24  55  84  36  24  26  36
    E   1084    1002    478 299 7   256 342 342 695 378 175 132 465
    F   497 246 283 206 4   142 151 168 297 224 194 198 148
    H   8   5   4   3   0   2   3   2   7   5   3   2   0
    G   3191    2119    1656    856 50  826 955 739 1447    1342    975 628 1277
    K   58  26  27  51  1   18  22  42  47  35  19  20  14
    S   363 254 131 105 6   82  86  121 196 98  81  57  125
    T   54  59  20  4   0   9   12  7   36  23  5   4   20
    O   554 304 207 155 3   130 260 183 287 204 98  106 195
    P   756 497 325 230 5   212 300 280 448 270 201 140 313
    PP  64  43  26  17  1   15  35  17  32  28  18  9   27
    R   265 157 109 89  1   68  68  104 154 96  63  55  90
    S   377 204 201 114 5   112 267 136 209 172 147 90  157
    St  770 443 405 234 5   172 464 232 367 270 290 136 294
    Qs  47  33  11  14  0   18  14  19  26  17  5   6   13
    Y   1806    626 1102    1177    14  625 619 1079    1273    981 845 891 455
    W   123 177 27  28  0   18  62  34  64  27  14  4   51
    Z   2770    1375    1579    1082    17  900 1630    1137    1465    1383    861 755 1201

I want to sort the dataframe by values in each row. Once done, I want to sort the index also.
For example the values in first row corresponding to category A, should appear as:
2 50  53  81 133 141 153 161 169 197 297 377 424
I have tried df.sort_values(by=df.index.tolist(), ascending=False, axis=1) but this doesn't work. The values don't appear in sorted order at all

A: np.sort + sort_index
You can use np.sort along axis=1, then sort_index:
cols, idx = df.columns[1:], df.iloc[:, 0]

res = pd.DataFrame(np.sort(df.iloc[:, 1:].values, axis=1), columns=cols, index=idx)\
        .sort_index()

print(res)

           1    2    3    4    5     6     7     8     9    10    11    12  \
Category
A          2   50   53   81  133   141   153   161   169   197   297   377
B          4   65   66   68   70    71    79    92    93   106   111   121
C          2   82   98  116  139   148   150   159   175   195   308   379
D          0   24   24   25   26    36    36    38    40    55    56    84
E          7  132  175  256  299   342   342   378   465   478   695  1002
F          4  142  148  151  168   194   198   206   224   246   283   297
G         50  628  739  826  856   955   975  1277  1342  1447  1656  2119
H          0    0    2    2    2     3     3     3     4     5     5     7
K          1   14   18   19   20    22    26    27    35    42    47    51
O          3   98  106  130  155   183   195   204   207   260   287   304
P          5  140  201  212  230   270   280   300   313   325   448   497
PP         1    9   15   17   17    18    26    27    28    32    35    43
Qs         0    5    6   11   13    14    14    17    18    19    26    33
R          1   55   63   68   68    89    90    96   104   109   154   157
S          6   57   81   82   86    98   105   121   125   131   196   254
S          5   90  112  114  136   147   157   172   201   204   209   267
St         5  136  172  232  234   270   290   294   367   405   443   464
T          0    4    4    5    7     9    12    20    20    23    36    54
W          0    4   14   18   27    27    28    34    51    62    64   123
Y         14  455  619  625  626   845   891   981  1079  1102  1177  1273
Z          1   17  755  861  900  1082  1137  1375  1383  1465  1579  1630

A: One way is to apply sorted setting 1 as axis, applying pd.Series to return a dataframe instead of a list, and finally sorting by Category:
df.loc[:,'1':].apply(sorted, axis = 1).apply(pd.Series)
           .set_index(df.Category).sort_index()

       Category   0    1    2    3     4     5     6     7     8     9    10  ...
0         A   2   50   53   81   133   141   153   161   169   197   297   ...
1         B   4   65   66   68    70    71    79    92    93   106   111  ...


text:
Q: How to cast generic type after isAssignableFrom check in Kotlin? See the example:

class MyTypeAdapter<T : Throwable>
    (private val gson: Gson, private val skipPast: TypeAdapterFactory) : TypeAdapter<T>() {
   // :Throwable is needed to access the stackTrace field
}

private class ThrowableTypeAdapterFactory : TypeAdapterFactory {
    override fun <T> create(gson: Gson, typeToken: TypeToken<T>): TypeAdapter<T>? {
        if (Throwable::class.java.isAssignableFrom(typeToken.rawType)) {
            return MyTypeAdapter<T>(gson, this) // compile error: Type argument is not within its bound
        }
        return null
    }
}

So in Java we have raw use parameterized class but Kotlin doesn't allow it anymore.
I tried to find something from https://kotlinlang.org/docs/reference/generics.html
but couldn't get a clue. Please advice.

A: You should be able to cheat thanks to type erasure:
return MyTypeAdapter<Throwable>(gson, this) as MyTypeAdapter<T>

It looks wrong, but the class can't actually do anything different depending on T.
Or if Kotlin won't accept this cast directly (can't check at the moment) something like
return (MyTypeAdapter<Throwable>(gson, this) as MyTypeAdapter<*>) as MyTypeAdapter<T>

or even
return (MyTypeAdapter<Throwable>(gson, this) as Any) as MyTypeAdapter<T>

should work.


text:
Q: How to stop a minecart at a random moment? I'm working on a roulette table on a server that I'm playing on, inspired by MagmaMusen's video on YouTube:

It uses a minecart with an armor stand inside it. The minecart is not visible, but the top of the iron helmet on the armor stand is visible like a moving square on top of the diferent-coloured carpets above the minecart. The minecart goes in a circle (about 3x3 blocks big) on powered rails, until a player flicks a lever and stops the minecart by turning off the rails.

The main flaw of this is that the moment the roulette stops isn't random. This could cause some arguing between the players. How can I avoid this problem? Is it possible to have a button that will stop the rails at a random moment instead of the lever?
It would also be nice if you could avoid using too complicated redstone circuits and command blocks.
Note:
You can check out MagmaMusen's video "How to make a Working Roulette Table" if you didn't get the way it works from my explanation.

A: You want a system that will use a random feature of the game. I used dispensers. The redstone on the image looks a bit big, but I just placed the parts of it farther away to look less complicated. Here's some images:

Now, let's dig deeper:

*

*Start button

*Button Switch. Each time the input signal goes off, the output signal changes (goes on if it was off and vice versa) - something like a button to lever converter. Here's how it works:

The input must power both pistons at once.

*Fast Redstone clock

*Piston on/off switch for the clock

*Randomizer. There's a dispenser with 8 stacks of items which won't pass through the water (eg. chicken eggs or snowballs) and 1 stack which will (normal items). The system will power the Dispenser each second until a shooted item powers the pressure plate. To reset it just go to the sign and collect the item. A screenshot:

*Roulette (minecart stopper)

*Signal shortener - basically a lever to button converter. This sends a short signal each time it's powered.

*Minecart releaser. This will release the Minecart onto the roulette rail.