text:
Q: How to use a function to pass a control name for executing the same code routines in C# I would like to know how I can use a function to pass in the control name (in this case a Combo box)?
I have 8 Combo boxes, all of which are subject to the same code, so instead of duplicating the code 8 times and changing the name of the called combobox name, is it possible to pass the name of the combobox as a control into a function?
This is the code before I tried this method:-
private void cmbDataSetA_1_TextChanged(object sender, EventArgs e)
        {
            string filenameExtension = Path.GetExtension(cmbDataSetA_1.Text);

            try
            {
                // Clear combo before population
                cmbDataSetB_1.Items.Clear();

                // Make sure the data feed replacement media item matches the type of media (JPG/MOV etc)
                if (filenameExtension == ".jpg")
                {
                    for (int i = 0; i < cmbDataSetA_1.Items.Count; i++)
                    {
                        string item = cmbDataSetA_1.GetItemText(cmbDataSetA_1.Items[i]);

                        if (Path.GetExtension(item) == ".jpg")
                        {
                            cmbDataSetB_1.Items.Add(item);
                            cmbDataSetB_1.Refresh();
                        }
                    }
                }
                else if (filenameExtension == ".jpeg")
                {

                }
                if (filenameExtension == ".png")
                {

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR = " + ex);
            }

        }

Then I tried this following:-
// Call function with 2 combos (original and second to populate based on items in original)
PopulateCombo(cmbDataSetA_1, cmbDataSetB_1);

public void PopulateCombo(Control comboA, Control comboB)
        {
            string filenameExtension = Path.GetExtension(cmbDataSetA_1.Text);

            try
            {
                // Clear combo before population
                comboB.Items.Clear();

                // Make sure the data feed replacement media item matches the type of media (JPG/MOV etc)
                if (filenameExtension == ".jpg")
                {
                    for (int i = 0; i < comboA.Items.Count; i++)
                    {
                        string item = comboA.GetItemText(cmbDataSetA_1.Items[i]);

                        if (Path.GetExtension(item) == ".jpg")
                        {
                            comboB.Items.Add(item);
                            comboB.Refresh();
                        }
                    }
                }
                else if (filenameExtension == ".jpeg")
                {

                }
                if (filenameExtension == ".png")
                {

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR = " + ex);
            }

        }

..however, I get the following errors:-
CS1061  'Control' does not contain a definition for 'GetItemText' and no extension method 'GetItemText' accepting a first argument of type 'Control' could be found (are you missing a using directive or an assembly reference?)
Any help would be great, please.
Thanks.

A: You have defined ComboA as Control. Control is a 'generic' base class for ComboBox and doesn't have defined the GetItemText method.  If you are sure you will use combo box, declare them as ComboBox:
public void PopulateCombo(ComboBox comboA, ComboBox comboB)

Or include some type checking code like:
if (comboA is ComboBox && comboB is ComboBox)
{
    //your code
}
else
{
     throw new InvalidArgumentException(); //or alternative code for other control types
}


text:
Q: ng-repeat creating a scope on multiples divs I have json data from server which i try to populate on the html.
The problem is i want the new data to be on one div grouped, not stacked on each other or each one on a single full row.
I tried to add some style, but not working.
Plus i'm using masonry framework with the grid system, and i feel like no css is applied
Here is how it's looking

And here is the code:

{{post.Title}}

        }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Showing $a_{j+1}=\frac{1}{2}(\frac{4}{a_j}+a_j)$ is convergent How to show the following sequence is decreasing and bounded below.
Let $a_1>2$ for $j \ge 1$ define
$a_{j+1}=\frac{1}{2}(\frac{4}{a_j}+a_j)$
I am trying to show it is decreasing
First I did the induction method
Base case $a_1=3>2.16667=a_2$
Then Induction hypothesis is let $j=k$ then $a_{k}>a_{k+1}$ then show
$a_{k+1}>a_{k+2}$
So I did
$a_{k+1}=\frac{1}{2}((\frac{4}{a_k}+a_{k})>\frac{1}{2}((\frac{4}{a_{k+1}}+a_{k+1}))=a_{k+2}$
But how do I show this be true??? I am not sure.

A: We can prove that $a_j\gt 2$ for every $j$ by induction using AM-GM inequality :
$$a_{j+1}=\frac 12\left(\frac{4}{a_j}+a_j\right)\gt \sqrt{\frac{4}{a_j}\times a_j}=2.$$
So,
$$a_j-a_{j+1}=-\frac{2}{a_j}+\frac{a_j}{2}=\frac{(a_j+2)(a_j-2)}{2a_j}\gt 0.$$

A: Let $f(x) = \frac{x}{2}+\frac{2}{x}$. For any $x>0$, $f(x)\geq 2$ holds by the AM-GM inequality. On the other hand, since $f(x)-x = \frac{2}{x}-\frac{x}{2}=\frac{4-x^2}{2x}$, $a_1>2$ gives: $$ 2\leq a_{j+1}<a_{j}<a_1$$
for any $j>1$. So $\{a_j\}_{j\geq 1}$ is decreasing and bounded below, hence it is converging to some $L$.
Such $L$ has to be $\geq 2$ and fulfill $L=\frac{L}{2}+\frac{2}{L}$, from which $L=2$ follows.

A: Note that
Newton's iteration for
$x^2 = a$
is
$x_{n+1}
=\frac12\left(x_n+\frac{a}{x_n} \right)
$.
So,
your iteration is
just Newton's iteration
for $\sqrt{4}$.
Look it up.


text: Q: For api call I want to create middelware service in angular 2 For different api call I want to create one middelware service in angular 2 which handle api response, if response expect from 200 page redirect to login.


text:
Q: In useEffect hook, how to find out what event triggered state change? I'm using useEffect hook to perform some sides effects after updating state. And that works perfectly fine, whenever child component invokes setOptions, useEffect fires as well.

I'm trying to figure out if there is a way to differentiate who updated options and based on that perform additonal work? More precisely, I would like to call another function in useEffect only if dependency was updated by specific component. Here's a dumbed down example of what I'm trying to do:

function App() {
  const [value, setValue] = useState({});
  const [options, setOptions] = useState([]);

  useEffect(() => {
    const newValues = await getNewValues();

    setValue(newValues);

    // If options have been changed from ChildComponentA
    // Then doSomething() else nothing
  }, [options]);

  function doSomething() {}

  return(
      <>
        <ChildComponentA handleChange={setOptions} />
        <ChildComponentB handleChange={setOptions} />
      </>
  )
}

The example may be weird, it's just an example of the problem I'm having. The main problem is that state can be changed by multiple events, and I can't tell which event triggered the state change.

A: Maybe you could try adding an additional parameter to your options variable which would tell you from where the change was triggered, i.e options.child = 'A', would tell you it came from A and you could check that within the useEffect with a condition as if (options.child == 'A'), this of course would require options to be an object and not an array and that within the handleChange callback you do something like.
<ChildComponentA handleChange={(value) => {value.child ='A'; setOptions(value);}} />

Going deeper and as a personal recommendation, your app shouldn't aim to work different with the same state if it gets changed by one place or another since one of the main purposes of the state is to be a universal source of truth within your component and that each sub component that uses it treats it as such.


text:
Q: The system cannot execute the specified program in visual studio I have windows 10, and visual studio 2017, target framework is 4.5.1.
I wrote a simple console app, that only prints "Hello world", but when I run the output says:
The system cannot execute the specified program
Please give some advises.

A: Check your anti virus settings, that's might be the issue.


text:
Q: smack cannot retrieve offline messages via OfflineMessageManager I have a problem with while getting offline messages from ejabberd server 18.01 via smack library.
I have a connector method
private static AbstractXMPPConnection connectToServer(String serverHost, Integer port, String userName, String userPassword) {

        DomainBareJid xmppDomain = null;
        try {
            xmppDomain = JidCreate.domainBareFrom(serverHost);
        } catch (XmppStringprepException e) {
            System.out.println("XMPP Domain initialization exception " + e.getMessage());
            return null;
        }

        XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
                .setXmppDomain(xmppDomain)
                .setHost(serverHost)
                .setPort(port)
                .setDebuggerEnabled(true)
                .setSendPresence(false)
                .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
                .build();

        AbstractXMPPConnection connection = new XMPPTCPConnection(config);

        try {
            connection.connect().login(userName, userPassword);
            return connection;
        } catch (XMPPException | SmackException | IOException | InterruptedException e) {
            System.out.println("Something went wrong while connection to server: " + e.getMessage());
            connection.disconnect();
            return null;
        }
    }

and offline messages receiver
private XMPPConnection connection;

    @Override
    public void run() {
        connection = Connector.getInstance();

        if (connection != null) {
            System.out.println("Start listening messages in the background");

            String offlineMessageOffline = "Offline message is %s from %s";

            OfflineMessageManager offlineMessageManager = new OfflineMessageManager(connection);
            try {
                if (offlineMessageManager.supportsFlexibleRetrieval()) {
                    offlineMessageManager.getMessages()
                            .forEach(message -> {
                                System.out.println(String.format(offlineMessageOffline, message.getBody(), message.getFrom()));
                            });
//                    offlineMessageManager.deleteMessages();
                }
            } catch (SmackException.NoResponseException | XMPPException.XMPPErrorException |
                    SmackException.NotConnectedException | InterruptedException e) {
                System.out.println(String.format("Error while getting offline messages from server: by the reason %s", e.getMessage()));
            }
            try {
                connection.sendStanza(new Presence(Presence.Type.available));
            } catch (SmackException.NotConnectedException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            ChatManager chatManager = ChatManager.getInstanceFor(connection);

            IncomingChatMessageListener listener = (entityBareJid, message, chat) -> {
                System.out.println(String.format("Incoming message is %s from %s", message.getBody(), message.getFrom()));
            };
            chatManager.addIncomingListener(listener);
        } else {
            System.out.println("Connection has not been established. Please try to choose option 1");
        }
    }

I start running message listener at the background. I see that database has an offline message and in the dubug node I see that offlineMessageManager.getMessageCount() returns the proper number of offline messages but method offlineMessageManager.getMessages() returns noting. The smack version is 4.2.3 but earlier version has the same problem
UPDATED
I found a workaround because it doesn't look like a obvious solution
public class ListenMessagesFromServerCommand implements Runnable {

    private XMPPConnection connection;

    @Override
    public void run() {
        connection = Connector.getInstance();

        if (connection != null) {
            System.out.println("Start listening messages in the background");

            String offlineMessageOffline = "Offline message is %s from %s";

            OfflineMessageManager offlineMessageManager = new OfflineMessageManager(connection);
            try {
                if (offlineMessageManager.supportsFlexibleRetrieval() && offlineMessageManager.getMessageCount() > 0) {
                    List<String> messagesNodes = offlineMessageManager.getHeaders().stream()
                            .map(OfflineMessageHeader::getStamp)
                            .collect(Collectors.toList());
                    offlineMessageManager.getMessages(messagesNodes)
                            .forEach(message -> {
                                System.out.println(String.format(offlineMessageOffline, message.getBody(), message.getFrom()));
                            });
                    offlineMessageManager.deleteMessages();
                }
            } catch (SmackException.NoResponseException | XMPPException.XMPPErrorException |
                    SmackException.NotConnectedException | InterruptedException e) {
                System.out.println(String.format("Error while getting offline messages from server: by the reason %s", e.getMessage()));
            }
            try {
                connection.sendStanza(new Presence(Presence.Type.available));
            } catch (SmackException.NotConnectedException | InterruptedException e) {
                System.out.println("Error sending presence available type " + e.getMessage());
            }

            ChatManager chatManager = ChatManager.getInstanceFor(connection);

            IncomingChatMessageListener listener = (entityBareJid, message, chat) -> {
                System.out.println(String.format("Incoming message is %s from %s", message.getBody(), message.getFrom()));
            };
            chatManager.addIncomingListener(listener);
        } else {
            System.out.println("Connection has not been established. Please try to choose option 1");
        }
    }
}


text:
Q: BALD-D battle Against Bad Database Design I'm no DBA, but I respect database theory. Isn't adding columns like isDeleted and sequenceOrder bad database practice?

A: IsDeleted columns have two purposes.

*

*To hide a record from users instead of deleting it, thus retaining the record in the database for later use.

*To provide a two-stage delete process, where one user marks a record for deletion, and another user confirms.
Not sure what SequenceOrder is about.  Do you have a specific application in mind?

A: Absolutely not.  Each database has different requirements, and based on those requirements, you may need columns such as those.
An example for isDeleted could be if you want to allow the user interface to delete unneeded things, but retain them in the database for auditing or reporting purposes.   Or if you have incredibly large datasets, deleting is a very slow operation and may not be possible to perform in real-time.  In this case, you can mark it deleted, and run a batch clean-up periodically.
An example for sequenceOrder is to enable arbitrary sorting of database rows in the UI, without relying on intrinsic database order, or sequental insertion.  If you insert rows in order, you can usually get them out of order..until people start deleting and inserting new rows.

A: SequenceOrder doesn't sound great (although you've given no background at all), but I've used columns like IsDeleted for soft deletions all my career.

A: Since you explicitly state that you're interested in the theoretical perspective, here goes :
At the level of the LOGICAL design, it is almost by necessity a bad idea to have a boolean attribute in a table (btw the theory's correct term for this is "relvar", not "table").  The reason being that having a boolean attribute makes it very awkward to define/document the meaning (relational theory names this the "Predicate") that the relvar has in your system.  If you include the boolean attribute, then the predicate defining such a relvar's meaning would have to include some construct like "... and it is -BOOLEANATTRIBUTENAME here- that this tuple has been deleted.".  That is awkward circumlocution.
At the logical design level, you should have two distinct tables, one for the non-deleted rows, and one for the deleted-rows-that-someone-might-still-be-interested-in.
At the PHYSICAL desing level, things may be different.  If you have a lot of delete-and-undelete, or even just a lot of delete activity, then physically having two distinct tables is likely to be a bad idea.  One table with a boolean attribute that acts as a "distinguishing key" between the two logical tables might indeed be better.  If otoh, you have a lot of query activity that only needs the non-deleted ones, and the volume of deleted ones is usually large in comparison to the non-deleted ones, it might be better to keep them apart physically too (and bite the bullet about the probably worse update performance you'll get - if that were noticeable).
But you said you were interested in the theoretical perspective, and theory (well, as far as I know it) has actually very little to say about matters of physical design.
Wrt the sequenceOrder column, that really depends on the particular situation.  I guess that most of the time, you wouldn't need them, because ordering of items as required by the business is most likely to be on "meaningful" data.  But I could imagine sequenceOrder columns getting used to mimick insertion timestamps and the like.

A: That depends. Being able to soft-delete a tuple (i.e., mark it as deleted rather then actually deleting it) is essential if there's any need to later access that tuple (e.g., to count deleted things, or do some type of historical analysis). It also has the possible benefit, depending on how indexes are structured, to cause less of a disk traffic hit when soft-deleting a row (by having to touch fewer indexes). The downside is that the application takes on responsibility for managing foreign keys to soft-deleting things.
If soft deleting is done for performance, a periodic (e.g., nightly, weekly) tasks can clean soft-deleted tuples out during a low-traffic period.
Using an explicit 'sequence order' for some tuples is useful in several cases, esp. when it's not possible or wise to depend on some other field (e.g., ids, which app developers are trained not to trust) to order things that need to be ordered in some specific way for business reasons.

A: Backing up what others have said, both can have their place.
In our CRM system I have an isDeleted - like field in our customer table so that we can hide customers we are no longer servicing while leaving all the information about them in the database.  We can easily restore deleted customers and we can strictly enforce referential integrity.  Otherwise, what happens when you delete a customer but do not want to delete all records of the work you have done for them?  Do you leave references to the customer dangling?
SequenceOrder, again, is useful to allow user-defined ordering.  I don't think I use it anywhere, but suppose you had to list say your five favorite foods in order.  Five tasks to complete in the order they need to be completed.  Etc.

A: Others have adequately tackled isDeleted.
Regarding sequenceOrder, business rules frequently require lists to be in an order that may not be determined by the actual data.
Consider a table of Priority statuses.  You might have rows for High, Low, and Medium.  Ordering the the description will give you either High, Low, Medium or Medium, Low, High.
Obviously that order does not give information about the relationship that exists between the three records.  Instead you would need a sequenceOrder field so that it makes sense.  So that you end up with [1] High, [2] Medium, [3] Low; or the reverse.
Not only does this help with human readability, but system processes can now give appropriate weight to each one.


text:
Q: Add column with initial value from another table Is it possible to set initial value for newly added column from another joined table?
Something like:
ALTER TABLE atable ADD COLUMN mycolumn VARCHAR(255) NOT NULL
VALUE SELECT acolumn FROM something s WHERE s.id = atable.some_id

?

A: I don't think what you want is possible.  Instead, use a separate update command:
ALTER TABLE atable ADD COLUMN mycolumn VARCHAR(255);

update atable a join
       something s
       on s.id = a.some_id
    set a.mycolumn = s.acolumn;


text:
Q: Ansible "become" plugin doesn't work when password variable is set in playbook I have a remote user without sudo and servers with forbidden ssh for root.
So I try to use next approach for privilege escalation:
- block:
  - name: Get hardware password
    shell: |
      slcli --format json hardware detail --passwords {{ hostname }}
    register: json_answer
    delegate_to: localhost
  - name: set hardwareInfo variable
    set_fact:
      hardwareInfo: "{{ json_answer.stdout|from_json }}"
  - name: set password variable
    set_fact:
      ansible_become_pass: "{{ hardwareInfo | to_json | from_json | json_query(password_query) }}"
    vars:
      password_query: "users[?username==`root`].password"
  no_log: true

- name: Install repository deb
  shell: |
    dpkg -i {{ deb_repo_url }}
  become: yes
  become_method: su
  become_user: root

But I get error:

{ "msg": "Incorrect su password", "_ansible_no_log": false }

I checked out ansible_become_pass variable and it has correct password.

A: Found that my variable was in wrong format (array instead of string).
{
    "changed": false,
    "ansible_facts": {
        "ansible_become_pass": [
            "my_password"
        ]
    },
    "_ansible_no_log": false
}

Changed set_fact to this and now it's works
- name: set password variable
  set_fact:
    ansible_become_pass: "{{ hardwareInfo | to_json | from_json | json_query(password_query) | join('') }}"


text:
Q: How can I specify a different path to unzip for file unzip? I am trying to unzip a .zip file from source to destination.
It is taking the default source as:

C:\Program Files\Microsoft Visual Studio 8\Common7\IDE

The source is actually in my project.
Code:
FastZip fz = new FastZip();
fz.ExtractZip("Emp2.zip", Server.MapPath("~/Response Attachments/"), "");

A: typically, we use command-line tool to do the individual job, you can run a script:
unzip XXX.zip -d C:\Program Files\Microsoft Visual Studio 8\Common7\IDE


text:
Q: Using Parse backend with a calendar view iOS I'm trying to develop an app in objective-c that uses Parse as a backend database and has a calendar in it. I have the user base down and I'm trying to use the open source MBCalendarKit to be able to add events to Parse. I don't know if this is a good way of doing things and I'm wondering if it is even possible to add an event from a calendar to Parse in iOS, and if MBCalendarKit is the way to go.

A: Even though Parse is going away, this question might help those with a different backend, so here's the scoop.
You don't create events in MBCalendarKit, but in your own data model. Once you've created your own data model and saved it to your local or remote data store, you can update the calendar UI.
I designed MBCalendarKit to model UITableView's delegation and data source protocols so you can tell it to reload whenever your async methods finish working. Just remember that you would need to do that from the main thread.


text:
Q: Bridged networking is unreliable on VMWare Fusion running Windows 7 I am running Windows 7 under VMWare Fusion on Snow Leopard, connecting to my router via Airport.
When I select "Share the Mac's network connection (NAT)" under the Network options, everything works fine.
But I want the Windows VM to have its own, externally visible, IP Address, so I choose "bridged", and now the internet doesn't work in the VM, or takes ages to find sites, and drops connections sporadically.
Anything I should be doing? Is this an Airport-related problem?

A: Do you have Internet Sharing turned on? (Even if it's not being used, just enabled).  That can cause problems with bridged mode in VMWare Fusion.   I was experiencing something similar, turned off Internet Sharing (wasn't actively using it anyways) and the problem went away.

A: Actuallly, seems like my router was the problem.
I am based in London, using a very recent 2-wire "business broadband" router from BT. Because it doesn't do Wifi "n" (only b/g) I have a Time Capsule bridged to it which serves as my Wifi node.
Seems either the 2-wire or the time capsule don't like VM Ware bridged mode, since I have another wifi connection (Virgin cable) and that works fine.


text:
Q: File not found with New GoogleMaps SDK for iOS I been struggling with the new iOS google maps sdk for some time.
I worked according to the tutorial on: https://developers.google.com/maps/documentation/ios/start
however whenever i tried to compile my simple project i get an error on line:
#import <GoogleMaps/GoogleMaps.h>

file not found...
BTW, I'm working with Xcode 4.5.1
Do you know how to solve this issue?

A: Don't worry google map isn't supported yet for iPhone developers.
because an API key is not generated yet you need to wait for an email from Google. so don't bother applying this tutorial. because eventually it will not work.
click on the below link :
Google Maps not working on iPhone simulator

A: You have to make sure to drag both the .framework package and the .bundle package over into XCode.
.framework package is just the GoogleMaps.framework folder which is in the top-most level of the SDK zip.
.bundle package is found under GoogleMaps.framework/Resources, and is titled "GoogleMaps.bundle"

A: Make sure .bundle file is not copied to the project folder when prompted.


text:
Q: Adding an admin section in Spring I have a Spring web project, which needs an admin section. I assumed this part would be easy and that I would have issues with security, but I can't even point to a /admin/ section.
I have the following in my dispatcher-servelet.xml to map JSP files to controllers:
<context:component-scan base-package="controller"/>
<context:component-scan base-package="controller.admin"/>

<bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/jsp/"
      p:suffix=".jsp" />

There is now a folder labelled "admin" in /WEB-INF/jsp/ and there I have adminindex.jsp. I also have the following in web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
    <security-constraint>
        <display-name>Constraint1</display-name>
    </security-constraint>
    <security-constraint>
        <display-name>admin pages</display-name>
        <web-resource-collection>
            <web-resource-name>Administration Pages</web-resource-name>
            <description/>
            <url-pattern>/admin/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <description/>
            <role-name>eCommerceAdmin</role-name>
        </auth-constraint>
        <!--  <user-data-constraint>
            <description/>
            <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint>-->
    </security-constraint>
</web-app>

When I try and access
localhost:8080/NewWebsite/admin/adminindex.htm
, I get

Access to the requested resource has been denied
INFO: ContextListener:
  attributeAdded('org.apache.jasper.compiler.TldLocationsCache',
  'org.apache.jasper.compiler.TldLocationsCache@44d1bd08')

I have no trouble accessing
localhost:8080/NewWebsite/index.htm, and I would also like to have an auto redirect for the admin folder like it is with the root folder. I.E going to
localhost:8080/NewWebsite/ directs to index.htm.
Any help would be great.

A: FIrst you need to validate the user?isn't it? Otherwise how your application would recognise wheter ADMIN is trying to access or normal USER? Before you do this remove security-constraint from your web.xml
So Add spring authentication in your app.
First Create a pojo class to have a list of GrantedAuthority which should implement org.springframework.security.core.userdetails.UserDetails . Below is a sample:
public class YourPojo implements UserDetails{

    /** The authorities. */
    //This collection will have eCommerceAdmin
    public Collection<GrantedAuthority> authorities;

    /** The username. */
    public String username;

    /** The account non expired. */
    public boolean accountNonExpired;

    /** The credentials non expired. */
    public boolean credentialsNonExpired;

    /** The enabled. */
    public boolean enabled;

    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = -2342376103893073629L;

    /* (non-Javadoc)
     * @see org.springframework.security.core.userdetails.UserDetails#getAuthorities()
     */
    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        return authorities;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.core.userdetails.UserDetails#getPassword()
     */
    @Override
    public String getPassword() {
        return null;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.core.userdetails.UserDetails#getUsername()
     */
    @Override
    public String getUsername() {
        return username;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.core.userdetails.UserDetails#isAccountNonExpired()
     */
    @Override
    public boolean isAccountNonExpired() {
        return accountNonExpired;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.core.userdetails.UserDetails#isAccountNonLocked()
     */
    @Override
    public boolean isAccountNonLocked() {
        return accountNonLocked;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.core.userdetails.UserDetails#isCredentialsNonExpired()
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return credentialsNonExpired;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.core.userdetails.UserDetails#isEnabled()
     */
    @Override
    public boolean isEnabled() {
        return enabled;
    }

    /**
     * Sets the authorities.
     *
     * @param authorities the new authorities
     */
    public void setAuthorities(Collection<GrantedAuthority> authorities) {
        this.authorities = authorities;
    }

    /**
     * Sets the username.
     *
     * @param username the new username
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * Sets the account non expired.
     *
     * @param accountNonExpired the new account non expired
     */
    public void setAccountNonExpired(boolean accountNonExpired) {
        this.accountNonExpired = accountNonExpired;
    }

    /**
     * Sets the account non locked.
     *
     * @param accountNonLocked the new account non locked
     */
    public void setAccountNonLocked(boolean accountNonLocked) {
        this.accountNonLocked = accountNonLocked;
    }

    /**
     * Sets the credentials non expired.
     *
     * @param credentialsNonExpired the new credentials non expired
     */
    public void setCredentialsNonExpired(boolean credentialsNonExpired) {
        this.credentialsNonExpired = credentialsNonExpired;
    }

    /**
     * Sets the enabled.
     *
     * @param enabled the new enabled
     */
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

}

Below is the HTTP tag that you require.
<!-- to use Spring security tags -->
    <bean class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler" />
<http pattern="/login*" security="none"/>
<http pattern="/static/**" security="none"/>
<http auto-config="false">
        <intercept-url pattern="/admin/**" access="eCommerceAdmin" />
        <form-login login-page="/login" default-target-url="/welcome"
            authentication-failure-url="/loginfailed" />
        <logout logout-success-url="/logout" />

        <session-management>
            <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
        </session-management>
    </http>

Now define your authentication provider.
<bean id="customeAuthProvider" class="your.auth.provider.class">
  </bean>

   <authentication-manager >
        <authentication-provider ref="customeAuthProvider" ></authentication-provider>
  </authentication-manager>

This customeAuthProvider should implement org.springframework.security.authentication.AuthenticationProvider.
@Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {

        UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken)authentication;
        String username = userToken.getName();
        String password = (String) authentication.getCredentials();
          //Do whatevr you want with the credentials
         //Then populate the authorities for this credential
         YourPojo user=new YourPojo ();
         user.setUserName("add username");
        //set other details
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<GrantedAuthority>();
        //if user is admin add the below line
        GrantedAuthorityImpl grantedAuthorityImpl = new GrantedAuthorityImpl("eCommerceAdmin");
       //Add other authorities as applicable like 'user' etc.
       user.setAuthorities(grantedAuthorityList);
       return new UsernamePasswordAuthenticationToken(username, password, user.getAuthorities());

FYR you can reference security xml file in your web.xml as below..and also your web.xml should have spring security filters.
<context-param>
 <param-name>contextConfigLocation</param-name>
  <param-value>
    /WEB-INF/your-applicationContext.xml
    /WEB-INF/your-spring-security.xml
  </param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

You need spring security dependencies as well..if you are using Maven for your project add the following dependencies else you can manually download these jars and proceed.
<!-- Spring Security -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>${spring.version}</version>
</dependency>

Now you are good to go..
FYR go through this

A: Have you tried to change your prefix to WEB-INF/jsp/admin/ ?

A: The problem isn't in the viewresolver so the info you provide isn't sufficient to answer your question. Please show a bit more config esp you security configuration.
Besides your question. The component-scan on controller.admin shouldnt be necessary cause the first one will scan it.

A: I think you should consider using spring security, then you can configure spring security role system to control access. Below is a snippet taken form one of my applications, as you can see  the /admin path requires the caller to have a role of Admin. Spring security is a bit complex to setup, but once setup it works very well.
<http auto-config='true' use-expressions="true" >

    <!-- public resources that everyone should be able to access -->
    <intercept-url pattern="/favicon.ico" access="permitAll" />
    <intercept-url pattern="/login"       access="permitAll" />
    <intercept-url pattern="/login/error" access="permitAll" />
    <intercept-url pattern="/**/*.js"        access="permitAll" />
    <intercept-url pattern="/**/*.jsp"       access="denyAll" />

    <intercept-url pattern="/admin/**"     access="hasRole('admin')" />

    </session-management>

</http>


text:
Q: Error using react-leaflet and react-testing-library: useLeafletContext() can only be used in a descendant of  I am using Jest and react-testing-library to test a Create-React-App project (TS) that uses Redux Toolkit for state management and react-leaflet for mapping. I am encountering an error when attempting to render components that have the  component down the tree.
Example test:
import React from 'react';
import { screen, waitFor } from '@testing-library/react';
import { renderWithProviders } from '../renderWithProviders';
import { ForestMap } from '../../Containers/Dashboard/ForestMap';
import { mockServer } from '../mockServer';

beforeAll(() => mockServer.listen());
afterEach(() => mockServer.resetHandlers());
afterAll(() => mockServer.close());

describe('ForestMap', () => {

  test('display map on successful response', async () => {
    renderWithProviders(<ForestMap />);

  });
});

ForestMap.tsx:
/*eslint-disable react-hooks/exhaustive-deps*/
import React, { useEffect, useRef } from 'react';
import { TileLayer, MapContainer, FeatureGroup } from 'react-leaflet';
import { Box } from '@mui/material';
import { EditControl } from 'react-leaflet-draw';
import { LatLng, LatLngBounds, LatLngExpression, Point, PointExpression,
  FeatureGroup as LeafletFeatureGroup } from 'leaflet';
import { useAppDispatch, useAppSelector } from '../../Redux/hooks';
import { useGetForestsQuery } from '../../Redux/api';
import { Forest } from '../Forests/forestTypes';
import { setSelectedForests, setShapeBoundState } from './ForestMapSlice';
import ForestMarker from './ForestMarker';
import 'leaflet/dist/leaflet.css';

const pointInPoly = require('point-in-polygon');//eslint-disable-line

const mapToken = process.env.REACT_APP_MAPBOX_TOKEN;

const zoomValue = 9;

export const ForestMap = (): JSX.Element => {
  const dispatch = useAppDispatch();
  const { bounds, radius, centerPnt, polyPnts,
    selectedForest } = useAppSelector((state) => state.forestMap);
  const { data } = useGetForestsQuery();
  const featureGroupRef = useRef<LeafletFeatureGroup>(null);

  const onCreate = (e: any) => {//eslint-disable-line
    const currentLayers = featureGroupRef.current?.getLayers();
    if (currentLayers && currentLayers.length > 1){
      featureGroupRef.current?.removeLayer(currentLayers[0]);
    }

    if (e.layerType === 'rectangle'){
      const rectBounds: LatLngBounds = e.layer.getBounds() as LatLngBounds;
      dispatch(setShapeBoundState({ bounds: rectBounds }));
    }

    if (e.layerType === 'polygon'){
      const polyLatLngs = e.layer._latlngs[0] as LatLng[];
      const polyPoints = polyLatLngs.map(Object.values) as unknown as LatLng[];
      dispatch(setShapeBoundState({ polyPnts: [...polyPoints] }));
    }

    if (e.layerType === 'circle'){
      const center: Point = e.layer.getLatLng() as Point;//eslint-disable-line
      const rad: number = e.layer.getRadius() as number;//eslint-disable-line
      dispatch(setShapeBoundState({ centerPnt: center, radius: rad }));
    }

  };

  const onDelete = (e: any) => {//eslint-disable-line
    dispatch(setSelectedForests({ selectedForests: [] }));
  };

  useEffect(() => {
    if (bounds && data){
      const rectSelected: Forest[] = [];
      for (let i = 0; i < data.length; i += 1){
        const { coordinates } = data[i].geom;
        if (bounds.contains([coordinates[1], coordinates[0]] as LatLngExpression)){
          rectSelected.push(data[i]);
        }
      }
      dispatch(setSelectedForests({ selectedForets: rectSelected }));
    }
  }, [bounds, data]);

  useEffect(() => {
    if (polyPnts && data){
      const circleSelected: Forest[] = [];
      for (let i = 0; i < data.length; i += 1){
        const { coordinates } = data[i].geom;
        if (pointInPoly([coordinates[1], coordinates[0]] as LatLngExpression, polyPnts)){
          circleSelected.push(data[i]);
        }
      }
      dispatch(setSelectedForests({ selectedForests: circleSelected }));
    }
  }, [data, polyPnts]);

  useEffect(() => {
    if (centerPnt && radius && data){
      const polySelected: Forest[] = [];
      for (let i = 0; i < data.length; i += 1){
        const { coordinates } = data[i].geom;
        if (data[i] && centerPnt.distanceTo([coordinates[1], coordinates[0]] as PointExpression) < radius){
          polySelected.push(data[i]);
        }
      }
      dispatch(setSelectedForests({ selectedForests: polySelected }));
    }
  }, [centerPnt, radius, data]);

  return (
    <Box sx={{ display: 'block' }}>
      <MapContainer
        zoom={zoomValue}
        center={[34.0522, -118.2437]}
        scrollWheelZoom
        style={{ height: '60vh', width: '100%' }}
        zoomControl
        >
          <TileLayer
              attribution='© OpenStreetMap contributors'
              url={`https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/{z}/{x}/{y}?access_token=${mapToken}`}
              no-wrap/>
          <FeatureGroup ref={featureGroupRef}>
              <EditControl
                position='topright'
                onCreated={onCreate}
                onDeleted={onDelete}
                draw={{
                  polygon: true,
                  rectangle: true,
                  polyline: false,
                  circle: true,
                  circlemarker: false,
                  marker: false,
                }}
                />
          </FeatureGroup>
          {data?.map((forest) => {
            const lat = forest.geom.coordinates[1];
            const lng = forest.geom.coordinates[0];
            return (<ForestMarker key={forest.id} id={forest.id as string} coords={[lat, lng] as LatLngExpression} isInSelectedForests={selectedForests?.indexOf(forest) !== -1}/>);
          })}
      </MapContainer>
    </Box>
  );
};

Error message:
    No context provided: useLeafletContext() can only be used in a descendant of <MapContainer>

      42 |       </Provider>);
      43 |   };
    > 44 |   return { store, ...render(ui, { wrapper: Wrapper, ...renderOptions }) };
         |                      ^
      45 | };

      at useLeafletContext (node_modules/react-leaflet-draw/dist/react-leaflet-draw.js:319:11)
      at EditControl (node_modules/react-leaflet-draw/dist/react-leaflet-draw.js:358:17)
      at renderWithHooks (node_modules/react-dom/cjs/react-dom.development.js:14985:18)
      at mountIndeterminateComponent (node_modules/react-dom/cjs/react-dom.development.js:17811:13)
      at beginWork (node_modules/react-dom/cjs/react-dom.development.js:19049:16)
      at HTMLUnknownElement.callCallback (node_modules/react-dom/cjs/react-dom.development.js:3945:14)
      at HTMLUnknownElement.callTheUserObjectsOperation (node_modules/jsdom/lib/jsdom/living/generated/EventListener.js:26:30)
      at innerInvokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:338:25)
      at invokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:274:3)
      at HTMLUnknownElementImpl._dispatch (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:221:9)
      at HTMLUnknownElementImpl.dispatchEvent (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:94:17)
      at HTMLUnknownElement.dispatchEvent (node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:231:34)
      at Object.invokeGuardedCallbackDev (node_modules/react-dom/cjs/react-dom.development.js:3994:16)
      at invokeGuardedCallback (node_modules/react-dom/cjs/react-dom.development.js:4056:31)
      at beginWork$1 (node_modules/react-dom/cjs/react-dom.development.js:23964:7)
      at performUnitOfWork (node_modules/react-dom/cjs/react-dom.development.js:22779:12)
      at workLoopSync (node_modules/react-dom/cjs/react-dom.development.js:22707:5)
      at renderRootSync (node_modules/react-dom/cjs/react-dom.development.js:22670:7)
      at performSyncWorkOnRoot (node_modules/react-dom/cjs/react-dom.development.js:22293:18)
      at node_modules/react-dom/cjs/react-dom.development.js:11327:26
      at unstable_runWithPriority (node_modules/scheduler/cjs/scheduler.development.js:468:12)
      at runWithPriority$1 (node_modules/react-dom/cjs/react-dom.development.js:11276:10)
      at flushSyncCallbackQueueImpl (node_modules/react-dom/cjs/react-dom.development.js:11322:9)
      at flushSyncCallbackQueue (node_modules/react-dom/cjs/react-dom.development.js:11309:3)
      at flushPassiveEffectsImpl (node_modules/react-dom/cjs/react-dom.development.js:23620:3)
      at unstable_runWithPriority (node_modules/scheduler/cjs/scheduler.development.js:468:12)
      at runWithPriority$1 (node_modules/react-dom/cjs/react-dom.development.js:11276:10)
      at flushPassiveEffects (node_modules/react-dom/cjs/react-dom.development.js:23447:14)
      at Object.<anonymous>.flushWork (node_modules/react-dom/cjs/react-dom-test-utils.development.js:992:10)
      at act (node_modules/react-dom/cjs/react-dom-test-utils.development.js:1107:9)
      at render (node_modules/@testing-library/react/dist/pure.js:97:26)
      at renderWithProviders (src/Testing/renderWithProviders.tsx:44:22)
      at Object.<anonymous> (src/Testing/Containers/ForestMap.test.tsx:15:5)

I am using a custom render function as RTL recommends here.
// test-utils.jsx
import React, { FC, PropsWithChildren, ReactElement } from 'react';
import { render, RenderOptions } from '@testing-library/react';
import { PreloadedState } from '@reduxjs/toolkit';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import { RootState, AppStore, setupStore } from '../Redux/store';

// This type interface extends the default options for render from RTL, as well
// as allows the user to specify other things such as initialState, store. For
// future dependencies, such as wanting to test with react-router, you can extend
// this interface to accept a path and route and use those in a <MemoryRouter />
interface ExtendedRenderOptions extends Omit<RenderOptions, 'queries'> {
  preloadedState?: PreloadedState<RootState>
  store?: AppStore
}

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const renderWithProviders = (
  ui: ReactElement,
  {
    preloadedState = {},
    store = setupStore(preloadedState),
    ...renderOptions
  }: ExtendedRenderOptions = {},
) => {
  // eslint-disable-next-line @typescript-eslint/ban-types
  const Wrapper: FC = ({ children }: PropsWithChildren<{}>): JSX.Element => {
    return (
      <Provider store={store}>
        <BrowserRouter>
            {children}
        </BrowserRouter>
      </Provider>);
  };
  return { store, ...render(ui, { wrapper: Wrapper, ...renderOptions }) };
};

All other tests are working as expected.
I have attempted modifying the renderWithProviders function by adding another <MapContainer> itself around children (below BrowserRouter), but this has not worked. I have also attempted to similarly wrap children with LeafletProvider, but I have not found a passed-in value for its prop value that works. My last attempt looked like as follows:
interface ExtendedRenderOptions extends Omit<RenderOptions, 'queries'> {
  preloadedState?: PreloadedState<RootState>
  store?: AppStore
  context?: any, // for use with react-leaflet
}

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const renderWithProviders = (
  ui: ReactElement,
  {
    preloadedState = {},
    store = setupStore(preloadedState),
    context = {},
    ...renderOptions
  }: ExtendedRenderOptions = {},
) => {
  // eslint-disable-next-line @typescript-eslint/ban-types
  const Wrapper: FC = ({ children }: PropsWithChildren<{}>): JSX.Element => {
    return (
      <Provider store={store}>
        <BrowserRouter>
          <LeafletProvider value={context}>
            {children}
          </LeafletProvider>
        </BrowserRouter>
      </Provider>);
  };
  return { store, context, ...render(ui, { wrapper: Wrapper, ...renderOptions }) };


text:
Q: MVC: Whats wrong with this routing? In my Global.asax file I have the following;
 public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Account", action = "LogOn", id = UrlParameter.Optional }); // Parameter defaults

        routes.MapRoute(
            "Contracts",
            "Contract/{contractId}",
            new { controller = "Contract", action = "Details" }
            );

I want to specify a route Contract/10 where 10 is the contractId which is the parameter for the Detail method in my ContractController.
So this works;
http://localhost:1234/Contract/Details?contractId=10
But not
http://localhost:1234/Contract/10
What am I doing wrong?

A: Put the "Default" route last after the "Contracts" route and all will be well.
The routing table finds the first match from top to bottom then stops looking. With this in mind always put more specific routes above the more generic ones
    routes.MapRoute(
        "Contracts",
        "Contract/{contractId}",
        new { controller = "Contract", action = "Details", contractId = UrlParameter.Optional }
        );

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Account", action = "LogOn", id = UrlParameter.Optional }); // Parameter defaults

Then make sure the Details action method in you ContractController accepts a parameter called contractId.

A: Change
   routes.MapRoute(
            "Contracts",
            "Contract/{contractId}",
            new { controller = "Contract", action = "Details" }
            );

To
   routes.MapRoute(
            "Contracts",
            "Contract/{action}/{contractId}",
            new { controller = "Contract", action = "Details" }
            );

And put it before the Default route.

A: Are you saying that typing in "http://localhost:1234/Contract/Details?contractID=10" does work and "http://locatlhost:1234/Contract/10" does not work?  Have you tried: "http://localhost:1234/Contract/Details/10"?  Or in the "Contracts" MapRoute, put after "action = "Details"": ", contractId = UrlParameter.Optional.  This way, it will look like this.
   routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Account", action = "LogOn", id = UrlParameter.Optional }); // Parameter defaults

    routes.MapRoute(
        "Contracts",
        "Contract/{contractId}",
        new { controller = "Contract", action = "Details", contractId = UrlParameter.Optional }
        );


text:
Q: Why doesn't Stackoverflow use Ajax for the edit feature? Why doesn't Stack Overflow use Ajax for the "edit question" feature?
It would be better for the user i think right? It would load faster. Plus they would use less bandwidth.
Are there any downsides for doing it?
My only guess is, that it's more work, because you have to sync the client and the server data.


text:
Q: Sorting array by float value I am having some trouble sorting an array by a float value. I have searched around the web, and I understand that I have to use a comparision function, but I am having issues understanding the concept.
I am using this code to read an xlxs file and pushing the values I need to a simpler array. I need to sort this array by the value of the top2box key so the highest value is key 0.
Here is my current code
// data is an array of arrays, lets loop through it to sort. The array contains each row of my xlxs file.

    var hon = [] //array that will hold the sorted entries from the excel file

    for(var i = 0; i < data.length; i++) {

        // we dont want empty data. each row has a key named Business Unit. In empty rows the value of the key is the name of the key. We dont need that data.
        if (data[i][3] != '' && data[i][0] != 'Business Unit') {

            // data belongs to an actual person
            // round top2box to display the percentage.

            // push the values we need to a simpler array
            hon.push({
                country: data[i][0],
                team: data[i][2],
                name: data[i][3],
                top2box: data[i][4],
                sumofvotes: data[i][5]
            })
        }
    }

    // loop done lets sort each array entry by top2box value. So highest top2box is the first entry of the array
    hon.sort(function(a,b) { return a.top2box - b.top2box;});

    // show the result.
    console.log(JSON.stringify(hon, null, 4));

However when displaying the results all of the top2box entries have been changed to "1" and is not sorted (probable due to this aswell)
The values of hon is a float, which will need to be shown as a percentage later on. Here are some example values. I need to maintain these exact values, but order them highest to lowest, so I can loop through the array and display them as html later.
"country": "Norway",
"team": "NO-Aftersales",
"name": "Andersen, Dennis",
"top2box": "0.47368421052631599",
"sumofvotes": "19"

Here is another
"country": "Sweden",
"team": "SE-AS",
"name": "Vuong, Adele",
"top2box": "0.51515151515151503",
"sumofvotes": "33"

SOLUTION
Turns out JSON.stringify(); was the root of the problem. Removing this from the console.log. So it instead is console.log(hon) shows the correct data and also sorts them correctly. Json stringify is not treating floats very nice.

A: You need to save the result of 'sort' like this:
var hon = [
{
    country: 'some country',
    team: 'some team',
    name: 'some name',
    top2box: 123123,
    sumofvotes: 123123
},
{
    country: 'some country2',
    team: 'some team2',
    name: 'some name2',
    top2box: 123,
    sumofvotes: 123
}
];

hon = hon.sort((a, b) => {return a.top2box - b.top2box}); // save the sort result
// (a - b) = Ascending sort, (b - a) = Descending sort

console.log(hon);

You can read more about sort here - Array#Sort and about Arrow functions here - Functions#ArrowFunctions


text:
Q: Cairo load image from data I have a doubt with cairo library.
I downloaded an image and I put it into a buffer memory. Is there any solution in cairo to load an image from data that there is in memory?
Thanks

A: Give a look to cairo_image_surface_create_for_data.

A: You can load image data from memory, but you need to lay out that memory in the correct format that Cairo expects.
For what you describe, it's probably easier to save the data in a tmpfile and let Cairo load it using FILE operations. Cairo recognizes more formats as filetypes than it does as in-memory structures.
When I used cairo_image_surface_create_for_data for bitmaps, I had to convert my byte-oriented Big-endian bitmap data into 32bit-word-oriented Little-endian rows.
You can tell from the littering of comments, that at times my efforts were reduced to hunt-and-peck, trial-and-error methods. But I got the desired output with this code. Steal from it what you can.
One more thing: The documentation for the in-memory formats (A8, RGB24, ARGB32) is in the .header files, not the reference manual.
enum { BIG, LITTLE } endian = LITTLE;

inline unsigned char reverse(unsigned char b) {
    return (b&1 ? 0x80: 0)
         | (b&2 ? 0x40: 0)
         | (b&4 ? 0x20: 0)
         | (b&8 ? 0x10: 0)
         | (b&0x10 ? 8: 0)
         | (b&0x20 ? 4: 0)
         | (b&0x40 ? 2: 0)
         | (b&0x80 ? 1: 0);
}

inline unsigned long wreverse(unsigned long w) {
    return ( ( w     &0xFF) << 24)
         | ( ((w>>8) &0xFF) << 16)
         | ( ((w>>16)&0xFF) << 8)
         | ( ((w>>24)&0xFF) );
}

unsigned char abit[2] =  { 0, 0xFF };
unsigned char aspeck[4] = { 0, 0x55, 0xAA, 0xFF };
unsigned char anibble[16] = { 0, 36, 72, 108, 144, 180, 216, 255 };
unsigned char *amap[] = { abit, aspeck, anibble };

void drawimage(state *st, int wid, int hgt, int bits, unsigned char *samp, unsigned char *tmap) {
    int stride;
    //stride = cairo_format_stride_for_width(CAIRO_FORMAT_A8, wid);
    stride = cairo_format_stride_for_width(CAIRO_FORMAT_RGB24, wid);
    //stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, wid);
    int n;
    //unsigned char data[n=stride*hgt];
    unsigned char data[n=stride*hgt*4];
    memset(data, 0, n);
    //unsigned char *data; data = calloc(n=stride*hgt, 1);
    unsigned long *ldata = (void *)data;

    int spo = 8/bits; /* samples per octet */
    int span = wid/spo + (wid%spo?1:0); /* byte width */
    int i,j;
    for (i=0; i < hgt; i++) {
        for (j=0; j < wid; j++) {
            unsigned char t;
            /*if (bits==8) t = samp[i*span + j/spo];
            else*/ t = ( ( samp[i*span + j/spo] >> (/*7 -*/ (j%spo)/* *bits */) )
                     & (0xFF >> (8-bits)) ) /*<< (8-bits)*/;
            if (bits < 8) t = amap[bits==1?0:bits==2?1:2][t];
            t = tmap[t]; /* map value through the transfer map */
            //printf("%2X ", t);
            //data[i*stride + j] = t;
            ldata[i*stride/4 + j] = /*0x80<<24 |*/ t<<16 | t<<8 | t;
        }
        //puts("");
    }
    /*
    for (i=0; i < hgt; i++) {
        //for (j=0; j < stride; j++)
            //printf("%2X ", data[i*stride + j]);
        for (j=0; j < stride/4; j++)
            printf("%2lX ", ldata[i*stride/4 + j] & 0xFF);
        puts("");
    }
    */

    cairo_surface_t *surf;
    //surf = cairo_image_surface_create_for_data(data, CAIRO_FORMAT_A8, wid, hgt, stride);
    surf = cairo_image_surface_create_for_data(data, CAIRO_FORMAT_RGB24, wid, hgt, stride);
    //surf = cairo_image_surface_create_for_data(data, CAIRO_FORMAT_ARGB32, wid, hgt, stride);
    //cairo_mask_surface(st->cr, surf, 0, 0);
    cairo_set_source_surface(st->cr, surf, 0, 0);
    cairo_paint(st->cr);
    cairo_surface_flush(st->surface);
    if (st->dis) XFlush(st->dis);
    cairo_surface_destroy(surf);
    //free(data);
}

OPFN_ void image(state *st, object w, object h, object bits, object mat, object proc) {
    unsigned char tmap[256];
    switch (bits.u.i) {
    case 1: case 2: case 4: case 8: break;
    default: error(st, rangecheck);
    }
    int n;
    int i;
    unsigned char data[n=w.u.i*h.u.i/(8/bits.u.i)];

    /* map gray scale through the transfer function */
    for (i = 0; i < 256; i++) {
        object v;
        v = consreal((double)i/255);
        push(v);
        pushe(consoper(st, "quit", NULL,0,0));
        pushe(consoper(st, "exec", NULL,0,0));
        pushe(consoper(st, "currenttransfer", NULL,0,0));
        run(st);
        v = pop();
        if (v.tag==integertype) promote(v);
        if (v.tag!=realtype) error(st, typecheck);
        tmap[i] = v.u.r * 255;
    }

    for (i = 0; i < n; ) {
        object s;
        pushe(consoper(st, "quit", NULL,0,0));
        pushe(proc);
        run(st);
        if (tos-os < 1) error(st, stackunderflow);
        s = pop();
        if (s.tag != stringtype) error(st, typecheck);
        memcpy(&data[i], STR(s), s.u.c.n);
        i += s.u.c.n;
    }
    if (DEBUG) { for (i=0; i<n; i++) { printf("%02x ", data[i]); } puts(""); }

    if (st->cr) {
        gsave(st);
            cairo_new_path(st->cr);
            cairo_rectangle(st->cr, 0, 0, 1, 1);
            cairo_clip(st->cr);

            {   cairo_matrix_t cm, icm;
                psm2cm(st, mat, &cm);
                cminvert(&cm, &icm);
                cairo_transform(st->cr, &icm);
            }

            cairo_set_source_rgb(st->cr, 0.0, 0.0, 0.0);
            drawimage(st, w.u.i, h.u.i, bits.u.i, data, tmap);
        grestore(st);
    }
}

A: Maybe you want something like gdk_pixbuf_new_from_data
http://developer.gnome.org/gdk-pixbuf/stable/gdk-pixbuf-Image-Data-in-Memory.html#gdk-pixbuf-new-from-data


text:
Q: in c#, how to make the form to be active all the so that scanned barcode doesn't get lost I have written a small application in c# which collects scanned barcodes. First scanned barcode goes into a txtbox, then I write them into a txt file. So the application window has to be active all the time. Sometimes if another window pops up, my application becomes inactive and the scanned barcodes are lost. Is there any way I can make my application window to be active all the time.

A: You could use a timer that constantly brings the form to the front and activates it, while not perfect, it should get the job done.
private void Form1_Load(object sender, EventArgs e)
{
    this.TopMost = true;
    Timer t = new Timer();
    t.Tick += new EventHandler(t_Tick);
    t.Interval = 50;
    t.Start();
}

void t_Tick(object sender, EventArgs e)
{
    this.BringToFront();
    this.Activate();
}


text:
Q: How to setup MiniProfiler for SQL profiling in EF 5 using ObjectContext? I have a WebApi setup and due to some reasons, I am facing performace issues with some of the api methods.
I would like to use MiniProfiler and to test the performance of these API methods and log the statistics delivered by Miniprofiler in to a Table.
The miniprofiler docs asks to add the follwing code,
using StackExchange.Profiling.Data;
...
public static MyModel Get()
{
    var conn =  new EFProfiledDbConnection(GetConnection(), MiniProfiler.Current);
    return ObjectContextUtils.CreateObjectContext<MyModel>(conn);
}

Can somebody help me where actually this needs to be added, how the table will be Created and configured?
N.B: I am using EF 5 with Object Context Database First approach(Not DbContext)


text:
Q: CSS skew issue - child elements skewing despite opposite skew added I'm trying to get a skewed nav, but the links are skewing with the nav. I understand the code should work if it's like this:
#nav {
   transform: skew(-15deg);
}
#nav li {
   transform: skew(15deg);
}

But that's not working. Here's a fiddle: http://jsfiddle.net/U5mq5/
Again, I want my nav li a to be straight, not slanted. Help?

A:
CSS Transforms Module Level 1
A transformable element is an element whose layout is governed by the CSS box model which is either a block-level or atomic inline-level element, or whose display property computes to table-row, table-row-group, table-header-group, table-footer-group, table-cell, or table-caption.

Therefore the display of the elements should be changed from inline to inline-block in order for skew() to work. In addition, I added white-space: nowrap in order to prevent the text from wrapping to a new line.
UPDATED EXAMPLE HERE
#nav ul li {
    display: inline-block;
    padding: 0 0 0 3.5%;
    transform: skew(15deg);
    -webkit-transform: skew(15deg);
    white-space: nowrap;
}


text:
Q: How do I remarshal a modified message with ActiveMQ (OpenWire)? First a little explanation of what I'm trying to do. I am writing a Java (1.7) application that will attempt to "fuzz" XML messages sent over ActiveMQ, using the OpenWire format from a producer to a target consumer. The intent is to gauge how the target responds to the fuzzed messages sent to it. I am using ActiveMQ version 5.12.1 on Linux CentOS 6.6.
There is an XML schema which defines the message types that will be sent. I have separate programs that generate sample instances of these messages and identifies where information is found in the wire format sent (OpenWire in this case). This information will be used in the fuzzing process to know the location of the data to change.
Part of the fuzzing process involves capturing the wire format message off the wire, making the change and forwarding the modified message on to the target. I have been able to successfully modify data and send it forward, as long as I have changed only content and not length. If the modification results in a change in length, the connection to the ActiveMQ server closes and the program fails.
Research indicates that the OpenWire messages all start with a 4 byte integer, representing the length of the following message data. I changed my code to adjust that length to reflect the change made to the test data. That did not work. After some more investigation, I discovered that just changing the length field was not the right thing to do - but it was not obvious what should (or could) be done.
I'm getting a strong impression, that the best thing to do would be to use the ActiveMQ API to re-marshal the modified message data and forward that on to the target. I have no idea if that's an option available to me.
I've tried to find information to help me determine the structure of the OpenWire messages involved so that I can know what I need to do when modifying the message. I started looking at the ActiveMQ javadocs and found the openwire packages. Perhaps I can utilize these to effect the changes I need to make and to have them successfully forwarded via ActiveMQ and received by the target.
Is there any documentation or sample code that provides instruction or examples of how to properly use this API to do what I need? Based on what I've described, is this something that is doable using the API? Any help would be appreciated. Thanks.

A: Have a look at http://camel.apache.org
There is no need to interpret the wire format directly.
Can even run in amq server.

A: It sounds like you want to send Xml data over ActiveMQ.

*

*You don't need to worry about Openwire. The client libraries handle that for you. That is the protocol that the ActiveMQ JMS library uses to talk to ActiveMQ, while your program only has to worry about how to talk JMS.

*Decide what API to use to talk to ActiveMQ.. if it is Java, use the JMS API and send a TextMessage object where the body is set to the string representation of the Xml data. If it is C#, look at ActiveMQ's NMS library. If PHP/Python/Perl or other scripting language, look for STOMP libraries and send Text messages with the Xml data as the body.


text:
Q: Creating dynamic asp.net label with Javascript I have a asp.net label inside a
 <td>
 <asp:Label ID="errorMesaage" runat="server">
   </td>

I want to create an asp.net label dynamically and append it to this td using JAVASCRIPT.
Then after appending this td would have another error message with a different id.
I also need a script that would also remove the item from the
Any help is appreciated.

A: No, you can't because the asp.net label is a server control so does not make sense in client code, ie on code rendered on client.
If you add it with javascript in your page it will not work at all.
You can add asp.net label dinamically in your server side code with something like
var lbl = new Label();
Page.Controls.Add(lbl);

A: I found a solution...what I did was that I cloned my current asp.net label using the Javascript clone method.


text:
Q: How to see db tables when using entity framework model first I have tried to use Entity Framework "model first" in VisualStudio2010, so i created the model with all the entities and the relationships on the .edmx file and generated the database.
but when i open SQL Server management studio i see that a new db was created but with no tables.
Am i supposed to see the tables?


text:
Q: image segmentation with the given coordinate data I have a bunch of image data and the corresponding coordinate data which divided the images into several parts, lets assume there are A, B, C, and D parts, these parts of each image are in different positions. I try to build a model to train them, and then predict that the image will correctly correspond to each of these four parts.
My idea is to make the image segmentation first and then do image classification.
So how do I make image segmentation with the given coordinate data, and what model and method should I use (if with PyTorch)?
Thanks in advance

A: I recently was working through the Deep learning with Python book by Francois Chollet.
Here is his notebook of applying image segmentation with tensorflow (sorry not Pytorch but concepts may be useful) on the Pet dataset.
https://github.com/fchollet/deep-learning-with-python-notebooks/blob/master/chapter09_part01_image-segmentation.ipynb
To summarize - you'll need a folder containing your images, and a folder containing the image segmentation masks (also images). Each pixel on the mask could be either 0,1 or 2 for instance. So if you was to visualize it using matplotlib (when you multiply by 127, you have either black (0), 127 (gray) or 254 (near-white). Each pixel in your image should be a value between 0-1, you'll see in the neural network afterwards how we scaled this by dividing by 254.
The logic of your neural network is as follows:

*

*Conv2D operations are used to transform your data, finding useful features. The first few stacks will find basic things like vertical and horizontal edges. The deeper layers will then start to identify more meaningful representations, for example it could be an eye, face, ears.

*The transformations aren't predefined, these are actually unknowns (weights), that the model will figure out itself.

*Since there would be a large number of parameters we tend to downsample to prevent overfitting. In image classification we tend to use MaxPooling, but in image segmentation you want to use strides instead. This is because MaxPooling tends to destroy spatial information (you are taking a large grid of values and transforming it into one value, aggressively removing information. Strides are better for object detection/image segmentation tasks.)

*The output from these layers is representing large chunks of the image, with a reduced number of features (kind of like compression).

*However since we want to to predict a class for each pixel in image segmentation, we'll need to return to the original shape of the input image. So you'll have a new stack of convtranspose layers, which does the opposite to compression in order to return to the original image size.

I hope the above provided some basic theory.
At a high level you need to build a neural network that follows these general principles:
You'll have two key stacks of layers.
The first stack is as follows:

*

*Use conv2d layers with padding=same (and some of them to have a stide=2 to downsample)

This could look like the following:
def get_model(img_size, num_classes):
inputs = keras.Input(shape=img_size + (3,))
x = layers.Rescaling(1./255)(inputs)

x = layers.Conv2D(64, 3, strides=2, activation="relu", padding="same")(x)
x = layers.Conv2D(64, 3, activation="relu", padding="same")(x)
x = layers.Conv2D(128, 3, strides=2, activation="relu", padding="same")(x)
x = layers.Conv2D(128, 3, activation="relu", padding="same")(x)
x = layers.Conv2D(256, 3, strides=2, padding="same", activation="relu")(x)
x = layers.Conv2D(256, 3, activation="relu", padding="same")(x)

The second stack of layers is an inverse of the above. Instead of 'compression', we are now trying to return to the original shape size of the image since in image classification, each pixel belongs to a class.
x = layers.Conv2DTranspose(256, 3, activation="relu", padding="same")(x)
x = layers.Conv2DTranspose(256, 3, activation="relu", padding="same", strides=2)(x)
x = layers.Conv2DTranspose(128, 3, activation="relu", padding="same")(x)
x = layers.Conv2DTranspose(128, 3, activation="relu", padding="same", strides=2)(x)
x = layers.Conv2DTranspose(64, 3, activation="relu", padding="same")(x)
x = layers.Conv2DTranspose(64, 3, activation="relu", padding="same", strides=2)(x)

Finally you will apply a softmax function since you are classifying between multiple outputs as seen below:
outputs = layers.Conv2D(num_classes, 3, activation="softmax",
padding="same")(x)
model = keras.Model(inputs, outputs)
return model

Finally, if the performance isn't as expected, residual blocks and batch normalization are two key things that can help improve your model but I won't go into it in this post.
My best advice would be to work through an example online, or the one I provided above to help replicate it on some new data.


text:
Q: How to understand the concept of vanishing point? Consider the diagram below:

We can see from the plane $\Phi$ two parallel lines on its surface. Then these two lines are projected onto the plane $\Pi$ where they appear to be intersecting.
My question is how did they become intersecting? and how is the perspective defined in this figure? that is to say from what field of view is the person looking at this diagram to see this phenomena? Because I don't understand what this diagram is specifically describing when it connects all these rays to the optical center $O$.
I have attached an example of train tracks and hope someone can help me understand it as an example of this phenomena

A: In the train track picture, the rails never meet, but appear to.  The point where they appear to meet is infinitely far away, but there is a definite angle to look to see the point of intersection (we must look at the middle of the picture).
In the top diagram the observer at $O$ must look in the direction $O\Pi$ to see where the two lines appear to meet (even though they never actually meet).

A: The diagram is confusing, but if you let the O be the observer and the two points in the region Φ be on two rails, then as the rails move away from the observer, the visual angle between them gets smaller. (You have a triangle with a fixed base, but an increasing height.)

A: Consider a two-dimensional case where a point on the x-axis is being projected onto the y-axis. Let's say we have a person at point P with coordinates $(P_x,P_y)$, an object at point A at coordinates $(A_x,0)$, and a point on the y-axis A' that A is projected onto at coordinates $(0,A'_y)$. We can draw a right triangle $(A_x,0),(0,0),(0,A'_y)$, and another right triangle $(A_x,0),(P_x,0),(P_x,P_y)$. The term "projection" refers to the line from P to A' being the same as the one going from P to A, so these two triangles are similar, and from that we can conclude that $\frac {P_x}{P_x+A_x}=\frac{P_y-A'_y}{A'_y}$. If we solve for $P_y-A'y$, we get $P_y-A'_y=\frac{P_xA'_y}{P_x+A_x}$. Thus, as the distance to A goes to infinity, the vertical separation between the person and the projected point goes to zero. The point with no vertical separation is the vanishing point. Since all lines are converging towards this point as they go to infinity, they also converge to each other.


