text:
Q: Incorrect float data is inserted In my SQL Server i have a table with a column called FloatValue With a Float data type.
I update this value from a WCF service with this method:
public int UpdateConfig(float value)
    {
        try
        {
            using (SqlConnection conn = GetConnection(DbName.Temp))
            {
                conn.Open();
                string command = @"UPDATE ConfigTable SET FloatValue = @value";
                using (SqlCommand cmd = new SqlCommand(command, conn))
                {
                    cmd.Parameters.AddWithValue("@value", value);
                    int res = cmd.ExecuteNonQuery();
                    return res;
                }
            }
        }
        catch (Exception ex)
        {
            return 0;
        }
    }

My problem is that when invoking this method like so:
UpdateConfig(1.1);

a select statement like this:
SELECT ConfigTable.FloatValue From ConfigTable

returns this value: 1.10000002384186
When updating this value directly from SSMS the correct data is being updated.
How can i solve this?

A: The reason for this discrepancy is that FLOAT (without specifying N) in SQL Server actually has a precision closer to the double type than to the float type in C#. Using double in your C# code should remove the discrepancy you are seeing.

A: This is as expected for a float value. Floats are not exact values so the value 1.1 may indeed be represented by the value 1.10000002384.
One solution would be to round the value to 1 or 2 digits if that is ok. Another solution would be to use a fixed precision number format like Decimal instead.
EDIT:
Actually, the Decimal is not fixed precision, but it is close enough for most use cases.


text:
Q: Unable to load data with emberJS I have the following Ember app. But when I go to the /products route I've got the following error: Error while loading route: TypeError {}
var App = Ember.Application.create();
App.Router.map(function() {
  this.route('products');
});

DS.Store.extend({
  revision: 11,
  adapter: DS.RESTAdapter.create()
});

var Product = DS.Model.extend({});

var ProductsRoute = Ember.Route.extend({
  model: function() {
    return App.Product.find();
  }
});

A: First, your code wont run because your model and route does not exist is scope of the App. It should look like this:
var App = Ember.Application.create();
App.Router.map(function() {
    this.route('products');
});

DS.Store.extend({
    revision: 11,
    adapter: DS.RESTAdapter.create()
});

App.Product = DS.Model.extend({});

App.ProductsRoute = Ember.Route.extend({
    model: function() {
        return App.Product.find();
    }
});

Next, you may want to replace:
this.route('products');

with:
this.resource('products');

as you are using RESTAdapter.
Finally DS.Model should specify which fields it should user from JSON response:
App.Product = DS.Model.extend({
    name: DS.attr('string')
});

Hope it will help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to generate predefined values for xaml property with typeconverter If I have a control and I start typing a foreground property for it, it offers me a list of Colors, seemingly from the Colors class.
edit: I think it's actually the KnownColor enum, which is internal.
How is this achieved?
I have an attached property which is of type MyClass. I have a static class with some pre-cooked instances of MyClass. I want to achieve the same behavior described above.
I know I can use a type converter and convert from the string to an instance, but this seems a little more advanced

A: You will need to use a Type converter.  The Xaml parser has built-in special handling of known types such as Brush and Color.


text:
Q: Force php to pass the SID in url - even if cookies are accepted in the browser I'm trying to get php to automatically pass the session ID via url, even if the browser accepts cookies.
I know url session id are normally considered a security risk, but I have a very specific application in mind which requires several separate users to be able to log in to the same php session, despite what cookie settings their browsers have. Sharing the url is my aim here, rather than a threat.
There will be several "groups" of users, each group should have a unique shared session, so simply applying a fixed session id in the code won't work. I want the "owner" of the group to be able to initiate the session, get a unique id, then pass this on to all the other users, via a url.
As it's an existing application, I can't make modifications that will affect the normal session behaviour for other users - this is for users in a  specific group of IPs - which is why i'm trying to modify the standard session handling.
I've tried using ini_set() to disable session.use_cookie, but that simply prevents the session from being remembered at all.
Any suggestions gratefully received.

A: Have you try enabling session.use_trans_sid ?

A: Set
session.use_cookies=0
session.use_trans_sid=1

via ini_set() or in the php.ini, .htaccess ...or where ever you can change the configuration settings.
see also:

*

*http://docs.php.net/session.configuration#ini.session.use-cookies

*http://docs.php.net/session.configuration#ini.url-rewriter.tags


text:
Q: how can a server handle lots of port 80 connections Admittedly this is a simple question but 20 minutes of googling and I just can't find an answer... I will frame my question with an example.
say I own www.reallypopular.com and my website sees 100 GET requests per second. Also let's say the average time for my server to respond to that GET request is 1 second (for the sake of the example just assume some server side processing.) My understanding of ports would say that the first client to contact my server would then block anyone else from connection to port 80 for 1 second. Following this logic, effectively only 1% of all users would actually be responded to and the rest would get "Port busy" or "not responding" or some such error.
Obviously I am missing something because this is clearly not what is happening so instead of proposing my theories as to why I'd love it if someone could set me straight here or point me to something I could read to clear this up. Thanks much.

A: The answer can be found in this wikipedia article:

Applications implementing common
  services often use specifically
  reserved, well-known port numbers for
  receiving service requests from client
  hosts. This process is known as
  listening and involves the receipt of
  a request on the well-known port and
  reestablishing one-to-one
  server-client communications on
  another private port, so that other
  clients may also contact the
  well-known service port.

Also, from this article on Berkeley sockets on wikipedia.

When an application is listening for
  stream-oriented connections from other
  hosts, it is notified of such events
  (cf. select() function) and must
  initialize the connection using the
  accept() function. Accept() creates a
  new socket for each connection and
  removes the connection from the listen
  queue.

A: TCP doesn't work that way. A connection to a port from another system does not mean that port can't receive other connections. From the wikipedia article on TCP:

Arriving TCP data packets are
  identified as belonging to a specific
  TCP connection by its sockets, that
  is, the combination of source host
  address, source port, destination host
  address, and destination port.

A: When the client connects, and the TCP server accepts the connection, a new socket is created at the server for communication with this  client. The original listening socket continues to listen for new requests, and the new socket is used to send and receive from a  particular client. Note that a TCP server with N active clients will  have N sockets to read/write for each client, in addition to the  main listening socket. All these N+1 sockets are all supposed to be  on the same port number (the server's well known port number), but  they have different socket file descriptors inside the server code.
Source


text:
Q: Solve parallel saves to mongodb so I've recently tried to create a booking site in which you can select a date you wish to book. Then you'd send a request to /api/v1/reserve which would check if the data is valid. Generate a stripe payment intent, save the reservation to the database and send the payment intent id to the front end (for confirmation). My problem is that if two clients click send at the same time, they both pay for the same date which shouldn't happen.
router.post("/reservation", async (req, res) => {

    //Check if everything is in the reqest
    if (!req.body?.name || !req.body?.phone || !req.body?.date) return res.sendStatus(400);
    if (!req.body.phone.match(/^[+]{0,1}[4]{1,2}[8][\s0-9]*$/)) return res.status(400).json({
        type: ErrorTypes.PHONE
    });

    //Validating date
    const reservationDate = new Date(req.body.date);
    if (reservationDate < new Date()) return res.status(400).json({
        type: ErrorTypes.DATE
    });
    //Checking if date is already reserved
    if (await checkIfDateReserved(reservationDate)) return res.status(400).json({
        type: ErrorTypes.RESERVED
    })
    //if reservation date is weekend raise the price
    const estimatedPrice = reservationDate.getDay() == 6 || reservationDate.getDay() == 0 ? 3500 : 2000;
    try {
        //Create payment intet
        const intent = await stripe.paymentIntents.create({
            amount: estimatedPrice,
            currency: "PLN",
            payment_method_types: ['card']

        });

        const document = new ReservationModel({
            name: req.body.name,
            reservationDate: reservationDate,
            phone: req.body.phone,
            complete: false,
            intentId: intent.id
        });
        await document.save();
        //If everything went smoothley, send the secret to the client
        //Send the client the intent secret to confirm the payment
        res.json({ clientSecret: intent.client_secret });

    } catch (error) {
        res.status(500);
    }

});

Basically, both processes run in parallel in different threads and they check if the date is reserved at the same time and reserve it at the same time. How can I make it so the database will wait until the first save request is finished before processing another? The reservationDate field is unique but it seems MongoDB still ignores it.
PS: Also, I thought about using transactions but I don't really know how would they apply here.

A: so I ended up using an answer in this question thanks to 0x1C1B. The mutex ended up working perfectly. Leaving the code if someone needs it.
const mutex = new Mutex();

router.post("/reservation", async (req, res) => {

    //Check if everything is in the reqest
    if (!req.body?.name || !req.body?.phone || !req.body?.date) return res.sendStatus(400);
    if (!req.body.phone.match(/^[\s0-9]{9,11}/)) return res.status(400).json({
        type: ErrorTypes.PHONE
    });

    //Validating date
    const reservationDate = new Date(req.body.date);
    if (reservationDate < new Date()) return res.status(400).json({
        type: ErrorTypes.DATE
    });
    await mutex.lock(); //Lock the mutex to avoid processing two reservations at once
    //Checking if date is already reserved
    if (await checkIfDateReserved(reservationDate)) {
        mutex.release(); //Release the mutex so other requests can continue
        return res.status(400).json({
            type: ErrorTypes.RESERVED
        })
    }
    //if reservation date is weekend raise the price
    const estimatedPrice = reservationDate.getDay() == 6 || reservationDate.getDay() == 0 ? 3500 : 2000;
    try {
        //Create payment intet
        const intent = await stripe.paymentIntents.create({
            amount: estimatedPrice,
            currency: "PLN",
            payment_method_types: ['card']

        });

        const document = new ReservationModel({
            name: req.body.name,
            reservationDate: reservationDate,
            phone: req.body.phone,
            complete: false,
            intentId: intent.id
        });
        await document.save();
        //If everything went smoothley, send the secret to the client
        //Send the client the intent secret to confirm the payment
        res.json({ clientSecret: intent.client_secret }); //Send the client_secret required for payment confirmation
        //If the confirmation doesn't go through in 5 minutes the reservation is canceled due to "createdAt" field in the schema (see ../../schemas/Reservation.ts)
        //If the payment goes through the automatic deletion is cancelled (see index.ts:59)
        mutex.release(); //Release mutex after reservation has been saved to db
        //So other users can't reserve it

    } catch (error) {
        res.status(500);
        mutex.release();
    }

});


text:
Q: Codesandbox with ReactJS nog working in Internet Explorer Edge When I try Codesandbox in the newest version of IE, it keeps showing 'Bundling dependencies'. I can't get most Codesandbox demo's to work in IE, they all have the same problem.
For example:
https://codesandbox.io/s/mZRjw05yp
https://voz37vlg5.codesandbox.io/
Is this a known problem? I can't find anything about it after googling it.
Does it work for anyone else in IE?
Thanks in advance.

A: Microsoft stopped active development on IE in 2016. It is still maintained but new stuff doesn't find it's way to IE anymore. AFAIK codesandbox uses service workers which are not and will not be supported by IE. I could imagine this is why it doesn't work.
EDIT: Seems that service workers are only used for offline functionality. Any warnings or errors in the console?


text:
Q: Finding total number of vertices of a polygon A polygon has 20 sides .
Then , find total number of triangles using vertices of polygon but not the sides of polygon. Ans is 800.
I used Pnc concept here .
Out of 20 vertices , I select 3 vertices to make a triangle.
$20C_3$ , then I subtract 16 *20.
Why 16? Since every 4 vertices of a polygon can make triangles with 2 sides. That gives us triangle which have one side of a polygon .
I am not getting how to go further than this .

A: You count all triangles and subtract those with exactly one polygon edge. You also need to subtract those with two such edges.

A: Number the vertices 1 through 20.
For the moment, assume that the order in which the vertices are selected matters.
Suppose the first vertex is #1. Then, if the second vertex is #3, there are 15 possible triangles, as the remaining vertex cannot be vertex 20, 1, 2, 3, or 4. Similarly, if the second vertex is #19, there are 15 possible triangles. For any other second vertex (#4 through #18), there are 14 possible triangles, because #20, #2, and the two vertices on either side of the second vertex are ineligible. So, all in all 15 + 15 + 15 * 14 = 240.
Since the first vertex can be any one of the 20, there are 20 * 240 = 4800 possible permutations.
But, order does not matter, so we must divide by $3!=6$ and $4800 / 6 =800$.


text:
Q: How to merge source sets while sharing dependencies to each other I'd like to publish a library with two different API versions where both use the same core code underneath. I tried shading/shadowing but have struggles getting the visibility right (I'd like to hide the core code from the API user). So I wanted to achieve my goals by having different source sets and configurations:
sourceSets {
    // the `main` source set acts as the common code base for `api` and `api2`

    api {
        java {
            srcDir 'src/api/java'
            // Includes classes from `main`:
            compileClasspath += sourceSets.main.output
            runtimeClasspath += sourceSets.main.output
        }
    }
    api2 {
        java {
            srcDir 'src/api2/java'
            // Includes classes from `main`:
            compileClasspath += sourceSets.main.output
            runtimeClasspath += sourceSets.main.output
        }
    }
}

