text:
Q: Await and Async callbacks hell I want to make the UserDataGenerator class works like a traditional SYNC class.
My expectation is that userData.outputStructure can give me the data prepared.
let userData = new UserDataGenerator(dslContent)
userData.outputStructure

getFieldDescribe(this.inputStructure.tableName, field) is a ASYNC call which invokes Axios.get
Below is my current progress but it's still not waiting for the data ready when I print out the userData.outputStructure
export default class UserDataGenerator {
    inputStructure = null;
    outputStructure = null;
    fieldDescribeRecords = [];
 constructor(dslContent) {

    this.outputStructure = Object.assign({}, dslContent, initSections)
    process()
}

async process() {
    await this.processSectionList()
    return this.outputStructure
}

async processSectionList() {
    await this.inputStructure.sections.map(section => {
       this.outputStructure.sections.push(this.processSection(section));
    })
}

async processSection(section) {
    let outputSection = {
        name: null,
        fields: []
    }
    let outputFields = await section.fields.map(async(inputField) => {
        return await this._processField(inputField).catch(e => {
            throw new SchemaError(e, this.inputStructure.tableName, inputField)
        })
    })
    outputSection.fields.push(outputFields)
    return outputSection
}

async _processField(field) {
    let resp = await ai
    switch (typeof field) {
        case 'string':
            let normalizedDescribe = getNormalizedFieldDescribe(resp.data)
            return new FieldGenerator(normalizedDescribe, field).outputFieldStructure
    }

}

A: You're trying to await arrays, which doesn't work as you expect. When dealing with arrays of promises, you still need to use Promise.all before you can await it - just like you cannot chain .then on the array.
So your methods should look like this:
async processSectionList() {
    const sections = await Promise.all(this.inputStructure.sections.map(section =>
         this.processSection(section)
    ));
    this.outputStructure.sections.push(...sections);
}

async processSection(section) {
    return {
        name: null,
        fields: [await Promise.all(section.fields.map(inputField =>
            this._processField(inputField).catch(e => {
                throw new SchemaError(e, this.inputStructure.tableName, inputField)
            })
        ))]
    };
}


text:
Q: Upload Images in asp.net mvc 3 aspx syntax for custom class without database I am having a problem uploading images in ASP.NET MVC 3. Currently I have a class called EmployeeModel which has the properties for employees:
public class EmployeeModel       //Model for employee information
{
    [Required(ErrorMessage = "ID Required")]
    public int ID { get; set; }//Employee Id

    [Required(ErrorMessage = "Name Required")]
    [RegularExpression(@"^[a-zA-Z\s]+$", ErrorMessage = "Name can have only alphabets and spaces")]
    public string Name { get; set; }//Employee Name

    [DataType(DataType.Date)]
    public DateTime DOB { get; set; }//Employee Date of birth

    [DataType(DataType.Date)]
    public DateTime DOJ { get; set; }//Employee Date of Joining

    [Required(ErrorMessage = "Address Requried")]
    public string Address { get; set; }//Employee Address

    [Required(ErrorMessage="Mobile Number Requried")]
    [RegularExpression(@"[0-9]{10}", ErrorMessage = "Mobile number not valid")]
    public double Mobile { get; set; }//Employee Mobile number

    [Required(ErrorMessage = "Email Requried")]
    [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Email Id not  valid")]
    public string Email { get; set; }//Employee Email-ID

    [Required(ErrorMessage = "Designation Requried")]
    public string Designation { get; set; }//Employee Designation

    [Required(ErrorMessage = "Salary Required")]
    public double Salary { get; set; }//Employee Salary
}

The requirement is that I need to upload an image for each employee and display them. I'm using a text file to store the information of the employee (acting as a database).

A: Maybe these articles can help: this and this.
The one from CodeProject uses MongoDB, but I think you can ignore that parts and get what you want. It seems simple enough.
And this one is the most simple one from SO.

A: Try to use HttpPostedFileBase property in your model.
And in your POST action use :
@using (Html.BeginForm("Action_name", "Controler_name", FormMethod.Post,
                                   new { enctype = "multipart/form-data" }))
{
// your form data here
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Will using Parallel.ForEach in ASP.NET prevent other threads from processing requests? I'm looking at using some PLINQ in an ASP.NET application to increase throughput on some I/O bound and computationally bound processing we have (e.g., iterating a collection to use for web service calls and calculating some geo-coordinate distances).
My question is: should I be concerned that running operations like Parallel.ForEach will take threads away from processing other requests, or does it use a separate pool of threads (I've heard about something called I/O completion ports, but not sure how that plays into the discussion)?

A: Parallel.ForEach will, at most, use one thread for as many cores as you have. The thread pool default maximum size is 250 times the number of cores you have. So you'll have to be really trying to run out of available threads.


text:
Q: trigger a save programmatically in a custom AEM component We have the need to create a custom AEM component that is able to trigger a save to the JCR programmatically (in the location of the page that is being edited). When building a custom AEM Component, you don't need to call the 'save' logic manually, you just add a <content> tag, and AEM will automatically add the content to the JCR when saving the dialog.
How can manually trigger the same save operation that would be executed when clicking the 'save' button on the custom AEM Component?

A: The AEM page/template editor does async POST requests when you drag'n'drop components on a page, for example:

You can implement an async request as well for your save button and leverage the Sling POST Servlet or your own custom servlet to add to the JCR.


text:
Q: C# monitor microphone usage I'm looking for an ability in managed code to monitor which processes are accessing microphone devices on my computer.
I was able to find C++ examples of viewing audio output (AudioSessionManager), but is there an API for input devices also?
Extended: How can one protect himself against microphone spying on Windows oeprating system?


text:
Q: Add html string inside td of table I need create a table from array string, and I use template script, it working with normal string but when I add string have html tag (ex: test) in array and my result show a button in td tag but I want it is string "test".
How I can show string html in td?
Here is my code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

      <title>JSON Transform</title>

Thank you verymuch.

A: If you want to display the <button> </button> without it converting to an HTML element you can escape the > and < symbols like this:
'<' = '<'
'>' = '>'

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

      <title>JSON Transform</title>


text:
Q: build errors in c++ code I have following c++ code and i am getting build errors in it.I am unable to find out the errors please any one help.Here is the code
#include<stdlib.h>
#include <iostream.h>
using namespace std;

class PropertyPortal;
class PropertyType;
class Commercial;
class Residential;
void main()
class PropertyPortal
{
private:

        int NoOfUsers;
        int UAN;
        char* Name;

        public:
       void setNoOfUsers(int no);
       void setUAN(int u);
       void setName(int n);
       int getNoOfUsers();
       int getUAN();
       char getName();
       int getPropertyInfo();
       //constructors of the class
       PropertyPortal();
       PropertyPortal(int, int, char);
       //destructor of the class
       ~PropertyPortal ();

       void setNoOfUsers(int no)
       {
                        NoOfUsers>=1;
                        }
                        void setUAN (int u);
                        {
                        NoOfUsers>=0;
                        UAN>=1;
                        Name=Null;
                        }
                        PropertyPortal (int no, int u, char* n)
                        {
                        NoOfUsers>=no;
                        UAN=u
                        Name=VU-Real-Estate;
                        }
                        PropertyPortal (int no, int u, char* n)
                        {
                        NoOfUsers>=no;
                        UAN=u
                        Name=n;
                        }
                        void setNoOfUsers(int no)
                        void setUAN(int u)
                        void setName(char n)
                        int getNoOfUsers()
                        int getUAN()
                        char getName()
                        int getPropertyInfo();
class PropertyType
{
      private:
              char* City
public:
        void setCity(char c);
        char getCity(char c);
        void getPropertyType();
        PropertyType();
        PropertyType(char);
        ~PropertyType();
        PropertyType();
{
        City=Null
}
        PropertyType(char* cCity)
{
        City=cCity
        }
        };
class Commercial:PropertyType
{
private:
        int PropertyValue
public:
       void setPropertyValue();
       int getPropertyValue();
       void getPlots();
       Commercial();
       Commercial(char);
       ~Commercial();
};

class Residential:PropertyType
private:
        int PropertyValue;
public:
       void setPropertyValue();
       int getPropertyValue();
       int getPropertyCategory();
};
void main ()
{
cout<<"This is just a prototype of all classes";
cout<<endl;
system("PAUSE");
}

I got error on line 2,32:2,10,103 Please help me to find out whats wrong and whats going on with the code.
Update

A: A lot of the errors are coming from having both function declarations and definitions inside the class. Do either
class Foo
{
    public:
        int func();
};
int Foo::func() { return 5; }

or
class Foo
{
    public:
        int func() { return 5; }
};

but not
class Foo
{
    public:
        int func();
        // ...
        int func() { return 5; }
};

I also see that you intend to have two constructors, one with default values, and one taking values from the creator. But then you do this:
PropertyPortal (int no, int u, char* n)
{
    NoOfUsers>=no;
    UAN=u
    Name=VU-Real-Estate;
}
PropertyPortal (int no, int u, char* n)
{
    NoOfUsers>=no;
    UAN=u
    Name=n;
}

I suspect you really mean
PropertyPortal ()
{
    NoOfUsers=1;
    UAN=1;
    Name="VU-Real-Estate";
}
PropertyPortal (int no, int u, char* n)
{
    NoOfUsers=no;
    UAN=u
    Name=strdup(n); // Remember to free() this later.
}

In fact, you'ld be even better off to scrap char*s all together, and use std::string, and maybe read about initializer lists.


text:
Q: How to make a fade-in effect in a div behind another div, without the former overlapping the latter? During the fade-in animation, the blue div is overlapping the red one, even though the red div has "position: absolute". How can I make it so the red one is on top also during the blue div's fade-in animation (preferably using only css, if it's not possible, with vanilla javascript instead)?
Live demo: https://jsfiddle.net/s5yvoL4z/2/#&togetherjs=4c97JQOdcD
Code:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

A: Add z-index: 1 to your .a class and for cleanliness add z-index: 0 to your .b class. The position attribute affects the positioning of the element but not the order in which they are stacked.

        .a {
          background-color: red;
          width: 15em;
          height: 15em;
          position: absolute;
          margin-top: -5rem;
          z-index: 1;
        }

        .b {
          background-color: blue;
          width: 15em;
          height: 15em;
          margin-top: 5rem;
          animation: show-img 1s;
                    z-index: 0;
        }

        @keyframes show-img {
          from {
            opacity: 0;
          }

          to {
            opacity: 1;
          }
        }
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

A: .a {
    background-color: red;
    z-index: 1;
    width: 15em;
    height: 15em;
    position: absolute;
    animation: show-img 2s;
}

.b {
    background-color: blue;
    position: absolute;
    width: 15em;
    height: 15em;
}

@keyframes show-img {
  from {opacity: 1;}
  to {opacity: 0;}
}

A: This can be achieved by adding z-index: 1; to the .a.


text:
Q: Add Table View to Data View in ArcMap gives Assertion Error I'm trying to create a Python AddIn for ArcMap 10.6 and the first process of the tool will be to add a tableview to a map document. At this point I just want python code to bring up rows from a table specified by a where clause when creating the table view so you can see this tableview in the data view display of the map document.
Here's my code so far:
import arcpy

# construct where clause
val = "\'%2%\'"
f1 = "DIST_NAME"
WC = """{} LIKE {}""".format(f1, val)

# create tableview
cList = arcpy.MakeTableView_management("CensusTract", "cList", WC)

# add tableview to dataframe
mxd = arcpy.mapping.MapDocument(r"C:\TableView.mxd")
df = arcpy.mapping.ListDataFrames(mxd)[0]
arcpy.mapping.AddTableView(df, cList)

And here is the error that I'm getting:
Runtime error
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "c:\program files (x86)\arcgis\desktop10.6\arcpy\arcpy\utils.py", line 182, in fn_
    return fn(*args, **kw)
  File "c:\program files (x86)\arcgis\desktop10.6\arcpy\arcpy\mapping.py", line 114, in AddTableView
    assert isinstance(add_table, TableView)
AssertionError

A: Instead of:
# create tableview
cList = arcpy.MakeTableView_management("CensusTract", "cList", WC)

# add tableview to dataframe
mxd = arcpy.mapping.MapDocument(r"C:\TableView.mxd")
df = arcpy.mapping.ListDataFrames(mxd)[0]
arcpy.mapping.AddTableView(df, cList)

try this:
# create tableview
tblView = arcpy.mapping.TableView("CensusTract")

# add tableview to dataframe
mxd = arcpy.mapping.MapDocument(r"C:\TableView.mxd")
df = arcpy.mapping.ListDataFrames(mxd)[0]
arcpy.mapping.AddTableView(df,tblView)

I used the AddTableView help to come up with the above untested code.


text:
Q: Vim move out of the braces/brackets without using the arrow keys or hl keys? My autocomplete for vim inserts something like this for C++ code:
if( ){

}

Inside the () is where my cursor is going to be.  Suppose I want to type
if(X[i] == 0){

}

I would type X, then [ and the closing brace will automatically be inserted, ].
I then type i, now my cursor is between i and closing ]. How do I get out so that I can keep typing the rest, the == 0 part?
If there is no autocomplete for the if statement, then it would be easy because I do not have to worry about the ( ).  I can just type, if, (, X[i].  To get out of the bracket, I would just use append, A and then go on to type the rest: == 0 ).
Normally, I would use the arrow key or hl to move out of the brackets.  Is there another way to do this?

A: There are several parts to your problem, and plugins that solve them -- of course you could reimplement them...
Regarding the auto-pairing, most (all?) bracketing plugins provide a jump over the closing bracket character by hitting the related key. Here for instance you could simply type ] instead of <right> or <esc>la as you would have done without the auto-pairing feature.
Note: contrary to most solutions you could copy paste from a 1990's vi trick, the plugins will permit to redo (:h .) an insertion where brackets appear.
I'm quite sure the exact technical solution has already been given here and/or on vi.SE.

There is another issue you haven't mentioned: jumping to in-between the curly brackets corresponding to the true branch of the if. To achieve this, we rely on placeholders. They could be inserted by snippet plugins, or through very advanced abbreviations.
The trendy snippet plugins have discrete placeholders. The plugins I'm maintaining have more intrusive placeholders (lh-cpp, mu-template. Placeholders that my bracketing plugin also inserts by default. What does this means? It means that typing if or [ will insert the same placeholders that also serve as jump points. As a consequence, I can use the same jump keybinding (CTRL+J by default in terminal vim) to jump after the closing ] or in between the {} -- hitting ] works as well when the cursor is just before a ], etc.


text:
Q: Constants and Pointers This is going to be a long-winded post, so I apologize in advance.. but trying to ask multiple questions with context:
So, I've been trying to learn C++, and I've been picking everything up fairly easily, but I make a habit of trying to do things alongside the tutorials in "slightly different ways", in order to ensure that I understand the functionality of the thing I'm learning.
I seem to have hit a mental roadblock regarding constants and their involvements with pointers.
In the previous section, I think I got a pretty solid grip on references, dereferences (and the difference between * when used for dereferences and pointers), and then wrote this code:
int a[5];
int * p;

p = a;

cout << "Select the value for the first item at address(" << &a[0] << ")" << nl;
cin >> *p;
p++;
cout << "Select the value for the second item at address(" << &a[1] << ")" << nl;
cin >> *p;
p++;
cout << "Select the value for the third item at address(" << &a[2] << ")" << nl;
cin >> *p;
p++;
cout << "Select the value for the fourth item at address(" << &a[3] << ")" << nl;
cin >> *p;
p++;
cout << "Select the value for the fifth item at address(" << &a[4] << ")" << nl;
cin >> *p;

for (int n=0;n<5;n++)
    cout << a[n] << "(" << &a[n] << ")" << nl;

Now, I realize that this isn't necessarily the most "optimized" solution, ever.. but it worked, I was able to "write" into the array I had store on the memory, and display the changes. It was neat, and like I said.. I think I got a pretty good understanding of how these things worked.
..and then, I hit the next section, which used the example:
const char * terry = "hello";

to teach me, and I quote: "As in the case of arrays, the compiler allows the special case that we want to initialize the content at which the pointer points with constants at the same moment the pointer is declared" (this being on the cplusplus.com tutorial).
Anyway, to get to the point: in order to try and familiarize myself with it and the previous section, I tried writing:
const char * p = "Hello.";

for (int n=0;n<5;n++)
    cout << p[n] << "(" << &p[n] << ")" << nl;
    cout << nl;

..and this does not work. I essentially tried replicating my previous code (although without the writing aspect) in an attempt to be able to read the RAM-location of each character in this constant array, and I experimented with every possible combination of pointers, references, dereferences, etc.. but I just get a print out of the whole "Hello." array with &p.
How in the hell does one get the reference of a constant array? I think I understand the basic premise that I'm creating an array and immediately allocating it to memory, and then assigning a pointer (p) to the first block ("H")'s location.. but I can't seem to print the blocks out. I was able to get the location of the first block to print at one point (can't remember what code I used to do this) and tied it into the for loop, but even then.. it just ALWAYS printed the location of the first block, even when assigned to follow the [n] count.
I have no idea what I'm missing, here, or if I'm just trying to reach "over my head", but maybe I just don't understand the usage/point of creating an array without being able to location the memory assignment of each item within it..
This brings me to my next issue, though. How does one get the memory location of a char variable, whether constant or not? I have been having issues with this code, as well:
char const a = 100;
int * b = &a;