text:
Q: Flutter Laravel API update user I tried to make crud, so how to update a user without changing his photo because if I pass a photo the update works perfectly but if I didn't pass the photo I got Exception: Invalid image data and the value of photo change in database.
Here is my Laravel code
$product=Products::findOrFail($id);
    $validator = Validator::make($request->all(), [
        'name' => 'required',
        'price'=>'required',
        'detail' => 'required',
        'quantity' => 'required',
        'discount' => 'required'
    ]);
    $input = $request->all();
    if(!is_null($input['photo'])){
        $image = $input['photo'];
        $image = str_replace('data:image/png;base64,', '', $image);
        $image = str_replace(' ', '+', $image);
        $imageName = Str::random(50).'.'.'png';
        if(!is_dir('/uploads/products')) {

            mkdir('/uploads/products', 0755, true);
        }
        Storage::disk('public_uploads')->delete($product->photo);
        Storage::disk('public_uploads')->put($imageName, base64_decode($image));

        $product->photo = $imageName;

    $product->name = $input['name'];
    $product->price = $input['price'];
    $product->detail = $input['detail'];
    $product->quantity = $input['quantity'];
    $product->update();

A: If statement should be like this
if($request->hasFile('photo')){
    //
}

instead of this
if(!is_null($input['photo'])){
    //
}

https://laravel.com/docs/8.x/requests#files


text:
Q: Fiddler Script - SaveResponseBody() I want to save all png images that are loaded along with some webpage into a separate folder.
I am using below code with in Fiddler Script [CustomRules.js].
static function OnBeforeResponse(oSession: Session)
{
if(oSession.url.EndsWith(".png"))
{
oSession.SaveResponseBody();
}
//Actual content of  OnBeforeResponse function.
}

Problem here is, I was unable to find any image got saved within Program files/Documents.
Where do "SaveResponseBody()" will save the HTTP Response Body?
Can we give our own custom folder?
My Fiddler version is (v4.4.5.6)

A: The default SaveResponseBody() method saves the files to your \Documents\Fiddler2\Captures\ folder. If you want to use a different name, use the overload that accepts a filename. You should check the Response's status code is 200 to ensure that you're not trying to save off HTTP/304 responses which won't contain a body. Also, rather than looking at the URL, you probably want to check the response's type.
So you end up with something like this:
if ((oSession.responseCode == 200) &&
   oSession.oResponse.headers.ExistsAndContains("Content-Type", "image/png"))
{
  SaveResponseBody("C:\\temp\\" + oSession.SuggestedFilename);
}

Note: The manual way of doing this would be to go to the QuickExec box below the Web Sessions list, type select png and hit Enter, then click File > Export > Selected Sessions > Raw Files.


text:
Q: Conditions for col $\mathbf{A} = \mathbb{R}^m$? Say I have an $m \times n$ matrix $\mathbf{A}$. What are the conditions of $\mathbf{A}$ needed for the column space of $\mathbf{A}$ to be equal $\mathbb{R}^m$ - that is, the basis of col $\mathbf{A}$ is also a basis of $\mathbb{R}^m$?. In other words, col $\mathbf{A} = \mathbb{R}^m$.
For example, if you have rank $\mathbf{A} = m$ and $m \leq n$, is col $\mathbf{A} = \mathbb{R}^m$? If so, why?

A: As the column space of $A$ is a subspace of $\mathbb R^m$, if its dimension is equal to $m$, it must be equal. So, is $\operatorname{rank}(A) = m$, then the column space if $\mathbb R^m$, there are no need to assume that $m \leq n$. Also, another (equivalent) condition is that the columns of $A$ forms a linearly independent set of $\mathbb R^m$, that is, $Ax = 0$ implies that $x = 0$.

A: Reduce the matrix. m <= n mean 2x3 or 3x3 (square) At most you will have m pivots meaning you will have m linearly independent columns. What is the rank? Gilbert Strang says the rank is the number of pivots after row reduction. We know that the linearly independent columns is the linear combinations of the columns that spans the C(A).


text:
Q: What is causing SyntaxError: Unexpected EOF error in underscore template? I am getting a SyntaxError: Unexpected EOF output when using an underscore template to render html in a Backbone application. Here is my template:-

It is specifically erroring on this part:-
id="<%= _.escape(menuItem.id)"

The id attribute is a number, here is the menuItem object:-
dataPath: ""
helpType: "default"
id: 0
moduleName: "TestModule"
modulePath: "interaction/test/testmodule"
title: "Test Module Interaction"

I have tried making the id a string or making it the title attribute in the underscore template code just to see if I can get a test case working in any shape or form but I am stumped so far. I have a similar template doing pretty much the same thing with no errors.
Any ideas what silliness I am engaging in to cause this? :-)