configurations {
    common {
        canBeResolved = true
        canBeConsumed = false
    }

    // These art the configurations used both for being consumed with `project(...)` or published:
    exposedApi {
        canBeResolved = true
        canBeConsumed = true
        extendsFrom common
    }
    exposedApi2 {
        canBeResolved = true
        canBeConsumed = true
        extendsFrom common
    }
}

task apiJar(type: Jar) {
    group = 'build'
    from configurations.exposedApi
    baseName = 'api'
}

task api2Jar(type: Jar) {
    group = 'build'
    from configurations.exposedApi2
    baseName = 'api2'
}

publishing {
    publications {
        api(MavenPublication) {
            artifact apiJar
            artifactId 'mylib-api'
        }
        api2(MavenPublication) {
            artifact api2Jar
            artifactId 'mylib-api2'
        }

    }
}

dependencies {
    common sourceSets.main.output
    exposedApi sourceSets.api.output
    exposedApi2 sourceSets.api2.output
}

If I want to use one of these APIs I can easily use project(path: ':mylib', configuration: 'exposedApi2') or use one of the published Maven artifacts and it works nicely.
But as soon as I change classes in the main source set to internal in order to achieve proper encapsulation of the main code, the API code won't compile anymore:
Cannot access 'SomeClassInMain': it is internal in '' (<-- yes, it really shows nothing in the '')

I also tried to merge the source set into one, so there is technically not really a main source set anymore:
sourceSets {
    api {
        java {
            srcDirs('src/api/java', 'src/main/java')
        }
    }
    api2 {
        java {
            srcDirs('src/api2/java', 'src/main/java')
        }
    }
}

That now works all as intended, no compilation errors, calls from the API to main work as expected and the classes in main even have internal visibility. But unfortunately IntelliJ seems to not pick up the fact that classes in main are really part of the same source set. I get an error (Unresolved reference: SomeClassInMain) in the IDE every time I mention a class from the main sources and of course no auto-completion would work, too, making the solution somehow not really practical in the end.
So just to sum up the goal:

*

*it's important that the main sources are accessible to the API

*but not to the user using the API (or the Maven publication) – the only thing the user should be facing is the API

*If possible, I'd like to not put the API and main code in separate modules and publish them separately for encapsulation reasons

*I tried a shading/shadowing (fat/uber JAR) approach but I haven't managed to reduce the visibility to internal in the main sources

*I'm new to the topic of these complicated kinds of build configurations so maybe I simply have chosen the wrong approach. Maybe there's a better one which I haven't yet managed to find?

Many, many thanks in advance!


text:
Q: How can I import the text of a file into a variable in javascript during compilation using webpack? I have an application that requires the use of long string values that are ideally stored in a separate text file.
However, I'm kind of stumped as to how I can perform something like the following:
import fileText from './path/to/filename.txt'

and have the end result being something like:
var fileText = 'Long text string that was derived during compilation'

It wouldn't be ideal if I have to reconstruct the original text into a javascript file that returns the string as I'd like to not abandon the syntax highlighting of the original text file.
Update:
Using raw-loader worked like a charm except I was using typescript and it was throwing errors during compilation. Setting up the following typescript declaration ended up getting it working for me.
declare module "*.txt" {
    const content :string;
    export = content;
}

Much appreciated!

A: Install raw-loader and use it load txt files:
npm install raw-loader --save-dev

Add to rules:
rules: [
  {
    test: /\.txt$/,
    use: 'raw-loader'
  }
]


text:
Q: How to properly assign a url as a prop to action creator I'm using react-native-image-crop-picker along with react-native-fetch-blob to grab an image from the camera roll and then save it to a Firebase storage bucket.
class CreateForm extends Component {
  componentWillMount() {
   this.setState({ loading: false });
  }

  // RNFetchBlob and RNImageCropPicker working together to store an
  // image in firebase, and then returning a url for that image.