cout << a << nl << *b << nl;
cout << nl;

Obviously, this doesn't work.. because I can't assign b to the location of a, since they're different variables.. and obviously making a char pointer is silly, since it's just going to print messed up/null characters instead of the location (I checked this, obviously.. not just assuming).
I hope I'm just missing an option to use which may just be "more advanced" than where I'm currently at.. but if I'm not, I don't quite see the point in being able to access the block location of any type of variable/constant, if you can't access ALL of them due to restrictions of the type being used.
This problem is sorta what limits the third quoted code, too: the fact that I can't just assign a variable to hold the &p value, since it itself would have to be a char to be compatible.. which is pointless since char can't hold the eight-digit reference.

A: In
const char * p = "Hello.";

[...]   cout << &p[n]   [...]

&p[n] is a pointer to char, and cout::operator<< has an overload that takes a pointer to a char and prints a null-terminated string, that's probably why you're confused.


text:
Q: Databse won't update after using fetchAll()? I am trying to get my database update after taking input from a form. It won't work, what do I do?
Issue:

*

*Input into forum after submitting won't change/update the database

What I've tried:

*

*Trying to just echo out every and each statement seperately

*Make seperate queries for each different variable (input variable)

Current code:

<?php
$user = 'root';
$pass = '';
try {
    $connection = new PDO('mysql:host=localhost;dbname=netland', $user, $pass);
    foreach ($connection->query('select database(), version()') as $row) {
    }
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "
";
    die();
}

$array_id = $_GET["id"];

$movies = $connection->prepare("SELECT * FROM films WHERE id = ?");
$movies->execute([$array_id]);
$movies_array = $movies->fetch();

?>
<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Netland - Edit: Films</title>

            Terug

            <?= $movies_array['titel'] . " - Rating: " . $movies_array['duur']; ?>

        <form method="POST" autocomplete="off" action="<?php $_PHP_SELF ?>">

                        Titel

                        <input type="text" id="titel" name="titel" value="<?= $movies_array['titel'] ?>">

                        Duur

                        <input type="number" id="duur" name="duur" value="<?= $movies_array['duur'] ?>">

                        Datum van uitkomst

                        <input type="date" id="datum_van_uitkomst" name="datum_van_uitkomst" value="<?= $movies_array['datum_van_uitkomst'] ?>">

                        Land van uitkomst

                        <input type="text" id="land_van_uitkomst" name="land_van_uitkomst" value="<?= $movies_array['land_van_uitkomst'] ?>">

                        Omschrijving

                        <textarea id="omschrijving" name="omschrijving" rows="10" cols="40"
                        ><?= $movies_array['omschrijving'] ?></textarea>

                        YouTube trailer id

                        <input type="text" id="link" name="link" value="<?= $movies_array['link'] ?>">

                        <input type="submit" id="wijzig" name="wijzig" value="Wijzig">

        </form>
        <?php
            if (isset($_POST['wijzig'])) {
                $titel = $_POST['titel'];
                $duur = $_POST['duur'];
                $datum_van_uitkomst = $_POST['datum_van_uitkomst'];
                $land_uit_uitkomst = $_POST['land_van_uitkomst'];
                $omschrijving = $_POST['omschrijving'];
                $link = $_POST['link'];
                $stmt = $connection->prepare('UPDATE films SET title = ?, duur = ?, datum_van_uitkomst = ?, land_van_uitkomst = ?, omschrijving = ?, link = ? WHERE id = ?');
                $stmt->execute([$titel, $duur, $datum_van_uitkomst, $land_uit_uitkomst, $omschrijving, $link, $array_id]);
                $updated_array = $stmt->fetchAll();
            }
        ?>

Thank you for helping in advance.


text:
Q: Unit Test case in Grails with mocking the methods I was trying to write a unit test case for the action 'passwordActive' in 'LoginController'. But i am not sure which all things to be mocked and how to do that.
    def passwordActive={
        log.error("Entering into Password Active")
        println "Password Active -- Params =  "+params

        String contextPath = request.contextPath
        String username = null
        User user = null

    try{

            if (params.username != null && params.username.trim().length() > 0) {
            username = params.username
            user = User.findByUsername(username)
            }

            if (user == null) {
                log.error("USER not found.")
                flash.errorLogin = "Username is incorrect"
                redirect(action:"auth")
                return
             }else if(user.password != params.password){
                log.error("USER password is wrong..")
                flash.errorLogin = "Please enter valid password.."
                redirect(action:"auth")
                return
             }else if (!user.active) {
                log.error("USER is inactive.")
                flash.errorLogin = "User in Inactive"
                redirect(action:"auth")
                return
            }

            session["userid"] = user.id

            String userRole = user.authority.authority
            String url = contextPath + "/" + userRole
            println "URL = "+url
            redirect(url: url, method: 'post', params: params)
            return
       }
       catch(Exception e){
        println e.printStackTrace()
       }

    log.error("Exit into Password Active")

    }

i want to write a test case where username does not exist. in that case flash message should be having the message "username incorrect" and i can assert it.
Here what all things should be mocked and how to do that. Could you please explain the working with a small example (preferably related with above code so that it would be easy for me to understand)

A: Writing your own security implementation is a terribly bad idea. I suggest you take a look at how the Spring Security plugin does it for educational purposes, then just use that plugin - it is mature, flexible and easy to set up.
For said educational purposes, let's see how we could mock above code using an approach that is loosely along the lines of how Spring Security does it: You would move the user lookup into a service/bean as controllers aren't meant to contain any 'business' logic. Say something like this:
class UserProviderService {
    User findUser(String username) {
        User.findByUsername(username)
    }
}