A: Looks like you didn't close <%= with %>


text:
Q: Is it possible to use the __dict__ attribute on an instance of a cython defined class? I have a vector class I have defined in cython, and I am trying to show some of the attributes to users. I want to iterate over them using the __dict__ attribute, but I'm getting an error that my object does not contain that attribute. Is it possible to use the __dict__ attribute on instances of cython defined objects?
For example:
from my_cython_lib import vector

v1 = Vector()
for attrtibute in v1.__dict__:
    # do stuff to the attribute

My vector class:
cdef class Vector:
    def __cinit__(self):
        self.x = None
        self.y = None
        self.z = None


text:
Q: Does having two exports increase bundle size If I have the following code
class x {
    ...
}
export CreateFragmentContainer(x,graphqlQuery)

Will the bundle size of my project if I do an another export of class x without the fragmentContainer such as the below?
export class x {
    ...
}
export CreateFragmentContainer(x,graphqlQuery)

Also, will the answer to this question change depending on the framework used?

A: The bundle size increases only if you import both at the same time, or when you have a default export + named exports, but just use the default export.
What i mean:
export default class {
    ...
}

export const a = '1';

----

Import Something from './myfile'

vs
export default class {
    ...
}

export const a = '1';

----

Import { a } from './myfile'

Method 2 has lower bundle size.
No, it does not depend on the framework, it is a "language feature".