  openImage() {
    this.setState({ loading: true });
    const Blob = RNFetchBlob.polyfill.Blob;
    const fs = RNFetchBlob.fs;
    window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
    window.Blob = Blob
    //const uid = "12345"

    ImagePicker.openPicker({
      width: 300,
      height: 300,
      cropping: true,
      mediaType: 'photo',
    }).then(image => {
      const imagePath = image.path;

      let uploadBlob = null;

     const storage = firebase.storage();
     const storageRef = storage.ref();
     const imageRef = storageRef.child('dp.jpg');
     const mime = 'image/jpg';
     fs.readFile(imagePath, 'base64')
       .then((data) => {
          //console.log(data);
       return Blob.build(data, { type: `${mime};BASE64` });
    })
       .then((blob) => {
          uploadBlob = blob;
          return imageRef.put(blob, { contentType: mime });
       })
      .then(() => {
          uploadBlob.close();
          return imageRef.getDownloadURL();
       })

Everything works perfectly until this bit of code:
      .then((url) => {
          console.log(url);
          this.props.entryUpdate({ prop: 'image', url });
    });
   });
  }

It logs the url just fine.  But when I try to assign this url as a prop named 'image' to the action creator 'entryUpdate', the Firebase realtime database gets an undefined object and throws an error.
Here's the action creator 'entryUpdate':
 export const entryUpdate = ({ prop, value }) => {
   return {
    type: ENTRY_UPDATE,
    payload: { prop, value }

  };
 };

Without the 'image' prop, everything executes correctly. So I know that I'm not giving the action creator the right syntax somehow. The
this.props.entryUpdate({ prop: 'image', url });

line has to be just plain wrong. Any help would be so appreciated!

A: The problem is you're destructuring the object being passed into the action creator incorrectly, ({ prop, value }) is basically grabbing the properties from the object being passed through. prop is correct because the object being passed as an argument has a prop key with 'image' as the value. value however is undefined because value is not a defined key on the object passed as an argument. Using url instead would be correct and should fix your issue:
export const entryUpdate = ({ prop, url }) => {
   return {
    type: ENTRY_UPDATE,
    payload: { prop, url } // or { prop, value: url } if you dont want to edit your dispatcher.

  };
 };

A: This is what worked:
.then((url) => {
      const { image } = this.props;
      this.props.entryUpdate({ prop: 'image', value: url });

I had to declare { image } as this.props, as well as specifying
value: url


text:
Q: Mouse Rollover event for ASP.NET control I have a ASP.NET ImageButton control (no AJAX) with a Image_Click event that fetches data from SQL server. Now I want to add a Mouse Rollover to the Image Button that should fetch the data from the SQL server and display it on a Label.
I know you can add a Javascript Mouse Rollover event on the Image Button.
 imgae_Button.Attributes.Add("onmouseover", "myJacascriptFunction()");
How do I get the Javascript code fire Server side code to fetch the SQL data?
Can this be done?
EDIT: Clarification onclick() event not only fetches data from SQL but also writes to another table. This event has alreday been coded without AJAX.
It is the mouse rollover event that I need help with. When the user hovers over the image, data should be fetched from SQL database & displayed on a label control.

A: This sure can be done, and will almost certainly involve AJAX.
In your mouse rollover event you want to define myJavascriptFunction() to click the image button on the users behalf, this will subsequently postback to the server as if the user had simply clicked.
You then want to place the image button and the label you want to show the answer into an UpdatePanel and ensure you stick a ScriptManager on the page too to handle the request/response.
This should achieve what you want.


text:
Q: Enable and disable 'edit' on orders for shop manager (woocommerce) I'm currently using the woocommerce-readonly-role this plugin to disable the ability to edit for a specific user where they only are able to view orders instead of editing just for shipping purposes in woocommerce. However, I need to enable some of the buttons to be editable, and I actually have some other features/custom code in the orders and need to enable it to be editable. Hence, in the current plugin I'm using, no matter which features I've added on, it is still unable to edit as I assuming the plugin is disabling the whole 'clickable' button on the order page regardless of additional features I added into order page.
So, I'm planning to be selective on which button is not accessible for the specific user.
The main issue is how do I disable edit (only enable readonly) more button / field edit including for shop manager only as below:  You image reference may view from here: https://snipboard.io/AtOWBY.jpg

*

*Disable Add Order (I was following this and added to function Remove or hide "add new" button on woocommerce on bulk order panel  using the code below

add_filter( 'woocommerce_register_post_type_shop_order','your_function_name' );
function your_function_name($fields) {
        $fields['capabilities'] = array(
            'create_posts' => false,
          );
        return $fields;
    }

*

*it works in admin role, but how can I amend the function which gets executed ONLY for "shop manager" role )

*Disable Date created (I was following this WooCommerce: Disable Date on Edit Orders - I've tried this code by using a plugin 'Simple Custom CSS and JS' and add accordingly using the code below.

/**
 * Enqueue a script in the WordPress admin, excluding edit.php.
 *
 * @param int $hook Hook suffix for the current admin page.
 */
function wpdocs_selectively_enqueue_admin_script( $hook ) {
    // if ( 'edit.php' != $hook ) {
    //     return;
    // }
    wp_enqueue_script( 'my_custom_woocommerce_script', get_template_directory_uri() . '/woocommerce/assets/meta-boxes-order.js', array(), '1.0' );
}
add_action( 'admin_enqueue_scripts', 'wpdocs_selectively_enqueue_admin_script' );

jQuery(document).ready(function(){
    alert("ok"); // only for testing purpose that this file is loaded
    jQuery(".order_data_column_container .order_data_column p:eq(0) input").attr('disabled', true);
});

However, it does not work and how can I amend the function which gets executed ONLY for "shop manager" role )
I was searching a lot for below too, but I can't find the file that I have to change for below, where it only can view and non editable.

*Disable Customer

*disable product link (only able to view product & its SKU instead of clicking redirect to edit product page)

*Disable Order Action

*Disable custom field

*Disable Add New Custom Field

*Disable downloadable permission

A: Use get_current_user(), this way you can get user object then check user's role from the object and if it is shop manager then apply your code as you mentioned.
add_filter( 'woocommerce_register_post_type_shop_order','your_function_name' );
function your_function_name($fields) {
    $user = wp_get_current_user();
    if ( in_array( 'shop_manager', (array) $user->roles ) ) {
        $fields['capabilities'] = array(
            'create_posts' => false,
        );
        return $fields;
    } else {
        return $fields;
    }
}


text:
Q: Unique char pair in two strings So I need some help with an exercise, I'm stuck! Go easy on me, I'm fairly new to this. The exercise goes as follows:

Given two char arrays of equal lengths, determine if each character from the first array can be replaced uniquely with a character from the second one so that both arrays are equal. Display the character pairs between the two arrays.

Example 1:
Given the following input: aab and ttd, the console will display:
True
a => t
b => d

Example 2:
Given the following input: aba and ttd, the console will display:
False

In the second example the answer is False because there is no unique replacer for character a: both t and d correspond.
I have been busting my head with this and honestly I feel like I cannot even think straight anymore. Tweaked the code so many times already that I almost don't understand it anymore. It still passes the first test though, but seems to keep failing a test with a longer string input. For example with the inputs: ala bala portocala and cuc dcuc efghijcuc, the console displays True and then the pairs, which is not right. Below you have my POS code, any advice is welcome.
static void Main(string[] args)
    {
        string a = Console.ReadLine();
        string b = Console.ReadLine();

        string one = string.Empty;
        string two = string.Empty;

        bool res = false;
        int count = 0;

        for (int i = 0; i < a.Length; i++)
        {
            if (!one.Contains(a[i].ToString()))
            {
                if (!two.Contains(b[i].ToString()))
                {
                    one += a[i];
                    two += b[i];
                }
            }
        }

        char[] firstPhrase = new char[one.Length];
        char[] scndPhrase = new char[two.Length];

        for(int i = 0; i < one.Length; i++)
        {
            bool temp = false;
            for(int j = 0; j < two.Length; j++)
            {
                if(firstPhrase[j] != one[i])
                {
                    for(int k = 0; k < scndPhrase.Length; k++)
                    {
                        if(scndPhrase[j] == two[i]) { res = true; break; }

                    }
                    if(res == true) { break; }
                    else { continue; }
                }
                if(firstPhrase[j] == one[i])
                {
                    if (scndPhrase[j] == two[i]) { temp = true; continue; }
                    else { res = true; break; }
                }

            }
            if(temp == false)
            {
                firstPhrase[count] = one[i];
                scndPhrase[count] = two[i];
                count++;
            }
            if(res == true) { break; }
        }

        if (res == true)
            Console.WriteLine(res);
        else
        {
            Console.WriteLine(!res);
            for (int i = 0; i < firstPhrase.Length; i++)
            {
                Console.WriteLine($"{firstPhrase[i]} => {scndPhrase[i]}");
            }
        }
        Console.Read();
    }

I look forward to your critique and I wish you all a Happy Easter!
Edit: forgot to mention, so so sorry guys. The tests don't allow the use of LINQ or any other directives, LINQ was actually the first thing I wanted to try.

A: Here is a solution using only System namespace.
The important part here is to change the characters in both arrays to tokens first.
This means, for "ala bala portocala" we will have:
{ 0, 1, 0, 2, 3, 0, 1, 0, 2, 4, 5, 6, 7, 5, 8, 0, 1, 0 }

So whenever a new character (which has not appeared before) is found, we increment the number by 1.
And you can see that this works well to evaluate if the two char arrays are a match in terms of this interesting perspective.
static int[] Tokenize(char[] array)
{
    int length = array.Length;
    int[] distinctArray = new int[length];
    int offset = 0;
    for (int i = 0; i < length; i++)
    {
        bool appearedBefore = false;
        for (int j = 0; j < i; j++)
        {
            if (array[j] == array[i])
            {
                appearedBefore = true;
                distinctArray[i] = distinctArray[j];
                break;
            }
        }
        if (!appearedBefore)
        {
            distinctArray[i] = offset;
            offset++;
        }
    }
    return distinctArray;
}

Then the test method:
static void Test(char[] array1, char[] array2)
{
    Console.WriteLine("[{0}] VS [{1}]", new string(array1), new string(array2));

    int[] array1Tokenized = Tokenize(array1);
    int[] array2Tokenized = Tokenize(array2);

    for (int i = 0; i < array1.Length; i++)
    {
        if (array1Tokenized[i] != array2Tokenized[i])
        {
            Console.WriteLine("False");
            return;
        }
    }

    Console.Write("True");
    for (int i = 0; i < array1.Length; i++)
    {
        bool appearedBefore = false;
        for (int j = 0; j < i; j++)
        {
            if (array1[j] == array1[i])
            {
                appearedBefore = true;
                break;
            }
        }
        if (!appearedBefore && array1[i] != array2[i])
        {
            Console.Write(" {0} => {1}", array1[i], array2[i]);
        }
    }
    Console.WriteLine();
}

And the results:
static void Main(string[] args)
{
    Test("ala bala portocala".ToCharArray(), "cuc dcuc efghijcuc".ToCharArray());

    Test("ala bala portocala".ToCharArray(), "cuc dcuc efghfjcuc".ToCharArray());

    Test("aab".ToCharArray(), "ttd".ToCharArray());
}

Output:
[ala bala portocala] VS [cuc dcuc efghijcuc]
False

[ala bala portocala] VS [cuc dcuc efghfjcuc]
True a => c l => u b => d p => e o => f r => g t => h c => j

[aab] VS [ttd]
True a => t b => d

A: Here is a short solution using only the System namespace.  Basically all we need to do is loop through the strings once in parallel, and for each position check whether the characters from each string are mapped to each other.  There are three cases:

*

*The characters have not been mapped before, in which case we map them to each other;

*The characters are already mapped to each other, in which case we keep going;

*Either character is already mapped, but not to the other character, in which case there is not a valid solution so we return null.

To keep track of the mappings we use two parallel arrays, mappings and reverseMappings.  Since characters are just numbers, we can use the value of the first character as an index into the mapping array and set the value equal to the second character.  Same thing for the reverse mapping, but with the opposite characters.  (This will work as long as the mapping arrays are large enough to handle every possible character value we expect.  For ASCII, 128 is the max size needed.  For Unicode it would need to be 65536.)  As we go, we keep a count of how many pairs we've seen so far.  This is needed so that we know how big to make the return array (an n-by-2 array of arrays), which will contain the actual character pairings required for the output.  We construct that by scanning through the mapping array once, looking for all mappings that have a non-zero value.
public char[][] GetCharacterMappings(string s1, string s2)
{
    if (s1 == null || s2 == null || s1.Length != s2.Length) return null;

    // I'm assuming the inputs can only be in the ASCII character set;
    // If they can have any Unicode character, make this value larger (e.g. 65536)
    const int maxCharValue = 128;
    char[] mappings = new char[maxCharValue];
    char[] reverseMappings = new char[maxCharValue];
    int pairCount = 0;

    for (int i = 0; i < s1.Length; i++)
    {
        char c1 = s1[i];
        char c2 = s2[i];

        if (mappings[c1] == 0 && reverseMappings[c2] == 0)
        {
            // these characters have not been mapped before
            mappings[c1] = c2;
            reverseMappings[c2] = c1;
            pairCount++;
        }
        else if (mappings[c1] != c2 || reverseMappings[c2] != c1)
        {
            // either character is already mapped to some other character
            return null;
        }
    }

    char[][] pairs = new char[pairCount][];
    int p = 0;
    for (int i = 0; i < maxCharValue; i++)
    {
        if (mappings[i] != 0)
            pairs[p++] = new char[] { (char)i, mappings[i] };
    }

    return pairs;
}

The output routine just checks whether the pairings are null, and if not, dumps them all out:
public void WriteResult(char[][] pairs)
{
    Console.WriteLine(pairs != null);
    if (pairs != null)
    {
        for (int i = 0; i < pairs.Length; i++)
        {
            Console.WriteLine(pairs[i][0] + " => " + pairs[i][1]);
        }
    }
}

Here is a working demo: https://dotnetfiddle.net/lBHKUY

A: Consider using a .NET dictionary. When below function returns null, there is no consistent mapping. When it returns a dictionary, its content will be the mapping. I compiled this, I did NOT test it..
public static Dictionary<char, char> BuildMapping(string s1, string s2)
{
    if (s1.Length != s2.Length) return null;
    Dictionary<char, char> result= new Dictionary<char, char>();
    for (int i = 0; i < s2.Length; i++)
    {
        if (result.ContainsKey(s1[i]))
            if (result[s1[i]] == s2[i]) continue;
            else return null;
        result[s1[i]] = s2[i];
    }
    return result;
}

A: Here is a solution with LINQ:
var result = str1.Zip(str2, (f, s) =>  f.ToString() + s.ToString())
                 .GroupBy(c => c[0])
                 .Where(c => c.Select(d => d[1]).Distinct()
                 .Skip(1).Any()).Any() ? false : true;

All that you need to run this, is just adding using System.Linq to your using directives.
You can see the result online here: https://dotnetfiddle.net/OF2cnO


text:
Q: How to tie in an object that's related with others- C#, OOD I'm struggling on a blackjack console app and need help designing/relating my Seat class.
For the game, there are six seats and a seat can only have one player but a player can occupy (or bet) on up to three seats if the seat is unoccupied.  Also, the TableGame has six seats available.
Regarding the TableGame class, it should have six seats.  So should I construct the six seats in the TableGame constructor?  What about creating a public property i.e. SeatsAvailable that uses an array to catch which seats are available?
Also, a player occupies a seat, and places a bet on it.  How should I go about coupling these guys together so that it's tied to the player making the bet?
Advice on how to couple the Seat class with the TableGame, Player class would be greatly appreciated as well as any critiques, direction I should take note of.  Thank you in advance for helping a beginner learn the ropes of OO design.
public class TableGame
{
    public TableGame(IEnumerable<string> playerNames)
    {
        List<Player> players = new List<Player>();
        foreach (string name in playerNames)
        {
            players.Add(new Player(name));
            // add the player to a new instance of a seat or to an array of already created seats(6)???
        }

        Dealer dealer = new Dealer();
        players.Add(dealer);

        PlayGame(players, dealer);
    }

    private void PlayGame(List<Player> players, Dealer dealer)
    {
        try
        {
            Deck playingDeck = new Deck();
            Deal(playingDeck, players);
            Play(playingDeck, players);
            DetermineHandResults(players, dealer);
            TransferBets(players, dealer);
        }
        catch (InvalidTransferAmountException ex)
        {
            players.Remove(ex.OffendingPlayer);
        }

        DisplayResults(players);    // I want this here so that DispayResults() is still called even if an InvalidTransferAmount exception is caught.
    }                               // However other types of exceptions (unhandled) will kick me out of PlayGame() and DisplayResults() will not be
                                    // called.  Use a finally block to execute something no matter what exception is thrown- handled or unhandled.
    public void Deal(Deck deck, List<Player> players)
    {
        deck.Shuffle();
        for (int i = 1; i < 3; i++)
            foreach (Player player in players)
                player.ReceiveCard(deck.Deal());
    }

    public void Play(Deck playingDeck, List<Player> players)
    {
        foreach (Player player in players)
            player.Strategy(playingDeck);
    }

    public void DetermineHandResults(List<Player> players, Dealer dealer)
    {
        foreach (Player player in players)
        {
            if (player.playerHand.HandValue() > 21)
                player.result = Result.Lose;
            else if (player.playerHand.HandValue() <= 21 && dealer.playerHand.HandValue() > 21)
                player.result = Result.Win;
            else if (player.playerHand.HandValue() <= 21 && player.playerHand.HandValue() > dealer.playerHand.HandValue())
                player.result = Result.Win;
            else if (player.playerHand.HandValue() == dealer.playerHand.HandValue())
                player.result = Result.Draw;
            else
                player.result = Result.Lose;
        }
    }

    public void TransferChips(Player playerTo, Player playerFrom, decimal value)
    {
        if (playerFrom.TotalChips < value)
            throw new InvalidTransferAmountException(string.Format("Can not transfer {0} from {1}'s bank roll, only {2:2d} available!",
                value, playerFrom.Name, playerFrom.TotalChips), playerFrom);
        playerTo.TotalChips += value;
        playerFrom.TotalChips -= value;

    }

    public void TransferBets(List<Player> players, Dealer dealer)
    {
        foreach (Player player in players)
        {

            if (player.result == Result.Win)
            {
                TransferChips(player, dealer, player.Bet);
                Console.WriteLine("{0} wins {1} dollars.", player.Name, player.Bet);
            }
            else if (player.result == Result.Lose)
            {
                //if (player.TotalChips < player.Bet)
                TransferChips(dealer, player, player.Bet);
                Console.WriteLine("{0} loses {1} dollars.", player.Name, player.Bet);
            }
            else
                Console.WriteLine("{0} pushes.", player.Name);
        }
    }

    public void DisplayResults(List<Player> players)
    {
        foreach (Player player in players)
        {
            Console.WriteLine("{0} has {1} and {2}s.  Total chips: {3}", player.Name, player.playerHand.HandValue(), player.result, player.TotalChips);
            player.ShowHandValues();
            Console.WriteLine();

        }
    }
}

public class Seat
{
    public Seat()
    {   }

    public bool Occupied;

}

public class Player
{
    private string name;
    private decimal bet =10, totalChips = 100;
    public Hand playerHand = new Hand();

    public Player()
    {  }

    public Player(string name)
    {
        this.Name = name;
    }

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public Result result { get; set; }

    public decimal TotalChips
    {
        get
        {
            return totalChips;
        }
        set
        {
            totalChips = value;
        }
    }

    public decimal Bet
    {
        get
        {
            return bet;
        }
    }

    public void ReceiveCard(Card card)
    { playerHand.Hit(card); }

    public void AskForCard(Deck deck)
    {
        playerHand.Hit(deck.Deal());
    }

    public virtual void Strategy(Deck deck)
    {
        while (playerHand.HandValue() < 17)
        {
            AskForCard(deck);
            if (playerHand.HandValue() == 21)
                Console.WriteLine("Congratulations {0} you got 21!", Name);
            if (playerHand.HandValue() > 21)
                Console.WriteLine("Sorry {0} you busted.", Name);
        }
    }

    public void ShowHandValues()
    {
        foreach (Card card in playerHand.GetCards())
        {
            Console.Write(card.ToString() + "  ");
        }
    }
}

public class InvalidTransferAmountException : ApplicationException
{
    public InvalidTransferAmountException(string msg, Player offendingPlayer) : base(msg)
    {
        OffendingPlayer = offendingPlayer;
    }

    public Player OffendingPlayer { get; private set; }

}


text:
Q: What is different about the way IE implements last-child? I am using a template that has CSS code looking like this:
h2:last-child,
p:last-child,
ul:last-child,
ol:last-child,
dl:last-child,
hr:last-child {
    margin-bottom: 0;
}
/* IE class */
h2.last-child,
p.last-child,
ul.last-child,
ol.last-child,
dl.last-child,
hr.last-child {
    margin-bottom: 0;
}

Can someone explain why the author did it differently for IE?  Is that still needed for the modern browsers?

A: It means that there is/was a decorator JS library/code that adds the class .last-child and .first-child to what it is applied to for IE8 and below.

A: They are probably using jQuery, to apply a class to the last child element because older IE browsers do not support css3 and thus last-child would not work.
$("hr:last-child")
    $(this).addClass("last-child");
});

Modernizr is a great library that helps conditionally handle js/css for different browsers


text:
Q: Python how to make all number combinations Python Python 3.10.2
How do I make all number combinations that I only use one of the list item in one combination?
for example:
list = ['258', '2478', '27', '2457', '578', '26', '26', '267']

22225222
52225222
82225222
24225222
27225222
28225222
...
88778667

A: Use recursion
def f(s):
    if len(s) == 1: return list(s[0])
    return [x+y for x in f(s[:-1]) for y in s[-1]]


text:
Q: Code for two worksheet change events which I have combined not working Having looked for an answer to my question, I am at a loss and need some help.  I have two different worksheet change events in the same worksheet which will be triggered by two entirely separate cell's changing condition (one is empty to not empty to trigger an Unlock range event, and the second is a change in value which will trigger a series of hide cell events based on the value it has changed to.  (the second works perfectly on its own, but the first doesn't.) I have obviously missed something or my code is mince, and I need help
here is my code
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address(False, False) = "D5" Then
Select Case Target.Value
    Case Is = "": Range("A6:D115").Locked = True
    Case IsNot = Empty: Range("C6:D6,A16:D16,C19:D22,D25:D25,D41:D57,B58:D58,C63:D63,C65:D73,C75:D78,C80:D84,D88:D88,A93:D98,D101:D103,B113:B114,D113:D113").Locked = False