In the controller you would injected it as a dependency (def userProviderService) on which you would then call your own function, e.g. userProviderService.findUser(username). During normal operation Grails would inject your UserProviderService into the controller while in unit tests you can mock it however you like (e.g. controller.userProviderService = [ findByUsername: { -> return null } ] if you for example wanted to test the controller response for an unknown user.
Similar for password comparison you would use a passwordService that would implement password hashing, comparison and so on and you could mock its response before every test. Note that this stuff is again not trivial if you care about security and very easy to mess up so again: don't do it yourself!
The way you structure your code determines how easy or hard it will be to test it. Sure you could mess with User.metaclass and override methods left and right, but that approach usually proves very fragile. By splitting up your code you can make your life easier! How to structure your code so it is testable is definitely something you learn by experience so keep thinking about it!


text:
Q: Does a game server create threads for each user request (like dota 2)? For a user base of 100,000 and 4 users per game session, should we create new threads for each request such as create_session, move_player, use_attack, etc. ?
I wanted to know what would be the optimal way to handle large connections because if we create large number of threads, context switching will eat up most of the cycles and if no threads are created each request has to wait for previous request to complete.

A: I would avoid thread-per-connection if your goal is scalability. It would be better to have a queue of events and a thread pool.
A game company would probably use a non-connection-based internet protocol like UDP. All requests can theoretically come in on the same socket, so you only need 1 thread to handle that. That thread can assign work to other threads.
You can have a larger threadpool where any thread can be assigned any job. Or you could further organize the work into specific jobs, each with a threadpool to process a queue of tasks. But I wouldn't launch a new thread for each request.
How you design your threadpools and task distribution system depends on the libraries for whatever language you're using and the application requirements.


text:
Q: How should I write tests for Forms in Django? I'd like to simulate requests to my views in Django when I'm writing tests. This is mainly to test the forms. Here's a snippet of a simple test request:
from django.tests import TestCase

class MyTests(TestCase):
    def test_forms(self):
        response = self.client.post("/my/form/", {'something':'something'})
        self.assertEqual(response.status_code, 200) # we get our page back with an error

The page always returns a response of 200 whether there's an form error or not. How can I check that my Form failed and that the particular field (soemthing) had an error?

A: https://docs.djangoproject.com/en/stable/topics/testing/tools/#django.test.SimpleTestCase.assertFormError
from django.tests import TestCase

class MyTests(TestCase):
    def test_forms(self):
        response = self.client.post("/my/form/", {'something':'something'})
        self.assertFormError(response, 'form', 'something', 'This field is required.')

Where "form" is the context variable name for your form, "something" is the field name, and "This field is required." is the exact text of the expected validation error.

A: I think if you just want to test the form, then you should just test the form and not the view where the form is rendered. Example to get an idea:
from django.test import TestCase
from myapp.forms import MyForm

class MyTests(TestCase):
    def test_forms(self):
        form_data = {'something': 'something'}
        form = MyForm(data=form_data)
        self.assertTrue(form.is_valid())
        ... # other tests relating forms, for example checking the form data

A: The original 2011 answer was
self.assertContains(response, "Invalid message here", 1, 200)

But I see now (2018) there is a whole crowd of applicable asserts available:

*

*assertRaisesMessage

*assertFieldOutput

*assertFormError

*assertFormsetError

Take your pick.


text:
Q: anyone know what changes if any were made to asp.net wizard control in framework 3.5? HI,
i would like to know what differences if any there is between the .net framework 3.5 asp.net control compared to the .net 2.0 framework version

A: None whatsoever.
ASP.Net 3.5 does not introduce any changes to System.Web.dll.
The only changes in ASP.Net 3.5 are in the new System.Web.Extensions.dll.

A: Can't improve on SLaks, but if you want to see everything that was new in .Net 3.5 ...


text:
Q: Convert string to Multiline in VB.net I want to fit a text to a specific screen size. The text is editable - change text, change font size, font color, font family.
For Example:

"For God loved the world so much that he gave his only-begotten Son, so that everyone exercising faith in him might not be destroyed but have everlasting life. For God loved the world so much that he gave his only-begotten Son, so that everyone exercising faith in him might not be destroyed but have everlasting life."

is a string which is very long and it's single line.
I want it to be put in a label like this.

"For God loved the world so much that
  he gave his only-begotten Son, so that
  everyone exercising faith in him might
  not be destroyed but have everlasting
  life. For God loved the world so much
  that he gave his only-begotten Son, so
  that everyone exercising faith in him
  might not be destroyed but have everlasting life."

VB.Net. Any Suggestion?

A: Try this code :
label3.MaximumSize = New Size(100, 0)
label3.AutoSize = True


text:
Q: $\int \frac{1}{y-1} dy = \ln |y - 1|$? I read the following in a book on differential equations
$$\int \frac{1}{y-1} dy = \log |y - 1|$$
If I put $\int \frac{1}{y-1} dy$ into Wolfram Alpha it gives $\log (y - 1)$, i.e. the argument of the function is not an absolute value unlike the first equation. So which is correct and why am I seeing conflicting results for the same integral?

A: That happens because $\log (y - 1)$ only exists in $(1, +\infty)$, hence its derivative would be $1/(y - 1)$, but with considering only values of $y$ that are greater than $1$.
This is of course different from what you are trying to integrate, because that $1/(y - 1)$ inside the integral is a function that is defined everywhere in $\mathbb{R}$ (with the sole exception of $1$). Then its indefinite integral is $\log |y - 1|$ because not only its derivative is $1/(y - 1)$, but its domain is also exactly $\mathbb{R} - \{1\}$, that is the same of the function you're trying to integrate.
This happens because functions with different domains are different functions even if their written expression is the same, so $1/(y - 1)$ may yield different results when integrating, according to what its domain is.


text:
Q: How to log in to an Ubuntu VPS with public-key through vnc? I have a VPS with a ssh key pair set on it and password authentication disabled.
Today I accidentally lost my ssh access to my VPS. I was trying to change the default ssh port to port 1025. I added a bad line to the sshd_config file and failed the syntax. Instead of Port 1025 I entered Port1025 without the space in between. I immediately lost my ssh access right after restarting ssh service.
Then consulting my VPS provider they suggested to use vnc access to the server and correct the mistake.
Now the question is here when I try vnc I'm taken to a tty terminal that asks me for login credentials. But I already have disabled password authentication. Is there any way to use public-key authentication at this stage? Does this mean I have permanently lost access to my data?
Please help if you know of a solution.


text:
Q: How to colour \hrule I am trying to display a coloured \hrule.
This discussion implies wrapping the \hrule in a \textcolor should do, but that adds an ugly extra vertical space above the \hrule.
Other questions on TeX.SE, such as this, or this, deal with coloring \rule rather than \hrule, but \rule already produces that extra vertical space even without \textcolor.
MWE with the original \hrule and two unsuccessful attempts to colour it:
\documentclass{article}

\setlength{\parindent}{0cm}

\usepackage{xcolor}

\begin{document}

abc%
\vskip 1mm%
\hrule

abc%
\vskip 1mm%
\textcolor{red}{\hrule}

abc%
\vskip 1mm%
\rule{\textwidth}{.1mm}

\end{document}

This produces:

I know I could probably use the hack of inserting a negative \vskip to remove a \baselineskip offset, but I am looking for a clean way of colouring a \hrule that does not involve such a workaround.

A: Try {\color{red}\hrule} -- you need the {...} around \color etc. to prevent the color leaking into other parts of the document.
\documentclass{article}

\setlength{\parindent}{0cm}

\usepackage{xcolor}

\begin{document}

abc%
\vskip 1mm%
\hrule

abc%
\vskip 1mm%
{\color{red}\hrule}
%\textcolor{red}{\hrule}

abc%
\vskip 1mm%
\rule{\textwidth}{.1mm}

\end{document}

Edit Here's some improvement
\documentclass{article}

\setlength{\parindent}{0cm}

\usepackage{pgffor}
\usepackage{xparse}
\usepackage[x11names]{xcolor}

\NewDocumentCommand{\colorrule}{O{.4pt}m}{%
  {\color{#2}\hrule height#1}%
}

\begin{document}

abc%
\vskip 1mm%
\hrule

% Now a blue rule
\colorrule{blue}
abc%
\vskip 1mm%
\foreach \x in {Red4,Red3,Red2,Red1,orange,yellow,LightBlue1,LightBlue2,LightBlue3,LightBlue4,blue,green,brown} {%
\colorrule[2pt]{\x}
}

abc%
\vskip 1mm%
\rule{\textwidth}{.1mm}

\end{document}


text:
Q: Conserved quantity from a conserved current In my QFT course, it was asserted that the conserved quantity associated with some conserved current is given by $Q = \int_v j^0d^3x$ where $j^0$ is the time component of the conserved current, and $d^3x$ is over the three spatial coordinates. My professor "left it as an exercise to the reader" to come up with an explanation for this, but I'm having trouble figuring out where this comes from.
My very hacky way of thinking about it currently is if you say $j^\mu = (j^0,J)$, where $j^0$ is the time component and $J$ comprises the spatial components. If you expand out $\partial_\mu j^\mu = 0$, you get $\partial_tj^0 -\nabla\cdot  J = 0 $. And if you integrate with respect to both time and space, you get
$$\int d^3x j^0 = \int d^3x dt( \nabla\cdot J)$$
Where the RHS is the conserved quantity, and the LHS is the form we want it in. I understand the RHS has form where you can use the divergence theorem, but I wouldn't then be sure where to take it. And I'm not even sure if this approach is right. Why would we say the RHS is a conserved quantity?
Can someone provide a bit of help on this one? Sorry if my notation isn't standard, I am still learning the lingo.
Update
Ok, so I see how one might be able to interpret the RHS, $\int d^3x dt( \nabla\cdot J)$ as a conserved quantity. By definition, if you take the time derivative, it must equal zero. So, let's see.
$$\frac{d}{dt}\int d^3x dt( \nabla\cdot J) = \int d^3x( \nabla\cdot J)$$
and then using the divergence theorem
$$\int d^3x( \nabla\cdot J) = \int_S(J\cdot \vec{n})dS = 0?$$
Should the spatial components of the conserved current vanish at the boundary? If not, I am unsure why this should be zero.

A: We mame use of
$$\partial_\mu \mathcal j^\mu=0 $$
$$\int d^3x (\partial_0\mathcal j^0 +\nabla\cdot \bf J)=0$$
for big enough volume the divergence term vanishes (by the divergence theorom $\int d^3x \nabla \cdot \bf J=\int \bf J \cdot \bf \hat n dA $ and the boundaries at infinity vanishes)
giving you
$$\frac{d}{dt}\int d^3x \mathcal j^0=0$$
Note that we make the boundaries at infinity vanish all the time.
Assumption of vanishing boundaries at large enough boundaries generally don't matter as we observe the vicinity of fields is quite small. The irony is we ignore them in General Relativity too, even though vicinity of gravitational fields are quite large but at a far enough distance flat spacetime will be observed.


text:
Q: WCF: Exception handling on OneWay OperationContract I am having a WCF duplex service with Silverlight client and .NET 3.5 WCF service.
The scenario I have is: during the duplex push OneWay operation from server to client if an exception happens in client notification handler the channel gets silently faulted so any further duplex calls from server timeout and fail. (As explained here One-Way Operations and Exceptions)
My question(s):

*

*Can I just decorate with FaultContract a OneWay OperationContract, wrap the exception on client and prevent faulting of the channel?

*if not, what would be some other way to catch the exception which occurred on the client during the duplex push from server?

A: When you use OneWay OperationContract, the receiver should not reply nor the sender of the request should expect one.

*

*You can't.

*Your best bet is you can create another OneWay OperationContract between client and the service so that the service can send the fault to the client.


text:
Q: Multivariate distribution I fit a multivariate distribution in R with below data. I need help in understanding the output.
      library(mvtnorm)
      h2
           a        b       c        d        e
      0.3837  1.11516  1.9256 -0.50875  1.88859
      0.8426 -0.84579 -0.7873  0.02639  0.33517
      0.1542 -0.09256 -0.1094 -1.38610  0.54481
     -1.6815  3.56519  3.1228  1.48618  1.53065
     -0.5342  0.71441  0.6989 -1.55011 -0.41603
      1.0721  4.52062  3.8051 -0.16023 -0.01286
     -0.3047  1.27455  0.7179  0.27030 -0.34911
      2.9078  1.61245  1.2929  0.21195  1.32390
     -0.3047 -0.51061 -0.4536  1.54295  1.08431
     -0.7636  0.96761  1.2947  0.73289 -0.59614

      mu = colMeans(h2)
      C1 = cov(h2)

    # Below function will compute probability for each row
      F2 = function(b)
      {
         pmvnorm(lower=-Inf, upper=b, mean=mu, sigma=C1)
      }
     # Below function will compute density for each row
      F3 = function(b)
      {
        dmvnorm(x=b, mean=mu, sigma=C1, log=FALSE)
      }

      proba=apply(h2,1, F2)
      dens = apply(h2,1, F3)
      cbind(h2,proba,dens)

          a        b       c        d        e    proba      dens
      0.3837  1.11516  1.9256 -0.50875  1.88859 0.072544 0.0007242
      0.8426 -0.84579 -0.7873  0.02639  0.33517 0.019907 0.0065792
      0.1542 -0.09256 -0.1094 -1.38610  0.54481 0.005645 0.0031873
     -1.6815  3.56519  3.1228  1.48618  1.53065 0.047796 0.0006827
     -0.5342  0.71441  0.6989 -1.55011 -0.41603 0.001885 0.0030992
      1.0721  4.52062  3.8051 -0.16023 -0.01286 0.112288 0.0013975
     -0.3047  1.27455  0.7179  0.27030 -0.34911 0.022331 0.0062871
      2.9078  1.61245  1.2929  0.21195  1.32390 0.271875 0.0012214
     -0.3047 -0.51061 -0.4536  1.54295  1.08431 0.032490 0.0026146
      -0.7636  0.96761  1.2947  0.73289 -0.59614 0.013268 0.0007913

My question, why the values of probability and density are very low for each row.
My interpretation is that, each of the rows does not belong to a multivariate normal distribution with mu and C1. Is that correct?

A: The values of cumulative probability and density are as low as they are due to the effects of being in 5 dimensions.  Your expectation as to what is reasonable is perhaps based to a large extent on 1 dimensional normal.
I checked the results for probability and density using MATLAB, and got exact agreement, so I think your results are correct.
I will show you just the cumulative probability results using only some of the columns, and you can start to get a feel.  These correspond to your proba output column, but only using some of the columns of input data.  I am not showing you every possibility.
Just the 1st column (1D):
   0.565637288338181
   0.702816002597073
   0.492667067696748
   0.068452074479719
   0.284582761085686
   0.763058850958907
   0.349888595566043
   0.985563411940202
   0.349888595566043
   0.225766862907170

Just the 2nd column (1D):
   0.472501841180498
   0.110154392554774
   0.217285938950877
   0.915626527024584
   0.380039621684968
   0.973799841208276
   0.509987926467789
   0.588761043921356
   0.151976916659519
   0.438008974406623

Just the 1st and 2nd columns (2D):
   0.264841990150589
   0.076405351627506
   0.105236178888105
   0.062355658370148
   0.106157429165297
   0.742779509346500
   0.176154283011264
   0.580041734712487
   0.051831899178908
   0.097057907212853

Just the 1st, 2nd, and 3rd columns (3D):
   0.264617423149077
   0.057300913569709
   0.083949731409476
   0.060366682143580
   0.093198795122322
   0.731508503440227
   0.126580702128226
   0.510771711413619
   0.040244089729650
   0.094487914775201

Just the 1st, 2nd, 3rd, and 4th columns (4D):
   0.073559770009587
   0.031623966714283
   0.006727668874189
   0.050106397108077
   0.003951924232790
   0.277948705795869
   0.067743297644953
   0.306330906498960
   0.037353799984810
   0.064902776076491

You can of course look at other combinations of the columns.
Going back to the original problem in 5D, I calculated the Mahalanobis Distances of the input data points relative to the fitted mean and covariance, and converted these to the corresponding probability levels from the Chisquare distribution which they would follow if truly multivariate normal with that mean and covariance.  The match is not great, although the data set is small. If these were sorted and the sample large enough, and the match were good, then it should be close to a straight line.  This is essentially getting at the distribution of points ellipsoidally about the mean relative to the fitted covariance - that has taken the effect of number of dimensions out of the picture, and is perhaps what you really (should) care about.
    0.7359
    0.1573
    0.3759
    0.7460
    0.3844
    0.6015
    0.1701
    0.6325
    0.4349
    0.7203

Full disclosure: I didn't do these Mahalanobis Distance calculations very carefully, so could have made a mistake.

A: Any real number is within support of normal distribution, this applies also to multivariate normal distribution. So any real number "belongs" to multivariate normal with any parameters, some values are just observed with smaller probabilities.
The probabilities that you see are low because this is a multivariate distribution. Try to visualize yourself univariate and bivariate normal distributions. In the first case you observe probabilities of points on $x$-axis, while in the second case probabilities of points in two dimensional space. Obviously multivariate distribution relates to greater total space, so individual probabilities for each point (or interval) are proportionally smaller than in univariate case. Imagine that you are interested in marginal distribution of one of the variables in bivariate normal distribution, to obtain it you would sum up (take integral) all the points from one of the dimensions,
$$ P(X = x) = \sum_y P(X = x, Y = y) $$
so from this alone you can imagine that the individual probabilities in bivariate case were smaller than in univariate case.
You can frame your question differently and ask if your sample fits the 95% (or other) highest density interval, i.e. if they fall below some predefined threshold. You can be also interested how likely they are under such model and if another model does fit your data better. Those however are different questions that need different approach than looking at the raw probabilities alone.


text:
Q: How can I set __m128i without using of any SSE instruction? I have many function which use the same constant __m128i values.
For example:
const __m128i K8 = _mm_setr_epi8(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
const __m128i K16 = _mm_setr_epi16(1, 2, 3, 4, 5, 6, 7, 8);
const __m128i K32 = _mm_setr_epi32(1, 2, 3, 4);

So I want to store all these constants in an one place.
But there is a problem: I perform checking of existed CPU extension in run time.
If the CPU doesn't support for example SSE (or AVX) than will be a program crash during constants initialization.
So is it possible to initialize these constants without using of SSE?

A: Initialization of __m128i vector without using SSE instructions is possible but it depends on how to compiler defines __m128i.
For Microsoft Visual Studio you can define next macros (it defines __m128i as char[16]):
template <class T> inline char GetChar(T value, size_t index)
{
    return ((char*)&value)[index];
}

#define AS_CHAR(a) char(a)

#define AS_2CHARS(a) \
    GetChar(int16_t(a), 0), GetChar(int16_t(a), 1)

#define AS_4CHARS(a) \
    GetChar(int32_t(a), 0), GetChar(int32_t(a), 1), \
    GetChar(int32_t(a), 2), GetChar(int32_t(a), 3)

#define _MM_SETR_EPI8(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa, ab, ac, ad, ae, af) \
    {AS_CHAR(a0), AS_CHAR(a1), AS_CHAR(a2), AS_CHAR(a3), \
     AS_CHAR(a4), AS_CHAR(a5), AS_CHAR(a6), AS_CHAR(a7), \
     AS_CHAR(a8), AS_CHAR(a9), AS_CHAR(aa), AS_CHAR(ab), \
     AS_CHAR(ac), AS_CHAR(ad), AS_CHAR(ae), AS_CHAR(af)}

#define _MM_SETR_EPI16(a0, a1, a2, a3, a4, a5, a6, a7) \
    {AS_2CHARS(a0), AS_2CHARS(a1), AS_2CHARS(a2), AS_2CHARS(a3), \
     AS_2CHARS(a4), AS_2CHARS(a5), AS_2CHARS(a6), AS_2CHARS(a7)}

#define _MM_SETR_EPI32(a0, a1, a2, a3) \
    {AS_4CHARS(a0), AS_4CHARS(a1), AS_4CHARS(a2), AS_4CHARS(a3)}

For GCC it will be (it defines __m128i as long long[2]):
#define CHAR_AS_LONGLONG(a) (((long long)a) & 0xFF)

#define SHORT_AS_LONGLONG(a) (((long long)a) & 0xFFFF)

#define INT_AS_LONGLONG(a) (((long long)a) & 0xFFFFFFFF)

#define LL_SETR_EPI8(a, b, c, d, e, f, g, h) \
    CHAR_AS_LONGLONG(a) | (CHAR_AS_LONGLONG(b) << 8) | \
    (CHAR_AS_LONGLONG(c) << 16) | (CHAR_AS_LONGLONG(d) << 24) | \
    (CHAR_AS_LONGLONG(e) << 32) | (CHAR_AS_LONGLONG(f) << 40) | \
    (CHAR_AS_LONGLONG(g) << 48) | (CHAR_AS_LONGLONG(h) << 56)

#define LL_SETR_EPI16(a, b, c, d) \
    SHORT_AS_LONGLONG(a) | (SHORT_AS_LONGLONG(b) << 16) | \
    (SHORT_AS_LONGLONG(c) << 32) | (SHORT_AS_LONGLONG(d) << 48)

#define LL_SETR_EPI32(a, b) \
    INT_AS_LONGLONG(a) | (INT_AS_LONGLONG(b) << 32)

#define _MM_SETR_EPI8(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa, ab, ac, ad, ae, af) \
    {LL_SETR_EPI8(a0, a1, a2, a3, a4, a5, a6, a7), LL_SETR_EPI8(a8, a9, aa, ab, ac, ad, ae, af)}

#define _MM_SETR_EPI16(a0, a1, a2, a3, a4, a5, a6, a7) \
    {LL_SETR_EPI16(a0, a1, a2, a3), LL_SETR_EPI16(a4, a5, a6, a7)}

#define _MM_SETR_EPI32(a0, a1, a2, a3) \
    {LL_SETR_EPI32(a0, a1), LL_SETR_EPI32(a2, a3)}

So in your code initialization of __m128i constant will be look like:
const __m128i K8 = _MM_SETR_EPI8(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
const __m128i K16 = _MM_SETR_EPI16(1, 2, 3, 4, 5, 6, 7, 8);
const __m128i K32 = _MM_SETR_EPI32(1, 2, 3, 4);

A: I suggest defining the initialisation data globally as scalar data and then load it locally into a const __m128i:
static const uint8_t gK8[16] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };

static inline foo()
{
    const __m128i K8 = _mm_loadu_si128((__m128i *)gK8);

    // ...
}

A: You can use a union.
union M128 {
   char[16] i8;
   __m128i i128;
};

const M128 k8 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };

If the M128 union is defined locally where you use the loop, this should have no performance overhead (it will be loaded in memory once at the begin of the loop). Because it contains a variable of type __m128i, M128 inherits the correct alignment.
void foo()
{
   M128 k8 = ...;
   // use k8.i128 in your for loop
}

If it is defined somewhere else, then you need to copy into a local register before you start the loop, otherwise the compiler may not be able to optimize it.
void foo()
{
    __m128i tmp = k8.i128;
    // for loop here
}

This will load k8 into a cpu register and keep it there for the duration of the loop, as long as there enough free registers to carry out the loop body.
Depending on what compiler you use, these unions may be already defined (VS does), but the compiler's provided definitions may not be portable.

A: You usually don't need this.  Compilers are very good at using the same storage for multiple functions that use the same constant.  Just like merging multiple instances of the same string literal into one string constant, multiple instances of the same _mm_set* in different functions will all load from the same vector constant (or generate on the fly for _mm_setzero_si128() or _mm_set1_epi8(-1)).
Using Godbolt's binary output (disassembly) mode lets you see whether different functions are loading from the same block of memory or not.  Look at the comment it adds, which resolves the RIP-relative addresses to absolute addresses.

*

*gcc: all identical constants share the same storage, regardless of whether they're from auto-vectorization or _mm_set.  32B constants can't overlap with 16B constants, even if the 16B constant is a subset of the 32B.

*clang: identical constants share storage.  16B and 32B constants don't overlap, even when one is a subset of the other.  Some functions using repetitive constants use an AVX2 vpbroadcastd broadcast-load (which doesn't even take an ALU uop on Intel SnB-family CPUs).  For some reason, it chooses to do this based on the element size of the operation, not the repetitivity of the constant.  Note that clang's asm output repeats the constant for each use, but the final binary doesn't.

*MSVC: identical constants share storage.  Pretty much the same as what gcc does.  (The full asm output is hard to wade through; use search.  I could only get the asm at all by having main find the path to the .exe, then work out the path to the asm output made with cl.exe -O2 /FAs, and run system("type .../foo.asm")).
Compiler are good at this, since it's not a new problem.  It's existed with strings since the earliest days of compilers.
I haven't checked if this works across source files (e.g. for an inline vector function used in multiple compilation units).  If you do still want static / global vector constants, see below:

It appears there is no easy and portable way to statically initialize an static/global __m128.  C compilers won't even accept _mm_set* as an initializer, because it works like a function.  They don't take advantage of the fact that they could actually see through it to a compile-time-constant 16B
const __m128i K32 = _mm_setr_epi32(1, 2, 3, 4);   // Illegal in C
// C++: generates a constructor that copies from .rodata to the BSS

Even though the constructor only requires SSE1 or SSE2, you don't want this anyway.  It's horrible.  DON'T DO THIS.  You end up paying the memory cost of your constants twice.

Fabio's union answer looks like the best portable way to statically initialize a vector constant, but it means you have to access the __m128i union member.  It may help with grouping related constants near each other (hopefully in the same cache line) even if they're used by scattered functions.  There are non-portable ways to accomplish, that, too (e.g. put related constants in their own ELF section with GNU C __attribute__ ((section ("constants_for_task_A")))).  Hopefully that can group them together in the .rodata section (which becomes part of the .text section).


text:
Q: Using React's useEffect, how can I cycle through images for 2 seconds each? I've tried using setInterval but it cycles way to quick.
Banner images array:
const banner = [Banner, Banner2]

React Hooks:
const [ currBanner, setCurrBanner ] = useState(0)

useEffect:
useEffect(() => {
    if( currBanner > 0 ) {
        setInterval(setCurrBanner(currBanner - 1), 2000)
    } else {
        setInterval(setCurrBanner(currBanner + 1), 2000)
    }
}, [currBanner])

Image component:
<img className={classes.banner} src={banner[currBanner]} alt="new menu" />


text:
Q: AWS glue interactive session in sagemaker notebooks via lifecycle configurations I am trying to work with glue interective session in sagemaker notebook by configuring the glue-conda-pyspark kernel via aws lifecycle configurations. It worked earlier while creating a notebook instance. Now the instance is running with configuration but i am no longer able to see the conda glue pyspark kernel in the kernel list. Could anybody help with the create script and start script to run the notebook with glue-pyspark.
I am configuring using this aws doc: https://docs.aws.amazon.com/glue/latest/dg/interactive-sessions-sagemaker.html#is-sagemaker-existing
and also aws took help from aws github scripts: https://github.com/aws-samples/amazon-sagemaker-notebook-instance-lifecycle-config-samples/blob/master/scripts/install-conda-package-single-environment/on-start.sh


text:
Q: How to manipulate select lists with Google Apps Script? I have a spreadsheet file with some sidebars to enter data and do some other things.
In a sidebar, I have a form to enter data, and along with the data there's 3 select lists to define the position of a Metallic Unit in a warehouse.
The position consists of 3 informations: level, letter and number.
Level can be N1, N2 or N3, letter can be A1, A2, B1, B2 until M2, and number can be 1 to 66.
Visually speaking it's like this:

<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">

Position:

<select>
  <option selected disabled>Level</option>
  <option>N1</option>
  <option>N2</option>
  <option>N3</option>
</select>
<select>
  <option selected disabled>Letter</option>
  <option>A1</option>
  <option>A2</option>
  <option>B1</option>
  <option>B2</option>
  <option>C1</option>
  <option>C2</option>
  <option>...</option>
</select>
<select>
  <option selected disabled>Number</option>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
  <option>6</option>
  <option>...</option>
</select>

The problem is, each level has some own details, like:

*

*For level N1, all letters and numbers exist.

*For level N2, all letters exist but numbers are only 33 to 66.

*For level N3, only F1, F2, G1 and G2 letters and 44 to 50 numbers exist.

So, the ideal form would change the content of the latter 2 selects based in the first option I select.
The problem is, GAS is limited to manipulate these elements, and I can't find a way that really works, because the content should change dynamically depending on the Level selected option.

A: You can use jQuery/javascript and DOM properties and methods to change the HTML in the select fields.  GAS is not limited.  There is very little that you can not do.
You need to use the onchange() event to populate the other select fields when the previous one has been selected:

<select id="idLevels" onchange="fncPopulateLetterSelect()">
  <option selected disabled>Level</option>
  <option>N1</option>
  <option>N2</option>
</select>

<select id="idLtrOptions">
  <option selected disabled>Letter</option>
  <option>A1</option>
  <option>A2</option>
  <option>B1</option>
  <option>...</option>
</select>

innerHTML
To get the third select box choices to change based on the second select box, simply use the same code structure, but different HTML element ID's and of course, different settings in the object array.


text:
Q: Magento 1.7 - Remove fields from registration in /customer/account/create/ I want to remove fields from Registration (/customer/account/create/). How can I do this?
is there some way without get into files of the store (e.g. hiding these fields)?

A: You should update some fields in the DB.
For example. I need to remove last name from registration form. It's a requried field.
So I created own module with sql update file to change field parameters:
upgrade-1.0.0.1-1.0.0.2.php
/* @var $installer Mage_Customer_Model_Entity_Setup */

$installer = $this;

$installer->startSetup();
// SELECT attribute_id, entity_type_id FROM eav_attribute where attribute_code = 'lastname'
// SELECT * FROM customer_eav_attribute where attribute_id in (SELECT attribute_id FROM eav_attribute where attribute_code = 'lastname')
$options = unserialize('a:2:{s:15:"max_text_length";i:255;s:15:"min_text_length";i:1;}');

if (isset($options['min_text_length'])) unset($options['min_text_length']);

$installer->addAttribute('customer', 'lastname', array(
    'validate_rules' => serialize($options),
    'required'       => false
));

$installer->addAttribute('customer_address', 'lastname', array(
    'validate_rules' => serialize($options),
    'required'       => false
));

$installer->endSetup();

After that you should hide this field using html+css or js
UPDATE:
Edit file /app/design/frontend/default/YOURTHEME/template/customer/widget/name.phtml to change your registration form. In my case I commented out html block there:
<?php /*if ($this->showMiddlename()): ?>
        <?php $isMiddlenameRequired = $this->isMiddlenameRequired(); ?>

            <label for="<?php echo $this->getFieldId('middlename')?>"<?php echo $isMiddlenameRequired ? ' class="required"' : '' ?>><?php echo $isMiddlenameRequired ? '*' : '' ?><?php echo $this->getStoreLabel('middlename') ?>

                <input type="text" id="<?php echo $this->getFieldId('middlename')?>" name="<?php echo $this->getFieldName('middlename')?>" value="<?php echo $this->escapeHtml($this->getObject()->getMiddlename()) ?>" title="<?php echo $this->getStoreLabel('middlename') ?>" class="input-text <?php echo $this->helper('customer/address')->getAttributeValidationClass('middlename') ?>" <?php echo $this->getFieldParams() ?> />

    <?php endif; */?>

Also you could add some class to
 and
. This class should has css property "display:none;".

A: Somehow I got it to work. This is want I did and I request you to try it and check if it solves the issue.

*

*Open Magento DB and go to the table core_config_data.

*Search for the path - customer/address/middlename_show.

*Edit Value field for customer/address/middlename_show and change it to 1 . Generally, this will be 0 (zero) by default.

*Save the table.

*Clear Cache. Preferably delete the folder Cache and Session present in var folder.

*Login to Magento admin and go to the following location:
System --> Configuration --> CUSTOMERS --> Customer Configuration

*Under "Name and Address Options" tab, now the option for "Show Middle Name (initial)" will be shown as "Yes".

*Change it to "No".

*Save Config and clear Cache.


text:
Q: Svelte - Help to parse data from API - object json I am having issues displaying the data I am fetching from an API.
Sample json data:
{
"records": [
    {
        "event": {
            "type": "navigate"
        },
        "setup": {
            "attributes": {
                "title": "New Tab"
            },
            "description": "",
            "name": "",
            "type": null,
            "url": "chrome://newtab/"
        },
        "time": 1612271431271
    },
    {
        "event": {
            "type": "navigate"
        },
        "setup": {
            "url": "https://3.basecamp.com/signup/account/new?plan=one_v1"
        },
        "time": 1612271438035
    },
    {
        "event": {
            "type": "focus"
        },
        "setup": {
            "altPath": "article/form/section[1]/div[1]/input[@id='signup_full_name'][@name='signup[full_name]'][@type='text']",
            "altSelector": "article #signup_full_name",
            "attributes": {
                "autofocus": "autofocus",
                "class": "input session-fields__signup floating-placeholder__input",
                "id": "signup_full_name",
                "name": "signup[full_name]",
                "placeholder": "Your name",
                "rcrdr-extra-style": {
                    "display": "block",
                    "visibility": "visible"
                },
                "required": "required",
                "type": "text"
            },
            "computedRole": "textbox",
            "frame": "0",
            "frame_id": "0",
            "html": "<input class=\"input session-fields__signup floating-placeholder__input\" placeholder=\"Your name\" required=\"required\" autofocus=\"autofocus\" type=\"text\" name=\"signup[full_name]\" id=\"signup_full_name\">",
            "nodeName": "input",
            "nodeType": 1,
            "rootpath": "/html/body/main/div/section/article/form/section[1]/div[1]/input",
            "selector": "#signup_full_name",
            "xpath": "id(\"signup_full_name\")"
        },
        "time": 1612271489789
    }
]

}
My goal is to display each key in a table, for example, the output should look like this:
table
What I have tried so far was:

    {#each [records] as record}

        {record}

    {/each}

The output I get is something like this:

{"records":[{"event":{"type":"navigate"},"setup":{"attributes":{"title":"New Tab"},"description":"","name":"","type":null,"url":"chrome://newtab/"},"time":1612271431271},{"event":{"type":"navigate"},"setup":{"url":"https://3.basecamp.com/signup/account/new?plan=one_v1"},"time":1612271438035},{"event":{"type":"focus"},"setup":{"altPath":"article/form/section[1]/div[1]/input[@id='signup_full_name'][@name='signup[full_name]'][@type='text']","altSelector":"article #signup_full_name","attributes":{"autofocus":"autofocus","class":"input session-fields__signup floating-placeholder__input","id":"signup_full_name","name":"signup[full_name]","placeholder":"Your name","rcrdr-extra-style":{"display":"block","visibility":"visible"},"required":"required","type":"text"},"computedRole":"textbox","frame":"0","frame_id":"0","html":"<input class=\"input session-fields__signup floating-placeholder__input\" placeholder=\"Your name\" required=\"required\" autofocus=\"autofocus\" type=\"text\" name=\"signup[full_name]\" id=\"signup_full_name\">","nodeName":"input","nodeType":1,"rootpath":"/html/body/main/div/section/article/form/section[1]/div[1]/input","selector":"#signup_full_name","xpath":"id(\"signup_full_name\")"},"time":1612271489789},{"event":{"type":"focus"},"setup":{"altPath":"article/form/section[1]/div[1]/input[@id='signup_full_name'][@name='signup[full_name]'][@type='text']","altSelector":"article #signup_full_name","attributes":{"autofocus":"autofocus","class":"input session-fields__signup floating-placeholder__input","data-sc-fieldtype":"FULL_NAME","data-sc-fieldtype-id":"160","id":"signup_full_name","name":"signup[full_name]","placeholder":"Your name","rcrdr-extra-style":{"display":"block","visibility":"visible"},"required":"required","type":"text"},"computedRole":"textbox","frame":"0","frame_id":"0","html":"<input class=\"input session-fields__signup floating-placeholder__input\" placeholder=\"Your name\" required=\"required\" autofocus=\"autofocus\" type=\"text\" name=\"signup[full_name]\" id=\"signup_full_name\" data-sc-fieldtype=\"FULL_NAME\" data-sc-fieldtype-id=\"160\">","nodeName":"input","nodeType":1,"rootpath":"/html/body/main/div/section/article/form/section[1]/div[1]/input","selector":"#signup_full_name","xpath":"id(\"signup_full_name\")"},"time":1612271498250}

Please, is anyone able to help me to display the output in a table using svelte?
Thank you.
Edit:
I have changed my code:

<button on:click={handleClick} {disabled}> Load Data </button>

{#await promise}

retrieving data...

{:then results}

    {#each [{ results }] as record}
      {record}
    {/each}

{:catch error}

{error.message}

{/await}

Now the output is simply:

*

*[object Object]

Please, do you know why I get this output?
Thanks

A: I am going to point out a few things that should help out, and I highly recommend reading the following:

*

*Svelte each blocks

*Svelte await blocks
records is a string but should be an array
Your variable called records is a single string; we can see this on the line stating records = JSON.stringify(recordsObject);.
Because it is a string and not an array, you are converting it into an array of one item in your each block using {#each [records] as record}. Syntactically that works, but that's almost certainly not what you want. What you actually want is for the records variable to equal the array inside of the json response.
records = recordsObject.records

If you are wondering why that works, then I highly recommend reading further on working with javascript objects.
Tables are not automatic
Each record is a javascript object, essentially a bundle of key-value pairs. Svelte does not automatically convert an object into a table because it does not, and cannot, know how. That's up to you to format using HTML.
So, when you have this in your code:

  {record}

That's just gonna spit out the raw object. You have to format it into a table yourself. The link on Svelte each blocks I provided earlier gives a small example of how to get started on that task.
For your specific case, the following is a start on how you can decompose a record into its different parts.

  Type: {record.event.type}; Time: {record.time}


text:
Q: Issue with File Download HTTP Headers in IE, when passed through nginx reverse proxy Setup:
IIS7 serving ASP classic VB script code which generates a dynamic VSC page/file with headers to download.
Response.ContentType = "text/x-vCalendar"
Response.Expires = -1
Response.Buffer = True
Response.Clear
Response.AddHeader "Content-Disposition", "filename=" & strFileName & ".vcs;"
Response.Write strFileContent

Our IIS7 serrvers are behind a nginx reverse proxy.  Everything is working fine, except this file download.
Problem:
When using IE and going in through the reverse proxy (load balancer) the file is not downloading as a .vcs but wanting to download the .asp file/page.
When using other browsers through the reverse proxy (load balancer) it works fine.
When using IE and bypassing the reverse proxy (load balancer), going straight to the IIS server, it works fine.
Assumption:
Sounds like it's a HTTP header issue.  The only differences I could find in the responses were the additional response headers of:
Connection: keep-alive
Vary: Accept-Encoding

Header Responses:
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 1431
Content-Type: text/x-vCalendar
Expires: Fri, 09 Jul 2010 13:26:38 GMT
Server: Microsoft-IIS/7.5
Content-Disposition: filename=2507541_16268.vcs;
X-Powered-By: ASP.NET
backend: iis1
Date: Fri, 09 Jul 2010 13:27:37 GMT

HTTP/1.1 200 OK
Connection: keep-alive
Vary: Accept-Encoding
Cache-Control: private
Content-Length: 1431
Content-Type: text/x-vCalendar
Expires: Fri, 09 Jul 2010 13:26:19 GMT
Server: nginx
Content-Disposition: filename=2507541_16268.vcs;
X-Powered-By: ASP.NET
backend: iis1
Date: Fri, 09 Jul 2010 13:27:15 GMT

Request
Is there any light anyone can shed on the issue?
nginx settings to change, or ASP code to add?

A: So I finally figured this out, thought I'd post it for anyone else who needed the assist.
I commented out the gzip_vary line, from my nginx.conf file - that seemed to fix things but I chose not to set the setting to "off" because I didn't want to forcefully remove the Vary header from other browsers where things were working... commenting out worked.
# commenting this out seemed to work, but I could have set to: off
# gzip_vary on;

additionally, I also told gzip to disable for IE6.
Gotcha: I found that specifying an expires header also caused problems.  I suggest you comment out any expires directives while testing and figure out how to filter out as needed.
so, for good measure, here's the updated compression part of my conf for nginx
 ## Compression
  gzip              on;
  gzip_buffers      16 8k;
  gzip_comp_level   6;
  gzip_http_version 1.0;
  gzip_min_length   0;
  gzip_types        text/plain text/css image/x-icon text/html text/xml application/x-javascript;
  #gzip_vary         on;
  gzip_disable     "msie6";
  gzip_proxied     any;


text:
Q: Why does naturalHeight or naturalWidth return `undefined`? My class assignment wants me to use the defer tag for the script I am referencing, but this leads to the image's naturalWidth being undefined due to the order of execution in my js file.
My HTML has this line in the head (assignment wants me to put it in the  but use defer="defer")

My js:
var catImageWidth = document.getElementById("cat-image").naturalWidth;
var birdImage = document.getElementById("bird-image");
birdImage.width = catImageWidth;

So I tried this:
var catImage = document.getElementById("cat-image");
var birdImage = document.getElementById("bird-image");
var catImageWidth;

catImage.onload = function() {
    catImageWidth = this.naturalWidth;
    console.log(catImageWidth) //logs 600
}

birdImage.width = catImageWidth; //logs `undefined`

I think that the assignment of birdImage.width is undefined because this line of code runs before catImage.onload actually happens. Does this mean that I'm slave to assigning birdImage.width within the scope of  the function of catImage.onload?
P.S. I tried ES6 of catImage.onload = () => { //block of code } but this didn't seem to work.

A: The issue is that you are trying to access a variable out of scope.
Please give this a try:

A:
Does this mean that I'm slave to assigning birdImage.width within the scope of the function of catImage.onload?

Seems so, that's the best way to do it.
You can use an arrow function, but not with the this keyword to reference the image.
Doesn't work:
catImage.onload = () => {
    catImageWidth = this.naturalWidth; //undefined
    console.log(catImageWidth)
}

Because in arrow function the this object doesn't bind to the image  reference, it references the outer scope's this.
Does work:
catImage.onload = function() {
    catImageWidth = this.naturalWidth;
    console.log(catImageWidth) //logs 600
}

Or:
catImage.onload = function() {
    catImageWidth = catImage.naturalWidth;
    console.log(catImageWidth) //logs 600
}


text:
Q: SVG textpath element renders incorrectly in Firefox when generated using Javascript The following code renders fine in Chrome, IE11 and Opera, but shows the text in the upper left corner in Firefox:
var svgNS = "http://www.w3.org/2000/svg";
var xlinkNS = "http://www.w3.org/1999/xlink";

var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
svg.setAttributeNS(null, "viewBox", "0 0 1000 1000");
svg.id = "clockSVG";
document.body.appendChild(svg);

var defs = document.createElement('defs');
defs.id = "defs";
svg.appendChild(defs);

var path = document.createElementNS(svgNS,"path");
path.setAttribute("d","M75,20 l100,0 l100,30 q0,100 150,100");
path.setAttribute("id","myTextPath2");
defs.appendChild(path);

var text = document.createElementNS(svgNS,"text");
text.setAttribute("x","10");
text.setAttribute("y","100");
text.setAttribute("fill","black");
svg.appendChild(text);

var textPath = document.createElementNS(svgNS,"textPath");
textPath.setAttributeNS(xlinkNS, "xlink:href", "#myTextPath2");
textPath.textContent = "Text along a more advanced path with lines and curves.";
text.appendChild(textPath);
svg.appendChild(text);

If I call text.getBBox(), it reveals that it hugs the left screen edge and somehow receives a negative y-value:
SVGRect { x: 0, y: -14.825797080993652, width: 355.164306640625, height: 18.532245635986328 }

After some experimentation I found that for textPath elements to render correctly in Firefox when declared in the HTML, the content of the textPath element must be on the same line as the tags.
This will render with a weird offset:
<text x="10" y="100" style="stroke: #000000;">
    <textPath xlink:href="#myTextPath2">
        Text along a more advanced path with lines and curves.
    </textPath>
</text>

This will render correctly:
<text x="10" y="100" style="stroke: #000000;">
    <textPath xlink:href="#myTextPath2">Text along a more advanced path with lines and curves.</textPath>
</text>

(If the text's x and y attributes are set to 0 or left blank, however, it renders correctly)
So I tried constructing the necessary HTML as a one-line string and inserting that:
var textPathString = '<textPath xlink:href="#myTextPath2">Text along a more advanced path with lines and curves.</textPath>';
text.innerHTML = textPathString;

Unfortunately, that doesn't render anything (doesn't work in Chrome, either).
How can I make sure Firefox displays textpaths generated by JavaScript correctly?
Are these bugs and should I report them?
Any and all help will be greatly appreciated as my project relies on being able to dynamically generate textpaths!

A: You have written createElement("defs") rather than createElementNS which you have used at all other points.


text:
Q: Error extracting setup 1 cab when trying to install Osu! I am new to Linux and am running Ubuntu 14.04 64-bit. I was trying to install a game called Osu! on Wine. I set up prefix in 64-bit wine version 1.7.3. When I run the .exe file of the game, an error shows up saying: error extracting setup_1.cab.The file is not a cabinet.

A: Ubuntu 16.04-18.04

*

*If your computer is 64-bit, add the 32-bit architecture:
sudo dpkg --add-architecture i386

*Add the Wine Staging repository:
wget -nc https://dl.winehq.org/wine-builds/Release.key
sudo apt-key add Release.key
sudo apt-add-repository https://dl.winehq.org/wine-builds/ubuntu/

Or in Ubuntu 17.10 and 18.04 you can skip Steps 2-4 and simply type:
sudo apt install wine-stable

*Update the list of available software.
sudo apt update

*Install winehq-stable.
sudo apt install --install-recommends winehq-stable

*Create a new Wine prefix (if you don't want to use your default prefix).
env WINEPREFIX=$HOME/.wineosu wineboot --init

If Wine prompts for installing Mono, click Cancel.

*Ensure that Mono is not installed (use 'wine' for 32-bit prefixes, and 'wine64' for 64-bit):
env WINEPREFIX=$HOME/.wineosu wine uninstaller --remove '{E45D8920-A758-4088-B6C6-31DBB276992E}'
env WINEPREFIX=$HOME/.wineosu wine64 uninstaller --remove '{E45D8920-A758-4088-B6C6-31DBB276992E}'

*Set reported version to Windows XP (it will ensure that the installer of .NET 4.0 will copy some required files like mscoree.dll).
env WINEPREFIX=$HOME/.wineosu winecfg

On winecfg dialog, change reported Windows version to Windows XP, and click OK.

*Download and install .NET Framework 4.0 (higher versions of .NET will not work on Wine if this version is not previously installed):
wget https://download.microsoft.com/download/9/5/A/95A9616B-7A37-4AF6-BC36-D6EA96C8DAAE/dotNetFx40_Full_x86_x64.exe
env WINEPREFIX=$HOME/.wineosu wine dotNetFx40_Full_x86_x64.exe /q
env WINEPREFIX=$HOME/.wineosu wineboot --restart

*Set reported version to Windows Vista, and add mscoree.dll override.
env WINEPREFIX=$HOME/.wineosu winecfg

Change reported Windows version to Windows Vista (because .NET 4.5 and higher don't install on Windows XP/2003, and osu! will not start if reported version is set to Windows 7 or higher).
Go to Libraries tab. Add an override to mscoree and set it to "Native". Close all dialogs by clicking OK.

*Download and install .NET Framework 4.6.1 (osu! Stable needs .NET 4.5 or higher to work, and Lazer needs .NET 4.6.1 or higher):
wget https://download.microsoft.com/download/E/4/1/E4173890-A24A-4936-9FC9-AF930FE3FA40/NDP461-KB3102436-x86-x64-AllOS-ENU.exe
env WINEPREFIX=$HOME/.wineosu wine NDP461-KB3102436-x86-x64-AllOS-ENU.exe /q
env WINEPREFIX=$HOME/.wineosu wineboot --restart

Make sure to append the "/q" parameter after the installer path to perform a silent installation, because GUI installation of .NET 4.6.1 still doesn't work (without more workarounds) on Wine.

*Download and install osu!:
Stable version: (Beta and Cutting edge must be selected at osu!'s Options menu after Stable is installed):
wget http://m1.ppy.sh/r/osu!install.exe
env WINEPREFIX=$HOME/.wineosu wine 'osu!install.exe'

It's highly recommended to change the installation path to C:\osu! so you can easily find osu! files later. Then you will find them on $HOME/.wineosu/drive_c/osu!. Make sure to use only ASCII characters for the path to avoid installation problems.
Lazer version:
osu!lazer can't be installed using its default installer because it needs non-administrator privileges. Instead, download the "osulazer-full.nupkg" file from https://github.com/ppy/osu/releases and extract it inside your wine drive_c.

Ubuntu 12.04-14.04
Detailed instructions to play osu! on Ubuntu (12.04 through 14.04 + variants) (x86_64)

*

*Add the Official Wine PPA. From the terminal run this command:
sudo add-apt-repository ppa:ubuntu-wine/ppa

*Update Software Sources.
sudo apt-get update

*Install Wine.
sudo apt-get install wine1.7

*

*Accept the license for the fonts package. (Well, read it first of course. You may have to click the Terminal window and use Tab and Arrow Keys to navigate.)

*Create a Wine Prefix Folder.
mkdir 'Wine Prefixes'

*

*Make sure your terminal is at your Home directory. (You can change directories to your home directory using the command cd ~)

*Create a osu! Wine Prefix and make it a 32-bit Prefix.
WINEPREFIX='/home/USERNAME/Wine Prefixes/osu!' WINEARCH=win32 winecfg

*

*Replace USERNAME with your Linux username. (You will have to do this for the rest of these instructions.)

*Feel free to just close the configuration window afterwards.

*Install .NET Framework 2.0 Service Pack 1.
WINEPREFIX='/home/USERNAME/Wine Prefixes/osu!' winetricks dotnet20sp1

*Download osume.exe.
wget http://osu.ppy.sh/release/osume.exe

*Create a osu! folder in the Program Files folder in your Wine prefix and move osume.exe to it.
mkdir '/home/USERNAME/Wine Prefixes/osu!/drive_c/Program Files/osu!' && mv osume.exe

*

*You can manually create the folders and move osume.exe with GUI also.

*Start osume.exe
WINEPREFIX='/home/USERNAME/Wine Prefixes/osu!' wine '/home/USERNAME/Wine Prefixes/osu!/drive_c/Program Files/osu!/osume.exe'

*Wait for osu! update to completely download osu!

*

*If you have a beatmap and/or skin library backup somewhere, now would be a good time to restore it.

*Start osu!

*Do any initial in-game setup you want.

*

*Includes logging in, setting a resolution, changing keybindings, etc.

*If you cannot see the login window (it appears behind osu!), set osu! to a smaller window resolution via cfg

*If setting a fullscreen resolution causes osu! to crash and you cannot close it, see additional notes.

*Exit osu!
From this point on, the only thing you need to do to run osu! is just run the osu!.exe binary (double-click it or use the wine command from the terminal). You will have to create a shortcut(s) to osu! if you want. The easiest way is to go to the folder via the GUI file browser, right-click osu!.exe and make a link, and put the link on your desktop.
Source: WineHQ AppDB osu!


text:
Q: cannot boot Ubuntu 13.04 64bit (dualboot Windows-8) I was have Ubuntu before maybe 10.10 and was working fine. after I buy my new laptop AsusX401A with Win8-64bit, I was installed Ubuntu 13.04 but after restart the computer I got a black Screen. and I Google it and install boot-repair. and than, just I can log-on to Win8 only. If i boot Ubuntu I got this message.
[[ 2.238863 kernel panic - not syncing: no init found. try passing init= option to kernel. see linux Docmentation/init.txt for guidance. ]]

A: Try to follow the following instructions to install a dual boot
http://www.makeuseof.com/tag/tired-of-windows-8-how-to-dual-boot-windows-ubuntu/


text:
Q: Get information about selected group of neighbors when using KNN-Algorithm I am trying to develop a ken-algorithm to find the 5-6 closest datasets and use the mean or median of that peer group for the prediction.
Economically it is very important to get to know the information about the selected peer group by the algorithm.
Is it possible to get the information about the nearest neighbours the algorithm used for the prediction in a certain case?
Thanks for all your help!


text:
Q: Is this an example of comaximal ideals $I,J$ such that $IJ\not=I\cap J$? Let $R$ denote the set of all finite formal sums of elements in the free group $\left<a,b\right>$ with the relation $a+b=1.$ Let $I$ be the principle ideal generated by $a$ and $J$ the principle ideal generated by $b.$ It follows that $ba\in I\cap J,$ however, $ba\not\in IJ.$
The fact that $ba\not\in IJ$ follows from if
$$\sum_{i=1}^mw_i\in I$$
where $w_i$ are words in $a,b,$ then by definition each $w_i$ contains $a.$ Similarly if
$$\sum_{j=1}^mv_i\in J,$$
then each $v_i$ contains $b$. Then
$$\left(\sum_{i=1}^mw_i\right)\left(\sum_{j=1}^mv_i\right)=\sum_{i,j}w_iv_j,$$
and each $w_iv_j$ has an $a$ to the left of a $b.$ So
$\sum_{i,j}w_iv_j\not=ba.$
Clearly $I+J=R$ as $a+b\in I+J$ and $a+b=1.$


text:
Q: Gmail Automation via Bash (To refresh POP Fetch from other accounts) Gmail has this option to fetch mails from other accounts. I used this feature to create a central mail box. Works good.
Gmail periodically polls other mail box over POP. But the frequency is 1 hour + , sometimes even more than that. There is no option to pull mails manually on mobile gmail version. But the full blow gmail web (not basic HTML Version) has has a REFRESH button on top which will fetch mails from other boxes right away. Also, under settings there is option to CHECK MAILS. Does the same.
Is there a way to automate a gmail login, click the REFRESH button and exit every 10 minutes?
I am comfortable with WGET, if it was a basic HTML, could have automated. But there is a lot of javascript processing before the page is loaded, and I am lost where to begin javascript automation via bash.
Any leads will help, Thanks.


text:
Q: appsettings.json and Class libraries that use ConfigurationManager.AppSettings I'm working on migrating an existing ASP.NET MVC app to ASP.NET Core. The solution has several class libraries (providing data access, services, etc). Many of those class libraries make use of the static ConfigurationManager.AppSettings["..."] way of getting the config from the web.config file.
With the ASP.NET Core app, though, there is no web.config file and it appears ConfigurationManager can't read appsettings.json.
I really like the new configuration system in ASP.NET Core, and am making use of it within the web app.
But is there a "simple" way to migrate these class libraries without having to rewrite them to use the new configuration system? Any basic replacement for the static ConfigurationManager.AppSettings["..."] calls that'll read appsettings.json? (note: we'll eventually rewrite them, but we'd rather do this one piece at a time)

A: If you're using .NET Standard 2.0 you can add a reference to the System.Configuration.ConfigurationManager NuGet package to get access to appSettings.
You can add an app.Config file (not web.Config) to your ASP.NET Core project to store the appSettings.  This will be copied to the output folder and renamed as AppName.dll.config during the project build.

A: Disclaimer: I didn't try this with a class library, but this worked in LinqPad:
void Main()
{
    var config = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
        .AddInMemoryCollection(new Dictionary<string, string>
        {
            ["test"] = "test",
            ["test2:test"] = "test2"
        })
        .Build();

    foreach (var pair in config.AsEnumerable())
    {
        // Skips the (test2 = null) pair
        if (pair.Value != null)
        {
            ConfigurationManager.AppSettings.Set(pair.Key, pair.Value);
        }
    }

    ConfigurationManager.AppSettings["test"].Dump();
    ConfigurationManager.AppSettings["test2:test"].Dump();
}

You could put something like this in your initialization code.
It sets all of the values available to the System.Configuration app setting collection.


text:
Q: Multiple events detected where should only be one I have an indicator element that should disappear when I hover it, and replacement should appear on same place.
Now when I leave this replacement, it should now disappear, and old indicator should take it's place again.
Here is a HTML for indicators or triggers:

HELP ME

And here is jQuery code:
jQuery('.help-trigger.for-mobile').hover(function(){
    jQuery(this).stop( true, true ).hide();
    jQuery('.help-trigger.for-desktop').stop( true, true).show();
    jQuery('.help-trigger.for-desktop').mouseout(function(){
        jQuery(this).stop( true, true ).hide();
        jQuery('.help-trigger.for-mobile').stop( true, true ).show();
    });
});

This in general works, but it sort of flickers and it's unstable. Events get detected more than they should (in lack of better words) so I get too many changes even though I haven't left .for-desktop element

A: You are adding a .mouseout() event handler each time(!) you hover your move over your .help-trigger.for-mobile elements. So on each mouseout you call several handlers ... is that your purpose?
EDIT: Additionally, using .hover() with only one callback will add a handler for both mouseenter and mouseleave, so you add additional handlers for .mouseout on each mouseenter and mouseleave

A: Hey i think you trying to achive something like that :
$('.help-trigger.for-mobile').hover(function() {
        $(this).hide();
    }, function() {
        $(this).show();
    });

You put a .mouseout inside the mouseover, can't work that way : https://api.jquery.com/hover/


text:
Q: How to try create an url from an uri without a trailing `/`? If I run this MCVE:
public static void Main()
{
    Uri.TryCreate("https://dotnetfiddle.net", UriKind.Absolute, out var result);
    Console.WriteLine(result); // should be "https://dotnetfiddle.net"

    Uri.TryCreate("https://dotnetfiddle.net:5555", UriKind.Absolute, out var result5555);
    Console.WriteLine(result5555); // should be "https://dotnetfiddle.net:5555"

    Uri.TryCreate("https://dotnetfiddle.net?a=1", UriKind.Absolute, out var result2);
    Console.WriteLine(result2); // should be "https://dotnetfiddle.net?a=1"

    Uri.TryCreate("https://dotnetfiddle.net/", UriKind.Absolute, out var result3);
    Console.WriteLine(result3); // correct

    Uri.TryCreate("https://dotnetfiddle.net/?a=1", UriKind.Absolute, out var result4);
    Console.WriteLine(result4); // correct

    Uri.TryCreate("https://dotnetfiddle.net/test", UriKind.Absolute, out var result5);
    Console.WriteLine(result5); ; // correct

    Uri.TryCreate("https://dotnetfiddle.net/test?a=1", UriKind.Absolute, out var result6);
    Console.WriteLine(result6); // correct
}

I will get the following output:
https://dotnetfiddle.net/
https://dotnetfiddle.net:5555/
https://dotnetfiddle.net/?a=1
https://dotnetfiddle.net/
https://dotnetfiddle.net/?a=1
https://dotnetfiddle.net/test
https://dotnetfiddle.net/test?a=1

but I am looking for:
https://dotnetfiddle.net
https://dotnetfiddle.net:5555
https://dotnetfiddle.net?a=1
https://dotnetfiddle.net/
https://dotnetfiddle.net/?a=1
https://dotnetfiddle.net/test
https://dotnetfiddle.net/test?a=1

I read the official documentation without finding about this issue.
How can I fix it to avoid the trailing '/' at the end of the uri? I would like to get the same output than my output. Keeping the / when I give one, but remove it when I dont.

A: You can do a little string builder with Uri segments
using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
            string url = "https://dotnetfiddle.net:333/?a=1";
            UriBuilder uri = new UriBuilder(url);
            Console.WriteLine(uri.Scheme + Uri.SchemeDelimiter + uri.Host + (url.Contains(uri.Port.ToString()) ? ":" + uri.Port : "") + (uri.Path.Length > 1 ? uri.Path : uri.Path.TrimStart('/')) + uri.Query);
    }
}

Output : https://dotnetfiddle.net:333?a=1


text:
Q: Как исправить ошибку TypeError: expected string or bytes-like object? Я написал регулярное выражение для проверки FQDN адресов, однако, оно не работает. Точно такое же регулярное выражение для ip-адресов выше проблем не создает. Я пытался приводить value словаря к строке в условии if/else, но это не помогло.
Полный текст ошибки:
Traceback (most recent call last):
  File "c:\Users\kvvol\Desktop\Pytest\Script.py", line 72, in <module>
    mistakes()
  File "c:\Users\kvvol\Desktop\Pytest\Script.py", line 31, in mistakes
    if(fqdnadd_pat.match(firewall['Исходящий FQDN']) and firewall['Исходящий FQDN'] != None):
TypeError: expected string or bytes-like object

Сам код:
import openpyxl
import re

wb = openpyxl.reader.excel.load_workbook(filename="Zayavka.xlsx")

wb.active = 0
ws = wb.active
firewall = {} #один блок с одним средством защиты

ipadd_pat = re.compile("^((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([1-9]|[1-2][0-9]|3[0-2]))?\s?(\([Nn][Aa][Tt]\s(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\))?;\s?){1,}$")
fqdnadd_pat = re.compile("^(([a-zA-Z0-9]+\.?)+\s?\(((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]);\s?){1,}\);\s?){1,}$")

def mistakes():
    if (firewall['Сегмент источника'] == firewall['Сегмент назначения']):
        print('Сегмент источника и сегмент назначения совпадать не должны')
    else:
        if(firewall['Адрес/сеть назначения'] == None):
            print('Заполните поле "Адрес/сеть назначения"')

        if(firewall['Исходящий адрес'] != None):
                print('Поле "Исходящий адрес" оставьте пустым')
        elif(firewall['Исходящий IP-адрес/сеть'] == None and firewall['Исходящий адрес'] != None):
                print('Содержимое поля "Исходящий адрес" перенесите в поле "Исходящий IP-адрес/сеть"')

        if(ipadd_pat.match(firewall['Исходящий IP-адрес/сеть']) and firewall['Исходящий IP-адрес/сеть'] != None):
            print("Ip-адреса заполнены корректно")
        else:
            print("Ip-адреса заполнены некорректно")

        if(fqdnadd_pat.match(firewall['Исходящий FQDN']) and firewall['Исходящий FQDN'] != None): # на этой строке ошибка
            print('FQDN заполнены корректно')
        else:
            print('FQDN заполнены некорректно')

        if(firewall['Протокол доступа'] != None):
                print('Поле "Протокол доступа" оставьте пустым')

        if(firewall['Порт доступа'] != None):
                print('Поле "Порт доступа" оставьте пустым')

def fire_fill():

    firewall['Название средства защиты'] = ws['B' +str(i+1)].value
    firewall['Сегмент источника'] = ws['B' +str(i+2)].value
    firewall['Сегмент назначения'] = ws['B' +str(i+3)].value
    firewall['Протокол доступа'] = ws['B' +str(i+4)].value
    firewall['Исходящий адрес'] = ws['B' +str(i+5)].value
    firewall['Порт доступа'] = ws['B' +str(i+6)].value
    firewall['Исходящая учётная запись/AD'] = ws['B' +str(i+7)].value
    firewall['Исходящий IP-адрес/сеть'] = ws['B' +str(i+8)].value
    firewall['Исходящий FQDN'] = ws['B' +str(i+9)].value
    firewall['Адрес/сеть назначения'] = ws['B' +str(i+10)].value
    firewall['Адрес назначения FQDN'] = ws['B' +str(i+11)].value
    firewall['Номер порта TCP'] = ws['B' +str(i+12)].value
    firewall['Номер порта UDP'] = ws['B' +str(i+13)].value

for i in range(1, ws.max_row):

    checker = i

    if(ws['A' +str(i)].value == '№ Заявки'):
        firewall['№ Заявки'] = ws['B' +str(i)].value
        print()
        print('Заявка ' + str(firewall['№ Заявки']))
        block_counter = 1

    while ws['A' +str(checker+1)].value == 'Название средства защиты':
        fire_fill()
        print()
        print('Блок ' + str(block_counter))
        mistakes()
        checker += 12
        block_counter += 1

A: Конструкция condition1 and condition2 and condition3 выполняется в Python слева направо и если находится хотя бы одно условие для которого выполняется bool(conditionX) == False - проверка обрывается на этом месте и возвращается False. Все последующие условия не проверяются.
В вашем случае первым выполняется проверка fqdnadd_pat.match(firewall['Исходящий FQDN']), которая вызывает указанную в вопросе ошибку.
Поэтому вам надо изменить порядок проверки и кроме того лучше использовать идиоматический вид проверки на None:
if firewall.get('Исходящий FQDN') and fqdnadd_pat.match(firewall['Исходящий FQDN']):
    ...

if firewall.get('Исходящий FQDN') - делает сразу две проверки:

*

*проверка на существование в словаре firewall ключа "Исходящий FQDN", т.к. dict.get(<not-existing-key>) вернет None

*проверка на то, что значение firewall['Исходящий FQDN'] не None

PS по канонам PEP-8, правильно проверять на variable is None следует так:
if not variable:
    ...

и для variable is not None:
if variable:
    ...


text:
Q: Get all site collection of a web application using powershell in SharePoint 2019 I want to get all collection url and name of a web application and export the values into excel, how to do that?

A: You could try the following code:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Web application URL and CSV File location Variables
$WebAppURL="https://intranet.crescent.com"
$CSVFile="C:\SitesList.csv"

#Get list of site collections in a web application powershell
Get-SPWebApplication $WebAppURL | Get-SPSite -Limit All | ForEach-Object {
    New-Object -TypeName PSObject -Property @{
             SiteName = $_.RootWeb.Title
             Url = $_.Url
             DatabaseName = $_.ContentDatabase.Name }
} | Export-CSV $CSVFile -NoTypeInformation


text:
Q: how to enumerate through multiple digital certificates in .net What is the best way to enumerate through multiple certificates in an exe.
I used the following code
X509Certificate2 certificate = new X509Certificate2(filePath);
var certificationCollection = new X509Certificate2Collection(certificate);
foreach (X509Certificate2 x509 in certificationCollection) {

But this code only return the first certificate if the exe contains more than one certificate.
Example : SHA1 , SHA256


text:
Q: Laravel Models, global filter I really don't want to have to override Eloquent to do this, and its robust enough that this could be possible without it.
Anyway I am working on a cloud style application that uses a table for subdomains. Every table in the database refers to this table to filter data into each subdomain (all using the same database).
So this means normally everywhere I need to call data I would need to apply $model->where('site_id','=',CURRENT_SUBDOMAIN_ID);
So is there anyway to add something like that in Eloquent? Still learning Laravel but have not found any information on this.
App::before(function($request)
{
    $host = $request->getHost();
    $parts = explode('.', $host);
    $subdomain = $parts[0];

    if($subdomain!='main'){
        $site_settings = DB::table('sites')->where('subdomain',$subdomain)->first();
        if(!$site_settings){ //find out a better way to do a 404 or redirect
            return Redirect::to('http://testing.app:8000/login');
        }
        Config::set('request.site_name', $site_settings->subdomain);
        Config::set('request.site_params', json_decode($site_settings->params));
        Config::set('request.site_id', $site_settings->id);
    }
});

This is how I am figuring out what subdomain the client is currently in, through it I have a global for site_id, the last step is basically applying to a model.
Also every model has the following:
public function site()
{
    return $this->belongsTo('\Site');
}

A: I was thinking the wrong way when I could not find this, it is not a global filter for laravel it is a scope.
Global filtering - how to use global scope in Laravel Eloquent
Just one of the things that laravel does in an innovative way that seems a little different then what you are used to. Great but mind blowing.