text:
Q: How can I restore the pam file system-auth? In my Centos 7 machine, and as an inexplicable mistake, I ran:
rm  /etc/pam.d/system-auth

Now, my system won't boot up, the network does not work, and in a few words, the system is trashed.
I tried to fix the problem with single user mode and running
ln -s /etc/pam.d/system-auth-ac /etc/pam.d/system-auth

This did not make any change and, after rebooting, my system is still not working.
The only solution that I found involves restoring the symlink from emergency mode, the challenge is, that emergency mode requires the root password which I don't have, and I don't seem to be able to change it from single user mode.
 Steps to reproduce:

 In a new CentOS installation:

• sudo rm  /etc/pam.d/system-auth
• Restart
• You will notice that the system won't reach the login page(if Gnome or KDE are enabled). Otherwise, you will reach the login page but it won't work even if you have the right credentials.

Error I received I tried to login in emergency mode after I changed the root password in single user mode.

Steps trying to fix it :
• Enter single user mode enabling it with rw init=/bin/bash
• ln -s  /etc/pam.d/system-auth-ac /etc/pam.d/system-auth

Thank you

A:
I mistakenly did rm  /etc/pam.d/system-auth

that file is actually a link to /etc/pam.d/system-auth-ac
at least looking at my RHEL 7.8 system at the moment, I expect it to be the same for CentOS.
So you may be able to simply boot your system using the CentOS install dvd (or usb stick) or any recovery type of live linux where you can mount your broken operating system's partition as read write.  Then it may simply be a matter of doing, as root,
ln -s   /etc/pam.d/system-auth-ac   /etc/pam.d/system-auth