End Select
End If

If Target.Address(False, False) = "D25" Then
Select Case Target.Value
    Case "Select as appropriate": Range("40:85").EntireRow.Hidden = False
    Case "USA - Breen Road": Range("40:85").EntireRow.Hidden = False
         Range("45:45,47:47,53:57,77:78").EntireRow.Hidden = True
    Case "USA - Conroe": Range("40:85").EntireRow.Hidden = False
         Range("40:52,77:78,80:80,85:85").EntireRow.Hidden = True
    Case "USA - Lafayette": Range("40:85").EntireRow.Hidden = False
         Range("43:43,45:47,49:49,53:57,61:83").EntireRow.Hidden = True
    Case "Europe - Aberdeen": Range("40:85").EntireRow.Hidden = False
         Range("40:49,53:57,77:78,80:80").EntireRow.Hidden = True
    Case "Europe - Gateshead": Range("40:85").EntireRow.Hidden = False
         Range("53:57").EntireRow.Hidden = True
    Case "Middle East - Dubai": Range("40:85").EntireRow.Hidden = False
         Range("43:43,46:47,50:57").EntireRow.Hidden = True
    Case "Middle East - Saudi Arabia": Range("40:85").EntireRow.Hidden = False
         Range("43:43,45:47,50:53").EntireRow.Hidden = True
    Case "Middle East - All": Range("40:85").EntireRow.Hidden = False
         Range("43:43,46:47,50:57").EntireRow.Hidden = True
    Case "Far East - Singapore - Loyang": Range("40:85").EntireRow.Hidden = False
         Range("41:41,44:57,77:78,80:80").EntireRow.Hidden = True
    Case "Far East - Singapore - Tuas": Range("40:85").EntireRow.Hidden = False
         Range("40:49,53:57,77:78,80:82").EntireRow.Hidden = True
    Case "Far East - Singapore - All": Range("40:85").EntireRow.Hidden = False
         Range("41:41,44:49,53:57,77:78,80:80").EntireRow.Hidden = True
    Case "Far East - Perth - Australia": Range("40:85").EntireRow.Hidden = False
         Range("41:57,63:63,67:67,72:72,74:83").EntireRow.Hidden = True
End Select
End If

End Sub

I have the cells all set to locked and the sheet protected - to prevent cells I don't want to have data in them, being fiddled with.
Any help will be greatly appreciated.

A: Case IsNot = Empty

is not valid syntax.
Change to
Case Is <> ""


text:
Q: GWT: Positioning DIV on top of image using getAbsoluteTop/Left - FF off by a few pixels? I'm working on some Google Web Toolkit Code that places an AbsolutePanel on top of an image. The way I'm doing this is to:

*

*wait until the image is loaded (i.e. width/height are >0)

*get the absolute coordinates of the image in the viewport using image.getAbsoluteLeft() and image.getAbsoluteTop