If that didn't fix it, then here is the contents of /etc/pam.d/system-auth-ac as it is in my RHEL 7.8 system Linux 3.10.0-1127.8.2.el7.x86_64, which should be the same as CentOS.  Simply recreate that /etc/pam.d/system-auth file being this.
# This is the contents of   /etc/pam.d/system-auth-ac   from RHEL 7.8

#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth        required      pam_env.so
auth        required      pam_faildelay.so delay=2000000
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 200000 quiet_success
auth        required      pam_deny.so

account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 200000 quiet
account     required      pam_permit.so

password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=
password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
-session     optional      pam_systemd.so
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so

If you suspect SELINUX compounding the problem, then all you should need to do is edit /etc/selinux/config and do SELINUX=permissive

A: Don't forget selinux.  Sestatus may tell you.
I'm not good enough with selinux.  So if sestatus says enforcing, then
sed -i~ '/SELINUX=/s/=.*/=permissive/' /etc/selinux/config

and the reboot should kick it into allowing that system-auth to be used.
It's not an awesome fix if your home/shop loves it some selinux, but you should/can figure out the proper context to spackle around system-auth, relabel that, re-enable selinux on the box, bounce again and move on.


text:
Q: Windows service and MS Access on UNC I am trying to get my Windows service to connect to an MS Acces database that is located on a UNC
private static void InsertData(string sql)
    {
        System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();

        conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
                                @"Data source=\\svr\Users\XXXX\XXXXX\db.accdb";

        try
        {
            conn.Open();
            OleDbCommand cmd = new OleDbCommand(sql, conn);
            cmd.ExecuteNonQuery();

            WriteToFile("Data saved successfuly...!");
        }
        catch (Exception ex)
        {
          WriteToFile("Failed due to: " + ex.Message);
        }
        finally
        {
            conn.Close();
        }
    }

This is the error I get
"The Microsoft Access database engine cannot open or write to the file '\svr\Users\XXXX\XXXXX\db.accdb'. It is already opened exclusively by another user, or you need permission to view and write its data."
The permissions are set to domain users, read, write and modify etc. The database is not open by anyone.
I have tried the exact code in a console app and it works fine.
Any ideas?

A: I just remembered where you could have an issue.  I remember having issues with the 64-bit ODBC vs. 32-bit ODBC!
If you are running 32-bit Ms Access you have to use 32-bit ODBC executable at path C:\Windows\SysWOW64\odbcad32.exe!
You have to setup the connecting first:
1) C:\Windows\SysWOW64\odbcad32.exe started as administrator and clicking on button add:

2) Then enter your connection here:

First edit An example of filling the ODBC Data Source:

Don't forget that afterwards you are addressing your newly create data source.


text:
Q: Mathematical rectangle function Python I want to make convolution of gaussian and rectangular functions like that:
from numpy import linspace, sqrt, sin, exp, convolve, abs
from matplotlib import pyplot as plt

def gauss(x, x0=0, sigma=1):
    return exp(-1*(x-x0)**2/(2*sigma**2))

def rect(x):
    return 1 if abs(x)<=0.5 else 0

x = linspace(-10, 10, 100)