*Set the position of the AbsolutePanel (a direct child of the RootPanel) to the same coordinates using RootPanel.get().setWidgetPosition(myPanel, imageAbsLeft, imageAbsTop);
This works in Chrome and IE. Strangely, though, Firefox always positions the AbsolutePanel "a few" pixels (I'd say between 1 and approx 10? But it varies from page load to page load) above the image. I'm clueless as to what's causing this. Any hints much appreciated!
A live example of this is here: http://yuma-js.github.com. If you click the "Add Annotation" there's a draggable box, which movement is constrained by the AbsolutePanel. You'll notice that the constraining works perfect for Chrome, but is off for FireFox.

A: Morning,
well, I did some research how I could overlay an image with a another object too, and found this article: How to overlay one div over another div.
Based on that I made a similar example using SVG and drawing example, where I draw a rectangle around a space station. What I can tell you is, that you don't want to mix pixel and percentage positioning, and if you can, you should use percentage positioning!
Hope this helps somehow.
Here is my example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">

  <title>SVG Example</title>

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
       <rect x="65%" y="40%" width="20%" height="30%"
        fill="none" stroke="red" stroke-width="2"/>
        </svg>

This example draws a fullscreen image and places a fullscreen svg element above it. The svg element then draws a rectangle based on percentage sizes,

which is around the space Station. If the browser window resizes, the size of the drawn rectanlge changes as well, to always be on top of the space

station.

Resources for this example where the following links:

How to overlay one div over another div

Wikipedia: Scalable Vector Graphics

W3C Recommendation: 9 Basic Shapes

Image from: Bing.com, © StockTrek/White/Photolibrary


text:
Q: How to set read only property to entire Django forms based on session user I have created a form that can be used to update/create/view records. When a user selects a record that record data is rendered in the form. So that user will able to view/edit the form. The problem statement here is that if a record is created by some other user then the session user will not able to edit (only the creator should have access to edit).
I am thinking to write a logic so that when the record is created by the session user then only he/she will edit. Otherwise, the user will just view the record using the same form.
Below is my view file
    current_blog = Blog.objects.get(pk=blog_id)
    init_dict = {
        "blog_title": current_blog.blog_title,
        "blog_description": current_blog.blog_description,
        "last_modified": current_blog.last_modified
    }
    form = NewBlog(initial=init_dict)

return render(request, "myblog/blog.html", {"new_blog": form})

form.py
class NewBlog(forms.Form):
blog_title = forms.CharField(label="Form Title", max_length=250, widget=forms.TextInput(
    attrs={"class": "form-control", "placeholder": "Enter title here"}
))
blog_description = forms.CharField(label="Blog Description", widget=forms.Textarea(
    attrs={"class": "form-control", "placeholder": "Enter blog Description"}
))

blog.html
{% for field in new_blog %}

                              <fieldset>
                                {{ field.label }}
                                {{ field }}
{{ field.errors }}

                              </fieldset>

                        {% endfor %}

A: First thing is if you just want user to view the details then you dont need a form for that.you can just display the users data in p tag or heading tag.
secondly you can set readonly attribute of html input tag so users wont be editing it.

*

*YOu can add attrs={"readonly": "true"} // inside forms.py attr object

*or you can use jquery : $('input').attr('readonly', true);


text:
Q: Not able to connect to sql for membership in Visual studio 2008 Okay, this thing is driving me insane, I have tried every way, I have SQL 2008 (running as an instance on my pc named Razor-PC and visual studio sp1, I want to use Login and Logout controls (asp.net membership) so I tried to connect in following ways. Also, in vs I have set the (tools -> options -> database tools-> Data connection -> SQL server instance name (left it blank) ) After creating a default website and without messing around even a single thing, I did the following

*

*In web.config changed Authentication to "Forms" and then in default.aspx added login control and ran the site and entered some random info into login view in the hope that though login will surely fail, asp.net will behind the secne create the membership's database (aspnetdb) and make all the connections itself to database. But nothing happened I didn't get any database in app_data and I found error msg as "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections."

*I tried (starting from scratch) changed the authentication to forms, then ran aspnet_regsql it did created the database in sql with no problems, but then after that, I ran wat and then when in provider tab, I selected "select a single provider for all site management" and cicked the "test" next to AspNetSqlProvider it said "Could not establish a connection to the database.
If you have not yet created the SQL Server database, exit the Web Site Administration tool, use the aspnet_regsql command-line utility to create and configure the database, and then return to this tool to set the provider."

*Started site (again from scratch) and then changed authentication to "Forms" and added this manually,
<connectionStrings>
<add name="SQLMembership" connectionString="Data Source=RAZOR-PC; initial catalog=aspnetdb; integrated security=true"/>
</connectionStrings>

and also added the following manually
<membership>
<providers>
<add connectionStringName="SQLMembership" name="AspNetSqlProvider" Type="System.Web.Security.SqlMembershipProvider" />
</providers>
</membership>

but still it doesn't connect, it keeps coming up with same error I mentioned in point 2, can any one please tell me what am I doing wrong???

A: try use sql server user login rather than integrated security in connection string. and then check whether it work or not..
<connectionStrings>
<add name="SQLMembership" connectionString="Data Source=RAZOR-PC; initial catalog=aspnetdb; uid=sqlusername; pwd=password"/>
</connectionStrings>

If not then go to database manager in visual studio and there try to create connection manually. there you will get that sql server causing problem or not.


text:
Q: Sending and returning my PHP SOAP request from a function I've written a function like so:
/**
   * Send the soap request to complemar
   * @method  SendSoapRequest
   * @param   string          $method       The requst action
   * @param   string          $requestData  The xml
   * @access  private
   */
  private function SOAPRequest( $method, $requestData ){
    /** Run the soap request */
        $result = $this->SOAPClient->call( $method, $requestData, 'xsi' );
    /** Now check if there are errors or faults */
        if( $this->SOAPClient->fault ){
      /** Save the fault to the last fault message */
      $this->SOAPLastFault = print_r( $result, true );
      /** Output the error */
      echo '
Fault

'.$this->SOAPLastFault.'
';
      /** Return false */
            return false;
        } else {
      /** Check soap for erros */
      $this->SOAPErrors = $this->SOAPClient->getError();
      /** Check soaps return for a message */
            if( $this->SOAPErrors ){
        /** we have an error output it */
                echo '
Error

' . $error . '
';
        /** return false */
                return false;
            }
        }
    /** No errors return the result */
        return $result;
    }

I'm trying to send the soap request thats already built above, take the request back in another file and set it in the db. I'm confused on what I should try.
The file I want to write the send and return is below.
class ComplemarUpdateOrderStatus extends \Framework\Event\Cronjob
{
  protected static $prefix = "[ComplemarUpdateOrderStatus]: ";

  public static function run( data ){
    /** Log that we started */
    self::logMessage("Started!");
  }

  {

  }

Should I SoapClient::__doRequest???
Any help would be appreciated. I'm very confused.


text:
Q: XML ParseError for letter? While attempting to parse some very large XML, I ran into a parsing error. I was able to narrow down that the issue was somewhere in the writeup tag and when I re-ran my code with just that section, it produced the following traceback.
Traceback (most recent call last):
  File "<input>", line 3, in <module>
  File "path\to\Python\Python37-32\lib\xml\etree\ElementTree.py", line 1315, in XML
    parser.feed(text)
  File "<string>", line None
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 1, column 310

When I looked at line 1, column 310 in Atom there's just a N which is not a forbidden character in XML. Why is this issue popping up and how can I fix it?
Code
from xml.etree import ElementTree as etree
xml = """<writeup>
sVw*f4FgT9`|wXNz!x)McB})KDh*0O"47BKR;G4F3]p3!-?n!\'%_sP:3WuGw44yTGF""Mf=8d34:Pb0pCZF](d%+(V\'M3-i*Dr:#sS/o*[_Z$"8%F*H6_lr&gt;I#lmd/RIUskV9@Ba\\poJ&lt;GVG]5CVIeJJytI7]q{pJQLF/&amp;N:kYrJ^3s"aCdHupx@_/Ool9qfo1.?$cdd&gt;u{Xi|yQyPahZ88ayU;DX[eDr9p?G)"*I^VG4xvJjZDCTUr1@qE6e=By_^YINk!\x02~eU3v1(pgU-\\"(*)[dg#}cVG&gt;2b=P-uH9z?fOS9amy\'e~ZO,2?,^cAWpt;jo+`p/D`B&gt;&gt;NLDqhN~&lt;"=_"DU0V^kqDTN=7EWZL|ax&amp;7dn&gt;]u1C)-[}~wuS",je`OOGIwT1g.jSe:3!tn^E2z!|4)B+rUV@6&amp;~,(iv,A%`W_\')E"kdD({ppNuPts%P%/Gi;`Hx-P/}WX(\\&amp;N2[pSy=\'9D1b?XNKG*E.@v3riX]Dq@8EEt;OA3:Uav3\'2^\\r;|Ck75}inlV)TrTFGgsI{wLx/KrmehxiwK*9^"UGa8DAV?wd~\\)gP4!r}(Y0Sx^ssxS^6zx4)#XS7|.bxFbV`t\\D,w\\YqW+&amp;%v)+&amp;fFtl]g28M61m34gD=|w{~OmjKbJr1QOI7I%]X\'m*r-p=sUeE.L-"rXR`L&gt;,nz{%\';3VY:aAKQa~ngm"Sx$3RxB!AH$O^t1&lt;9~t}ujaZ}D2\'*\\b}gGMBg4,`m9WL0Eo
</writeup>"""
root = etree.fromstring(xml)

A: The problem is \x02 in the string. Python thinks that is an ASCII hex character.
Try making your string a raw string by prefixing the string with "r". This will make \ a literal character instead of an escape character.
Example...
xml = r"""<writeup>
sVw*f4FgT9`|wXNz!x)McB})KDh*0O"47BKR;G4F3]p3!-?n!\'%_sP:3WuGw44yTGF""Mf=8d34:Pb0pCZF](d%+(V\'M3-i*Dr:#sS/o*[_Z$"8%F*H6_lr&gt;I#lmd/RIUskV9@Ba\\poJ&lt;GVG]5CVIeJJytI7]q{pJQLF/&amp;N:kYrJ^3s"aCdHupx@_/Ool9qfo1.?$cdd&gt;u{Xi|yQyPahZ88ayU;DX[eDr9p?G)"*I^VG4xvJjZDCTUr1@qE6e=By_^YINk!\x02~eU3v1(pgU-\\"(*)[dg#}cVG&gt;2b=P-uH9z?fOS9amy\'e~ZO,2?,^cAWpt;jo+`p/D`B&gt;&gt;NLDqhN~&lt;"=_"DU0V^kqDTN=7EWZL|ax&amp;7dn&gt;]u1C)-[}~wuS",je`OOGIwT1g.jSe:3!tn^E2z!|4)B+rUV@6&amp;~,(iv,A%`W_\')E"kdD({ppNuPts%P%/Gi;`Hx-P/}WX(\\&amp;N2[pSy=\'9D1b?XNKG*E.@v3riX]Dq@8EEt;OA3:Uav3\'2^\\r;|Ck75}inlV)TrTFGgsI{wLx/KrmehxiwK*9^"UGa8DAV?wd~\\)gP4!r}(Y0Sx^ssxS^6zx4)#XS7|.bxFbV`t\\D,w\\YqW+&amp;%v)+&amp;fFtl]g28M61m34gD=|w{~OmjKbJr1QOI7I%]X\'m*r-p=sUeE.L-"rXR`L&gt;,nz{%\';3VY:aAKQa~ngm"Sx$3RxB!AH$O^t1&lt;9~t}ujaZ}D2\'*\\b}gGMBg4,`m9WL0Eo
</writeup>"""

In your actual code, if you're getting the XML as a string from an outside source, try encoding the string with .encode("unicode-escape")
root = etree.fromstring(xml.encode("unicode-escape"))


text:
Q: SQL / MS Access - why isn't this CASE working? I'm writing a query that determines which price to use based on a user-defined date named "USERDATE". When I run this, I get a "syntax error (missing operator) in expression". I want the price selected to be the "UNIT_AMT" which is used later on in the query.
SELECT MDDB.NDC, CARRIER.GROUP_ID, [USERDATE] AS USERDATE, MDDB.CODE, CARRIER.DUR_MU_R, CARRIER.FEE_BR, CARRIER.FEE_GR, CARRIER.AWP_BR, CARRIER.AWP_GR, CARRIER.DUR_MU_M, CARRIER.FEE_BM, CARRIER.FEE_GM, CARRIER.AWP_BM, CARRIER.AWP_GM, MDDB.AWP_UNIT_AMT,

CASE
WHEN USERDATE >= AWP_EFF_DATE THEN AWP_UNIT_AMT
WHEN USERDATE >= AWP_1ST_OLDEST_EFF_DATE AND USERDATE < AWP_EFF_DATE THEN AWP_1ST_OLDEST_UNIT_AMT
WHEN USERDATE >= AWP_2ND_OLDEST_UNIT_AMT AND USERDATE < AWP_1ST_OLDEST_UNIT_AMT THEN AWP_2ND_OLDEST_UNIT_AMT
WHEN USERDATE >= AWP_3RD_OLDEST_UNIT_AMT AND USERDATE < AWP_2ND_OLDEST_UNIT_AMT THEN AWP_3RD_OLDEST_UNIT_AMT
WHEN USERDATE >= AWP_4TH_OLDEST_UNIT_AMT AND USERDATE < AWP_3RD_OLDEST_UNIT_AMT THEN AWP_4TH_OLDEST_UNIT_AMT
WHEN USERDATE >= AWP_5TH_OLDEST_UNIT_AMT AND USERDATE < AWP_4ST_OLDEST_UNIT_AMT THEN AWP_5TH_OLDEST_UNIT_AMT
ELSE AWP_UNIT_AMT
END AS UNIT_AMT,

((([UNIT_AMT]*[QTY])*((100+[AWP_GR])/100))+[DUR_MU_R]+[FEE_GR]) AS [GR PRICE],
((([UNIT_AMT]*[QTY])*((100+[AWP_BR])/100))+[DUR_MU_R]+[FEE_BR]) AS [BR PRICE],
((([UNIT_AMT]*[QTY])*((100+[AWP_GM])/100))+[DUR_MU_M]+[FEE_GM]) AS [GM PRICE],
((([UNIT_AMT]*[QTY])*((100+[AWP_BM])/100))+[DUR_MU_M]+[FEE_BM]) AS [BM PRICE]
FROM MDDB_MASTER AS MDDB, CARRIER_GROUP AS CARRIER
WHERE (((MDDB.NDC)="41520091574") AND ((CARRIER.GROUP_ID)="709608"));

Thank you for your time and help!

A: Since Access SQL does not support CASE ... WHEN, you could use nested IIf() expressions.  However, with so many conditions, that nested IIf() would be challenging.  In this case you may find Switch() easier to use.
Switch(
    USERDATE >= AWP_EFF_DATE, AWP_UNIT_AMT,
    USERDATE >= AWP_1ST_OLDEST_EFF_DATE AND USERDATE < AWP_EFF_DATE, AWP_1ST_OLDEST_UNIT_AMT,
    USERDATE >= AWP_2ND_OLDEST_UNIT_AMT AND USERDATE < AWP_1ST_OLDEST_UNIT_AMT, AWP_2ND_OLDEST_UNIT_AMT,
    USERDATE >= AWP_3RD_OLDEST_UNIT_AMT AND USERDATE < AWP_2ND_OLDEST_UNIT_AMT, AWP_3RD_OLDEST_UNIT_AMT,
    USERDATE >= AWP_4TH_OLDEST_UNIT_AMT AND USERDATE < AWP_3RD_OLDEST_UNIT_AMT, AWP_4TH_OLDEST_UNIT_AMT,
    USERDATE >= AWP_5TH_OLDEST_UNIT_AMT AND USERDATE < AWP_4ST_OLDEST_UNIT_AMT, AWP_5TH_OLDEST_UNIT_AMT,
    True, AWP_UNIT_AMT
) AS UNIT_AMT


text:
Q: How to use Redis as back end for mosquitto ACL (JPmens plugin is used)? I am working on Mosquitto and plan to use Redis as the back end to handle both username/password pair authentication and ACL. I am using JPmens' authentication plugin to do this. The authentication works well, but I can't make the ACL work. Redis uses unique keys and the usernames (keys in my cases) are used in username/password pairs for authentication purposes. I have tried to mix user name,password and topics together in sets/list, but none of them work.
the mosquitto conf:
auth_plugin /etc/mosquitto/auth-plug.so
auth_opt_backends redis
auth_opt_redis_host 127.0.0.1
auth_opt_redis_port 6379
auth_opt_redis_userquery GET %s
auth_opt_redis_aclquery GET %s-%s

Following name/password pairs are working fine for the authentication

SET user1 PBKDF2$sha256$901$Qh18ysY4wstXoHhk$g8d2aDzbz3rYztvJiO3dsV698jzECxSg
SET user2 PBKDF2$sha256$901$R74X2ae3MufMS20M$CAbXZFDmXJN7Cc28Dm/Z97OfM8Tz1JHn
  ...

Following settings won't work for the ACL: (a/b... as topics)

sadd user22 PBKDF2$sha256$901$Qh18ysY4wstXoHhk$g8d2aDzbz3rYztvJiO3dsV698jzECxSg a/b c/d
rpush user33 PBKDF2$sha256$901$q5/N74O6Iaf/e8Cg$dEA3tZSi/sJeXKAkX39Gd3agy2WY96gE e/f

What's the correct way to do so?
In the Redis API, aclrequery shows that:
Single stepping until exit from function be_redis_aclcheck, which has no line number information.

redisCommand (c=0x6537d0, format=0x6561c0 "GET user1-t/c") at hiredis.c:1345
1345    void *redisCommand(redisContext *c, const char *format, ...) {
(gdb) bt
0  redisCommand (c=0x6537d0, format=0x6561c0 "GET my-t/c") at hiredis.c:1345
1  0x00007ffff5e61376 in be_redis_aclcheck () from /etc/mosquitto/auth-plug.so
2  0x00007ffff5e5c351 in mosquitto_auth_acl_check ()

from /etc/mosquitto/auth-plug.so
Here, user1 is the user name and t/c is the topic. GET user1-t/c seems to tell me a string type is expected in the Redis database. Can anyone give me an example of how to get this to work?
Thanks

A: I have figured out how it works. If MQTT broker only allow client user1 to pub and sub "a/b" and "c/d" topics, the correct ACL data in Redis for the JPmens plugin will be:
user1-a/b 2
user1-c/d 2
"user1-a/c" is the key and 2 is the value.

A: It's not preferred, if Redis goes down for any reason your entire system will be down also.
It will be a SPF (single point of failure) in your architecture.


text:
Q: What are the consequences of Hash-Life running in O(log n)? After reading about the HashLife algorithm, I found that it runs in O(log n). The Game of Life is also Turing Complete, so in theory we should be able to run any algorithm on a "computer" constructed in GoL.
As a consequence of HashLife's time complexity, could algorithms run faster? e.g. if an algorithm takes 10 seconds to run on a pc, could it run faster in HashLife on that same pc?
An example: An algorithm running takes a 1000 instructions to run. A certain computer can process 1 instruction per second. So that algorithm takes a 1000 seconds to run.
Now, if we take that same algorithm and run it on the "computer" in GoL. It would, because of HashLife being O(log n) take 3 seconds? (assuming O(log₁₀n))
I'm probably overlooking something, since this would be a very important discovery, but I still thought I'd ask about it here.

A: Since Hashlife runs the Game of Life which is Turing complete, it can run any Turing-computable program. If the complexity for all programs run through Hashlife would be reduced by log(n), that would for example get the (NP-complete) SAT problem (where the best known implementations have O(2^n)) run in O(n). Maybe with multiple Hashlife simulations nested in each other, you could maybe solve every problem in O(log(n)). That could eventually lead to a proof for P=NP.
The problem is that the O(log(n)) only works for the average case, while the worst case still has O(n). Hashlife has three major optimisations:

*

*A Quadtree to be able to generalise operations for all higher level nodes of the tree

*Canonicalisation of all nodes in a hashtable to have only one object for every used node layout

*Memoisation of the next generation for each node to avoid recalculating it

Both of the latter only work so well because most configurations have many reoccuring patterns and comparatively few different possible nodes. For some of the more complex starting patterns, the Golly simulator starts with the usual very quickly growing speed (when the pattern is still small and regular), but gets slower the more the pattern grows, so it has apparently not purely logarithmic complexity.
You can use memoisation to speed up any other repeated deterministic procedure. You can use trees for efficient data management. You can use canonicalisation for immutable objects to save a lot of memory and calculations.

A: Edit 2
I think looking at the math behind big O will help. I will not really do this here.
Suppose we have n cells in game of life.
Now we implement an algorithm that walks though a list of m elements. This algorithm uses O(m) time. So with the ordinairy GoL implementation this runs in O(n*m). With the more effeicient implementation it needs O(m * log(n)).
Edit 1

algorithms that currently run in e.g. O(n), run in O(log n) instead?

Algorithms do not run. They are a model. Implementations of algorithms run.
I would like the question to be stated more clearly.
Here are thoughts.
There are four cases: (without GoL O(log n)) => (with GoL O(log n))

*

*algorithms O(n) => algorithm O(log n) ? Not possible

*implementation O(n) => algorithm O(log n) ? Can exist

*implementation O(n) => implementation O(log n) ? Exists (GoL)

*algorithm O(n) => implementation O(log n) ? Not possible

A:
What I meant to ask was if a certain algorithm could run faster, because it is executed in an environment that can run at O(log n). I've also updated my question to not imply a better time complexity, just running faster. I think your logic might be a little flawed.

Even if HashLife is O(log n) and Turing Complete, there's no guarantee that a program you write in it's "programming language" is going to run any faster.  The most likely possibility is that it will run slower, because HashLife is optimized for Conway's Game of Life, not general computing algorithms.


text:
Q: How do we create a widget in Vuejs using vue-custom-element and Vuejs3 in html? I am trying to learn how to create a simple VueJs Widget using vue-custom-element in a simple HTML page so I can use that page where ever it seems fit.
I am trying to add it by following
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-custom-element@3.3.0/dist/vue-custom-element.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/document-register-element/1.4.1/document-register-element.js"></script>
<script>
  Vue.customElement('test-widget', {
    template: `<div>Hello World!</div>`
  });
</script>

Unfortunately, when I am trying to load the page I am seeing 2 errors

*

*Uncaught TypeError: window.Vue.use is not a function
at vue-custom-element.min.js:6:9328

*Uncaught TypeError: Vue.customElement is not a function
I think it has something to do with the compatibility but not quite sure. So thanks in advance and remember I am trying to make it work on the HTML page, not on Vue CLI, and please suggest if there's any better way to do it.

A: From vue-custom-element's Description:

Works with Vue 0.12.x, 1.x and 2.x

You're using https://cdn.jsdelivr.net/npm/vue, which resolves to latest 3.x.
Let's change Vue version to latest 2.x:

<script src="https://unpkg.com/vue@2/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-custom-element@3.3.0/dist/vue-custom-element.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/document-register-element/1.4.1/document-register-element.js"></script>
<script>
  Vue.customElement('test-widget', {
    template: `<div>Hello World!</div>`
  });
</script>

<test-widget></test-widget>


text:
Q: Read FITS files I have some experience in several programming languages, but I would like to try APL. I'm doing some tutorials, but I want to work in a practical example. I would like to read astronomical images from a file, in FITS format (a very common format for Astronomy data), and perform some calculations on them. An image is nothing but a big numerical matrix (mine are integers, but they could be doubles... this is not important, anyway). And each file can have one or several images (not only that, but also tables and metadata information). Once one of the images is loaded, a function with some computations would be applied to it.
I would like to know whether there is any library or package for APL with functions to perform this FITS file handling (reading, writing, modification, retrieval or change of metadata, extension, etc.), or if I should use a kind of wrapper using any other language (C, C++, Python, ...) with well established libraries to perform all the input/output, with a computational core in APL.
(I quick search in Google and in some APL oriented sites didn't yield to any valid result.)

A: I don't know of such a library in APL, although it should be fairly easy to implement.
Dyalog APL can fairly easily use FITS libraries from other languages:

Language
Inteface

C and C++
⎕NA

C# and .NET
⎕USING

Python
Py'n'APL

R
rconnect


text:
Q: React: passing props through a layout component new to React here, I want to have a filter (in Nav.js) that filters content on App.js, but  is nested in a Layout component. What's the best way to pass around props here? Can I keep everything as a functional component?
files here:
https://codesandbox.io/s/filter-menu-react-layout-uvppj?file=/src/Layout.js

A: Just pass the setFilter as props and you should be good to go.
const Layout = props => {
  const { setFilter, children } = props;
  return (
    <div>
      <Nav setFilter={setFilter} />
      {children}
    </div>
  );
};


text:
Q: angular msal v2 missing group claims I'm looking to upgrade my angular app from MSAL v1 to MSAL v2, and one problem I have is the jwt token that the guard adds to requests does not include the group field in the payload anymore.
We use group membership to decide who can access what so this is a big blocker of course.
Is there some client side config I'm missing required to get the group claims to show up in the token for MSAL v2 ? I've tried the scopes openid, user.read and profile, not sure if that's even where I should be looking.
Group claims do show up in MSAL v1 tokens, so I'm assuming the Azure config is valid.
EDIT: I'm being told the v1 token seems to be an id_token, and the v2 token is an access_token. Is there a way to get v2 to send the id_token instead of the access_token when using the Guard ?
Thank you

A: The issue seemed to be the scope, I changed it from 'openid' to my $clientid/openid and it started working.


text:
Q: react-native-snap-carousel not displaying data I am trying to add a carousel component to my HomeScreen in my portfolio project using  (https://blog.logrocket.com)implement-react-native-snap-carousel/ as the format. I have successfully ran that project as a tutorial but am having trouble translating it to my project. Would you be able to look at my code and offer some advice? Thank you  (https://github.com/anmil-dev/onStageNative)
Expected a carousel of data from EVENTS.js to display in  on HomeScreen.js


text:
Q: How many comparisons required by following algorithms to arrange the A array in decreasingorder? Insertion sort, Quick sort, Selection sort, Heap Sort Suppose you are given an array A of 'n' integers in increasing order. How many comparisons required by the following algorithms to arrange the A array in decreasing order? Insertion sort, Quick sort, Selection sort, Heap Sort.
I was just thinking that insertion sort can not be done because it arranges the elements in increase order.
HELP ME SENPAI:-(


text:
Q: How to grab output from command in shell script I'm trying to write a shell script in RHEL which will execute grub-md5-crypt and the user will type their password.
Now the problem is how can I grab the encrypted md5 hash displayed to the user in the shell script?
I tried to figure this out but command redirection will not work here.
So how can I get the md5 encrypted text in the shell script after the script has executed grub-md5-crypt?

A: result=$(grub-md5-crypt | grep xy)
echo $result

If grub-md5-crypt prints to stderr use:
result=$(grub-md5-crypt 2>&1 | grep xy)
echo $result

A: If it doesn't work in your shell script you might want to use bash.
Just add:
#!/bin/bash

It must be in the first line of your file!
This means your script will be using bash interpreter other than normal shell's one (/bin/sh).
Completing noEntry's answer, you can also save output to a file.
grub-md5-crypt | grep xy > output

Or:
result=$(grub-md5-crypt 2>&1 | grep xy)
echo $result > output

This will generate a file names output with whatever would have been printed on screen.


text:
Q: How can I use a custom view of generic type (CustomView) in android layout xml? I am trying to use a CustomView<T> in layout xml. But getting "missing type arguments for generic class CustomView."
To ignore this issue I created a sub class of CustomView<T> which resolved the issue. But my goal was not achieved completely because this view will be used in multiple places with different type arguments so I am looking for some general solution.
I tried to resolve it by lint.xml by adding the below line but it is not resolved.
<issue id="rawtypes" severity="ignore"/>

Please suggest some trick to resolve it.


text:
Q: Qt QTreeView editable DOM model I have a QTreeView to which I set a subclassed DomModel:QAbstractItemModel. Each item is a DomItem which deals mostly with QDomNode. I set QDomDocument to this model. I think I've derived this system from one of the Qt examples.
It has 3 columns: 0 for node name, 1 for attributes and 2 for value.
Anyway, I wanted to make this XML DOM tree editable. I've modified some flags such as Qt::ItemIsEditable and some other things in the model class and now I can edit the model through QTreeView by double clicking.
For column 2 it's easy, since QDomItem has this setNodeValue function, however I've found there are no "set" functions for item->node().NodeName() and item->node().attributes() which would, I presume, modify columns 0 and 1.
So now when I modify column 2 it works, however columns 0 and 1 revert to their previous values upon pressing enter.
bool DomModel::setData(const QModelIndex &index, const QVariant &value,
                    int role)
{
if (role != Qt::EditRole) return false;

DomItem *item = static_cast<DomItem*>(index.internalPointer());

switch (index.column()){
    case 0:
        // ???
        break;
    case 1:
        // ???
        break;
    case 2:
        item->node().setNodeValue(value.toString());   // This works - QTreeView is updated
        break;
}
...
}

A: Well, apparently item->node().toElement() which returns a QDomElement has the necessary "set" functions and it works. So I think I've found a way to fully modify my XML DOM file through QTreeView.
This does the trick for me:
switch (index.column()){
   case 0: // added
      item->node().toElement().setTagName(value.toString());
      break;
   case 1: // added
      // this shall be modified to account for nonstandard spacings, etc.
      aux = value.toString().trimmed();
      aux.remove("\"");
      attributes.clear();
      attributes = aux.split(" ");
      for(int i = 0; i<attributes.size(); i++){
         item->node().toElement().setAttribute(attributes.at(i).split("=").at(0),
                                               attributes.at(i).split("=").at(1));
      }
      break;
   case 2: // Left it as it is
      item->node().setNodeValue(value.toString());   // This works - QTreeView is updated
      break;
}


text:
Q: How to get the SET_TIME permission I am developing a device owner app.
In the app I'm trying to gain the SET_TIME permission by using:
DeviceOwnerHelper.getInstance().getDevicePolicyManager().setPermissionGrantState(new ComponentName(this, DeviceOwnerReceiver.class), getApplicationContext().getPackageName(), Manifest.permission.SET_TIME, DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED);

But this method does not work? Please help!

A: You need to run your app as system/app in order to achieve that. In short a short way to say it you have to run your app under the folder /system/ or system/priv-app in some devices.
I am setting the time in my app using the shell with this command: (I have root access)
adb shell su 0 date -u [timethatyouwant]

edit: I typically use this commands to run my app as system/app
Don't know if I helped :p just look for it ;)


text:
Q: Non-trivial integral forms of algebras Suppose $\mathcal{A}$ is a $\mathbf{C}$-algebra then an integral form would be a subring $\mathcal{B} \subset \mathcal{A}$ such that the canonical map $\mathcal{B}  \otimes_{\mathbf{Z}} \mathbf{C} \rightarrow \mathcal{A}$ is a bijection.
For some algebras there is an obvious integral form in the following sense: there is a preferred $\mathbf{C}$-basis for $\mathcal{A}$ and the $\mathbf{Z}$-span of that basis is $\mathcal{B}$.  Now my question is do we have examples where $\mathcal{B}$ is non-obvious? In other words the basis coming from $\mathcal{B}$ would look very strange for those who only work with $\mathcal{A}$. Is there such an example where $\mathcal{A}$ is commutative?

A: Finite dimensional algebras (over alg. closed fields) which are of finite representation type have multiplicative bases, that is, bases such that the product of two of its elements is either an element of the basis or zero. This is a difficult and beautiful theorem of R. Bautista, P. Gabriel, A. Roiter and L. Salmerón.
This gives rather special integral forms for such algebras and, in general, it is quite non-obvious how to get them.

A: There are many important integral forms with a "strange" appearance. Namely, we have
1) Kostant's form for a finite-dimensional complex simple Lie algebra, see the classical Humphrey's book;
2) Garland's form for the loop algebra of a finite-dimensional complex simple Lie algebra $g$, see the proper Garland's paper. In this case appear some elements given by the coefficient of some series given by the exponential of a suitable generating series with coeficients in the loop Cartan subalgebra of $g$.
For commutative cases we probably have those expected elements from a $\mathbb{C}$-basis, since the "strange" elements always come from brackets in the non-commutative case!
Hope help you,

A: I got some "strange" integral forms when I generalized Garland's integral forms for the loop algebras to the map algebras of complex simple Lie algebras. The map algebras are a generalization of the loop algebras where we replace $\mathbb{C}[t^{\pm1}]$ by any algebra A. My integral forms are valid when A has a basis which is closed under multiplication. Thanks Mariano for letting me know that they are valid in more cases than I previously thought.


text:
Q: Spring4 error handling and HTTP status codes returned for REST services We are writing Spring4 based REST services and had a question about returned HTTP status codes.  It looks like the generally accepted approach is to let the app server or web server container handle the responses when the HTTP  protocol is not met.  For example 500 Internal Server could imply that the apache server internally has some permission issue.  For everything, a 200 should be returned by the application code.
I noticed that Spring and some Java libraries return 400 or 500 or other status that aren't necessarily associated with the standard HTTP response.  Are these libraries wrong?  For example, if any exception is thrown within a service method then a 500 is returned to the client. Is the HTTP response convention broken by Spring?  In that case, because an exception might be thrown by application code, shouldn't a 200 status code be returned?  Should the application code catch the error, return a 200 status code and add a more business/application specific message.  Let's say the application database is having issues?  Or is it OK to return the 500 message?

A:
For example 500 Internal Server could imply that the apache server
  internally has some permission issue.

Not necessarily. Uncached errors in the server-side application will cause the java server to return a "controlled" error 500.
From the web client point of view, 500 means:
-Something went wrong (somewhere) on the server-side. We don't know what. Don't retry the request-

For everything, a 200 should be returned by the application code.

The catalogue of status code is wider, but 200 is basically the default code to say: Ok, everything went fine. I encourage you to look at the 2xx status code list to enrich server-client the communication.

For example, if any exception is thrown within a service method then a
  500 is returned to the client. Is the HTTP response convention broken
  by Spring?

That's ok. When application errors reach the application server, the server catches them and does return the only reasonable error for uncontrolled errors. 500.

In that case, because an exception might be thrown by application
  code, shouldn't a 200 status code be returned?

That would be read in this way:
--the request successfully failed--
From the communication point of view, it doesn't seem to me effective. Usually, 5xx error codes mean: Try it much later, while 4xx codes mean: Try it again but, this time, do it well. Returning a 2xx code when the request didn't finish successfully. What are we communicating to the client?
We might argue that the text message will tell the user what to do, despite de https status code but, what happens if there's no user? How would you programme a machine-to-machine communication if every call ends "successfully"? Matching strings? Declaring custom status codes? Wouldn't that add unnecessary complexity?

Should the application code catch the error, return a 200 status code
  and add a more business/application specific message.

Depends. If you want your application to be a good www citizen then no, you should not. It's good for web applications to make a proper usage of the architecture web. So, if you need to communicate an error (5xx, 4xx) alongside with a specific error message, then do It. Tell to the web client: the request has not been processed due to the following errors

Let's say the application database is having issues? Or is it OK to
  return the 500 message?

It's ok, For this specific case, a 500 status code make sense. But, ultimately, depends on the requirements and your preferences. If you are concerned about how to manage the error handling with Spring web, it might interest the following links 1 or 2.


text:
Q: Using Object.assign with Observable Array I'm using Object.assign to add an attribute to each element of an Observable Array
Struggling figuring out the right operators to add an attribute to each object of the array. For example, in this case the name field was used inappropriately for grade.
Example:
let x = Observable.of({id: 1, name: first grader}, {id: 2, name: second grader})

// current solution using flatmap and then re-configuring as array
x
.flatMap( res => res.map( student => Object.assign({}, student, {grade: student.name})))
.toArray()

The above example works, but seems strange...as I'm flatmapping and then re-constituting the array.  Is there a better operator/ approach to reduce the steps?
If I just use Object.assign on the initial observable I get:
    Object {0: Object, 1: Object}, which is an object of objects rather than an array of objects.

A:
The above example works, but seems strange...as I'm flatmapping and
  then re-constituting the array. Is there a better operator/ approach
  to reduce the steps?

If your data is already available as an array then you can mutate the complete array yourself:
Rx.Observable.of([{id: 1, name: 'first grader'}, {id: 2, name: 'second grader'}])
  .map(students => {
    // note - this map below is Array.prototype.map, not Rx
    return students.map(student => Object.assign({}, student, {grade: student.name}));
  })
  .subscribe(x => console.log(x));

But Rx really shines when your data is received async:
Rx.Observable.from([{id: 1, name: 'first grader'}, {id: 2, name: 'second grader'}]) /* stream of future student data elements */
  .map(student => Object.assign({}, student, {grade: student.name}))
  .toArray() // combine your complete stream when completed into a single array emission
  .subscribe(x => console.log(x));

The toArray() is a utility function to wait for completion and then return all emitted elements inside an array as the first (and final) emission.

A: If you run your code as it is it will fail. Because if you pass multiple objects to Observable.of it will push them into stream one by one.
So I assume what you meant is
    Rx.Observable.of([{id: 1, name: 'first grader'}, {id: 2, name: 'second grader'}])

note the square brackets.
To achieve what you want you can use map operator:
    Rx.Observable.of([{id: 1, name: 'first grader'}, {id: 2, name: 'second grader'}])
      .map(res => res.map( student => Object.assign({}, student, {grade: student.name})))
      .subscribe(x => console.log(x));

See jsBin


text:
Q: Horizontal alignment of math accents for slanted symbols I want a double widehat accent. Here's my setup: xelatex, accents package, and a definition of dwtilde command (as a reference to dhatheight shows, the code is a modification of someone else's code found on the Web):
\newcommand{\dwtilde}[1]{%

    \settoheight{\dhatheight}{\ensuremath{\widetilde{#1}}}%

    \addtolength{\dhatheight}{-0.2ex}%

    \widetilde{\vphantom{\rule{1pt}{\dhatheight}}%

      \smash{\widetilde{#1}}}}

I'm using euscript for Euler fonts. Then, a $\dwtilde{\mathscr A}$ produces two wide tildes with the top one shifted to the left. How do I put the accents aligned horizontally?
Here's an example:

A: Run it with xelatex
\documentclass{article}
\usepackage{unicode-math}
\usepackage{libertine}
\def\dWDTilde#1{\widetilde{\widetilde{#1\mkern0mu}}}
%\setmathfont{XITS Math}

\begin{document}
foo
$\dWDTilde{\mathscr A}$
foo

\end{document}


text:
Q: perl: string matching to find longest substring $string1 = "peachbananaapplepear";
$string2 = "juicenaapplewatermelonpear";

I want to know what's the longest common substring containing the word "apple".
$string2 =~ m/.+apple.+/;
print $string2;

So I use the match operator, and .+ for matching any character before and after the keyword "apple". When I print $string2 it doesn't return naapple but returns the original $string2 instead.

A: Here is one approach. First get the locations where 'apple' appears in the strings. And for each of those locations in string1, look at all locations in string2.
Look to the left and right to see how far the commonality extends from the initial location.
$string1 = "peachbananaapplepear12345applegrapeapplebcdefghijk";
$string2 = "juicenaapplewatermelonpearkiwi12345applebcdefghijkberryapple";

my $SearchFor="apple";
my $SearchStrLen = length($SearchFor);

# Get locations in first string where the search term appears
my @FirstPositions =  getPostions($string1);
# Get locations in second string where the search term appears
my @SecondPositions =  getPostions($string2);

CheckForMaxMatch();

sub getPostions
{
  my $GivenString = shift;
  my @Positions;
  my $j=0;
  for (my $i=0; $i < length($GivenString); $i += ($SearchStrLen+1) )
  {
    $j = index($GivenString, $SearchFor, $i);
    if ($j == -1) {
     last;
    }
    push (@Positions, $j);
    $i = $j;
  }

  return @Positions;
}

sub CheckForMaxMatch
{
  my $MaxLeft=0;
  # From the location of 'apple', look to the left and right
  # to see how far the characters are same
  for my $i (@FirstPositions) {
    for my $j (@SecondPositions) {
      my $LeftMatchPos = getMaxMatch($i, $j, -1);
      my $RightMatchPos = getMaxMatch($i, $j, 1);

      if ( ($RightMatchPos - $LeftMatchPos) > ($MaxRight - $MaxLeft) ) {
        $MaxLeft = $LeftMatchPos;
        $MaxRight = $RightMatchPos;
      }
    }
  }

  my $LongestSubString = substr($string1, $MaxLeft, $MaxRight-$MaxLeft);
  print "Longest common substring is: $LongestSubString\n";
  print "It begins at $MaxLeft and ends at $MaxRight in string1\n";
}

sub getMaxMatch
{
  my $i= shift;
  my $j= shift;
  my $direction= shift;

  my $k = ($direction >= 1 ? $SearchStrLen : 0);

  my $FirstChar = substr($string1, $i+($k * $direction), 1);
  my $SecondChar = substr($string2, $j+($k * $direction), 1);

  for ( ; $FirstChar && $SecondChar; $k++ )
  {
    $FirstChar = substr($string1, $i+($k * $direction), 1);
    $SecondChar = substr($string2, $j+($k * $direction), 1);
    if ( $FirstChar ne $SecondChar ) {
      $direction < 1 ? $k-- : "";
      my $pos = ($k ? ($i + $k * $direction) : $i);
      return $pos;
    }
  }

  return $i;
}

A: The =~ operator is not going to reassign the value of $string2.  Try this:
$string2 =~ m/(.+apple.+)/;
my $match = $1;
print $match

A: Based on the general algorithm, but tracks not only the length of the current run (@l), but whether it includes the keyword (@k). Only runs that include the keyword are considered for longest run.
use strict;
use warnings;
use feature qw( say );

sub find_substrs {
   our $s;   local *s   = \shift;
   our $key; local *key = \shift;

   my @positions;
   my $position = -1;
   while (1) {
      $position = index($s, $key, $position+1);
      last if $position < 0;

      push @positions, $position;
   }

   return @positions;
}

sub lcsubstr_which_include {
   our $s1;  local *s1  = \shift;
   our $s2;  local *s2  = \shift;
   our $key; local *key = \shift;

   my @key_starts1 = find_substrs($s1, $key)
      or return;

   my @key_starts2 = find_substrs($s2, $key)
      or return;

   my @is_key_start1;  $is_key_start1[$_] = 1 for @key_starts1;
   my @is_key_start2;  $is_key_start2[$_] = 1 for @key_starts2;

   my @s1 = split(//, $s1);
   my @s2 = split(//, $s2);

   my $length = 0;
   my @rv;
   my @l = ( 0 ) x ( @s1 + 1 );  # Last ele is read when $i1==0.
   my @k = ( 0 ) x ( @s1 + 1 );  # Same.
   for my $i2 (0..$#s2) {
      for my $i1 (reverse 0..$#s1) {
         if ($s1[$i1] eq $s2[$i2]) {
            $l[$i1] = $l[$i1-1] + 1;
            $k[$i1] = $k[$i1-1] || ( $is_key_start1[$i1] && $is_key_start2[$i2] );

            if ($k[$i1]) {
               if ($l[$i1] > $length) {
                  $length = $l[$i1];
                  @rv = [ $i1, $i2, $length ];
               }
               elsif ($l[$i1] == $length) {
                  push @rv, [ $i1, $i2, $length ];
               }
            }
         } else {
            $l[$i1] = 0;
            $k[$i1] = 0;
         }
      }
   }

   for (@rv) {
      $_->[0] -= $length;
      $_->[1] -= $length;
   }

   return @rv;
}

{
   my $s1 = "peachbananaapplepear";
   my $s2 = "juicenaapplewatermelonpear";
   my $key = "apple";

   for (lcsubstr_which_include($s1, $s2, $key)) {
      my ($s1_pos, $s2_pos, $length) = @$_;
      say substr($s1, $s1_pos, $length);
   }
}

This solution in O(NM), meaning it scales amazingly well (for what it does).


text:
Q: How to get previous image? I'm trying to create a gallery based on this http://snook.ca/archives/javascript/simplest-jquery-slideshow tutorial and a problem arouse - i cant select previous image. Can somebody help?
The code is simple:
jQuery('#next_image').click(function(){
    jQuery('#archive_gallery :first-child').hide().next('img').show().end().appendTo('#archive_gallery');
});

Found a solution:
jQuery('#archive_gallery :last-child').prependTo('#archive_gallery').show().next('img').hide().end();


text:
Q: Who or whom in this statement? What is the proper pronoun in the following sentence?

There is no concept of leadership beyond (whomever/whoever) happens to be most experienced on a given team.

A: The answer is whoever. Since the person in question is the subject of the verb "happens," the nominative is correct. See this page from Cambridge on who/whom for details.
Furthermore, as the above article notes, "whom" is slowly being replaced by "who," so one could argue that one should use "whoever" regardless of context.
Incidentally, "beyond" may be the wrong word here. MacMillan defines it in this sense as "except," which does not work in context.


text:
Q: In Nginx, how to redirect to another domain, but to also preserve the path AND the subdomain? So, for instance, I have a domain olddomain.com and newdomain.com
Here's how I want requests redirects to work:
sub.olddomain.com/hello/world -> sub.newdomain.com/hello/world
olddomain.com/hello/world     -> newdomain.com/hello/world
There are many subdomains, so ideally I wouldn't want to create a rule for each one of them.
This seems like a solution:
server {
  listen 80;
  server_name olddomain.com *.olddomain.com;
  rewrite ^(/)(.*)$ http://newdomain.com/$2 permanent;
}

but it doesn't work with subdomains, since all subdomains would redirect to newdomain.com/path without regard for a subdomain.

A: You seem to be looking for something like this:
if ($http_host ~ (.*)\.olddomain\.com) {
    set $subdomain $1;
    rewrite (.*)$ http://$subdomain.newdomain.com$1 permanent;
}
rewrite ^(/)(.*)$ http://newdomain.com/$2 permanent;

These are my testcases
$ curl -I -H "Host: test1.olddomain.com" nginx1.tst
HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.4
Date: Thu, 08 May 2014 19:40:33 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: http://test1.newdomain.com/

$ curl -I -H "Host: test1.test2.olddomain.com" nginx1.tst
HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.4
Date: Thu, 08 May 2014 19:40:38 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: http://test1.test2.newdomain.com/

$ curl -I -H "Host: test1.test2.olddomain.com" nginx1.tst/with-something/appended.html
HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.4
Date: Thu, 08 May 2014 19:40:54 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: http://test1.test2.newdomain.com/with-something/appended.html

$ curl -I -H "Host: olddomain.com" nginx1.tst
HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.4
Date: Thu, 08 May 2014 19:41:10 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: http://newdomain.com/