f1 = gauss(x, sigma=1)
f2 = rect(x)
fsum = convolve(f1, f2)

y = linspace(-10, 10, 199)

plt.plot(x, f1)
plt.plot(x, f2)
plt.plot(y, fsum)
plt.show()

But I can't correctly describe rect function:
return 1 if abs(x)<=0.5 else 0
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

A: Assuming you want an array of 0 and 1 values, the same shape as x, you can use numpy.where:
In [8]: x = np.linspace(-10, 10, 100)
In [9]: np.where(abs(x)<=0.5, 1, 0)
Out[9]:
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   0, 0, 0, 0, 0, 0, 0, 0])

So your function could be:
from numpy import linspace, sqrt, sin, exp, convolve, abs, where
...
def rect(x):
    return where(abs(x)<=0.5, 1, 0)

A: def rect(x):
    y=x
    for i in range(len(x)):
        if abs(x[i]) <= 0.5:
            y[i] = 1
        else:
            y[i] = 0
    return y


text:
Q: Wrong characters with accents in alerts and confirms with Phonegap/Cordova I'm trying to display alert and confirm boxes with accents in them but when I run the application what I get are wrong characters, I checked the file encoding and it is UTF-8 and in the index.html I set the utf-8 charset.
Someone has any idea?
Thanks.

A: You can't use special characters in alert or confirm as they don't take special character directly,instead you can use \u escape sequence in the JavaScript string literal to display these characters.
alert("\u00e6\u00f8\u00e5")

to get output like this æøå
You can find utf-8 equivalent for character you want here


text:
Q: Inserting data into Data Grid View c# I am developing a diary application that allows user to insert appointments into a diary so they can see what others are doing during that week.
I've created an add appointments form which submits the appointment into the database successfully. But now i want to make these appointments visible in the data grid view under the correct date. As you can see by the attached photo the current week is along the top, and the users are down the side.
Any idea how i can make a start on this? I'm new to c# and SQL so its quiet a challenge...
DGV where the appointments will be displayed
Add appointments form which adds the data to the database when submitted

A: You need to start from MVVM architecture pattern first

https://www.wintellect.com/model-view-viewmodel-mvvm-explained/

Use observation collection and set data in observation collection and with the help of binding the data will auto-update in data grid view
Use Binding to update data in the data grid

How to bind WPF DataGrid to ObservableCollection

For SQL learn some basic knowledge

https://parallelcodes.com/wpf-mvvm-datagrid-bind-from-sql-database/


text:
Q: Как умножить каждый элемент CSV файла на число? Есть CSV файл, содержащий 8 столбцов и огромное количество строк исключительно числовых данных.
Как проще всего удвоить значение каждой ячейки?

A: Используя Pandas, это исключительно просто и гораздо быстрее по сравнению с решениями, использующими циклы:
import pandas as pd

pd.read_csv('/path/to/file.csv').mul(2).to_csv('/path/to/result.csv', index=False)

Или, если в вашем CSV отсутствуют имена колонок:
(pd.read_csv('/path/to/file.csv', header=None)
   .mul(2)
   .to_csv('/path/to/result.csv', header=None, index=False)
)

Если все данные не вмещаются в памяти, Pandas позволяет обработать данные по частям (chunks):
for chunk in pd.read_csv('/path/to/file.csv', header=None, chunksize=10**6):
    chunk.mul(2).to_csv('/path/to/result.csv', header=None, index=False, mode='a')

Тест
Генерим тестовые данные:
In [80]: x = pd.DataFrame(np.random.rand(10**6, 8))

In [81]: x.shape
Out[81]: (1000000, 8)

In [82]: x.head()
Out[82]:
          0         1         2         3         4         5         6         7
0  0.890351  0.814333  0.436384  0.477630  0.394325  0.339082  0.205078  0.033898
1  0.749606  0.045757  0.850344  0.496043  0.727086  0.717089  0.086069  0.826920
2  0.703955  0.492983  0.105174  0.298543  0.008731  0.885632  0.233774  0.046960
3  0.053236  0.024155  0.126744  0.139082  0.475896  0.747354  0.772720  0.816470
4  0.439865  0.344010  0.301929  0.528090  0.462750  0.113415  0.621818  0.796230

In [83]: x.to_csv('c:/temp/file.csv', index=False, header=None)

Размер C:\Temp\file.csv - 148MiB
Замер скорости на моем обычном (не SSD) диске:
In [84]: %%timeit
   ....: (pd.read_csv('c:/temp/file.csv', header=None)
   ....:    .mul(2)
   ....:    .to_csv('c:/temp/result.csv', header=None, index=False)
   ....: )
   ....:
1 loop, best of 3: 30.4 s per loop

Результат: 30 секунд на чтение исходного CSV, умножение всех элементов и запись результата обратно в CSV для 1-го миллиона строк и 8-ми столбцов

A: Если необходимо выполнить задачу, используя только стандартную библиотеку (иначе pandas как @MaxU продемонстрировал идеально подходит для данной задачи):
#!/usr/bin/env python3
import fileinput
import sys

with fileinput.FileInput(inplace=True, backup='.bak') as file:
    for line in file:
        try: # multiply whitespace-separated float numbers
            print(*[2*float(f) for f in line.split()])
        except ValueError as e:
            print("Can't parse %r line, error: %s" % (line, e), file=sys.stderr)

Данный код модифицирует файлы, заданные в командной строке, или stdin. Каждый исходный файл перемещается в *.bak файл на случай ошибки и stdout перенаправлен в исходный файл, чтобы изменения по месту производить.


text:
Q: How to remove the warning of repeated words in Pycharm? I have disabled typos but I still have inspection warnings like below in PyCharm ("typo: you repeated a word"). How can I get rid of them without manually ignoring them every time? In my field I have repeated words (genes) which aren't mistakes.
An example that shows this problem:
# test test

*

*Python 3.10.2

*Pycharm 2021.3

*Windows 11

A: I found the trick. It was actually because of the grammar inspection, and not the typo inspection that you need to uncheck.


text:
Q: How can I pass my config parameters to the frontend via Spring Boot? I have a question. I have created 2 config files. I can already use the parameters in the application.properties. My goal is to be able to display and edit the parameters later in the frontend. Like normal settings of any application. Unfortunately, I do not have an exact idea how I can implement this.
Does anyone have an idea for me how I can send my config via RestApi to the frontend?
My application.properties
#ConfigMaintenance
config.maintenance.next-Available-Update-Version=1.28.5
config.maintenance.next-Available-Update-Date= 18.05.2022
config.maintenance.automatic-update= true
config.maintenance.update-Api-Token= sk021=!2jsn?=jacmw
config.maintenance.latest-Version= 1.28.4

#ConfigGeneral
config.general.volume=56
config.general.dark-Mode=false
config.general.night-Mode=false
config.general.fps=144
config.general.screen-Resolution=1920 x 1080

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import lombok.Data;

@Configuration
@ConfigurationProperties(prefix = "config.general")
@Data
public class ConfigGeneral {
    private int volume;
    private Boolean nightModus;
    private Boolean darkMode;
    private int fps;
    private String screenResolution;

}

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import lombok.Data;

@Configuration
@ConfigurationProperties(prefix = "config.maintenance")
@Data
public class ConfigMaintenance {
    private String nextAvailableUpdateVersion;
    private String nextAvailableUpdateDate;
    private Boolean automaticUpdate;
    private String updateApiToken;
    private Boolean latestVersion;

}

Basically I would be interested in a solution, but a good report or even just a suggestion would be enough for me :).
Thanks in advance

A:
I have created 2 config files. I can already use the parameters in the
application.properties. My goal is to be able to display and edit the
parameters later in the frontend. Like normal settings of any
application.

I will add my notice here, because the question of how to pass them to UI may be valid but the outcome may be wrong for you.
In a Spring Boot application, the properties that you use and load via @Configuration
@ConfigurationProperties(prefix = "config.general") are loaded only during spring context initialization which happens when the application starts up. So considering that those properties already exist in your application.properties file, your Frontend would not be able to persist the changed properties somewhere.
1 Possible scenario I see for this requirement, is that those properties are loaded from Database and not application.properties, and then when edited the database records are edited to be persistent. Then you have to either restart the application or try to manually refresh the spring context for those properties to take effect. For this solution you could just create an endpoint from your spring-boot application that delivers all properties that exist in database and then another endpoint to edit those properties. Like simple crud operations.
2 Possible scenario but may be a bit overkill is to use cloud config server. Search for spring cloud bus and spring actuator refresh to see how you can apply some out of the box solutions for an application that needs dynamic properties.


text:
Q: Composable annotation in android jetpack compose I am working on a multimodule project with three modules Core, A and B. Both modules A and B uses Core. There is a screen (or composable) in module B that I need to reuse in module A. I can just move that screen to Core but I don't think this is scalable. So I am defining an Interface in Core whose implementation would be provided by B. Then A will get that Interface through DI and use it without dealing with it's implementation.
interface NotificationLayout {
    @Composable
    fun NotificationLayoutStatusState(
        modifier: Modifier,
    )
}

This will be implemented by B. But when I run it, it just crashes with NoSuchMethodError
java.lang.NoSuchMethodError: No interface method NotificationLayoutStatusState(Landroidx/compose/ui/Modifier;Landroidx/compose/runtime/Composer;I)V

Can anyone please help me. I think this has to do with the Composable annotation.

A: The solution is to enable compose(i.e not only adding the compose dependencies) in all the modules that use the interface. Previously I was only enabling compose in modules A and B but not in core and that was causing the issue.