text:
Q: Thread safe high performance random generator I need a high performance random number generator that is thread-safe. I need only random bytes in the value type (which is ulong for now), not within ranges. I've used the C# built-in Random class, but it was kind of slow and not thread-safe.
Later I moved to XORShift functions that actually works very fine, but to achieve thread-safeness I need to put the calculation in lock, and that degrades the performance drastically.
What I'm using to generate a random ulong is the following:
public class Rand
{
    ulong seed = 0;
    object lockObj = new object();

    public Rand()
    {
        unchecked
        {
            seed = (ulong)DateTime.Now.Ticks;
        }
    }

    public Rand(ulong seed)
    {
        this.seed = seed;
    }

    public ulong GetULong()
    {
        unchecked
        {
            lock (lockObj)
            {
                ulong t = 0;

                t = seed;
                t ^= t >> 12;
                t ^= t << 25;
                t ^= t >> 27;
                seed = t;

                return t * 0x2545F4914F6CDD1D;
            }
        }
    }
}

This works fine and fast, but locking makes it take about 1-2us if it is called from 200 concurrent threads, otherwise calculation finishes under 100ns.
If I remove locking there is a chance two threads take the same seed and will calculate the same random which is not good for my purposes. If I'm removing the ulong t declaration and work directly on the seed then there will be a very little chance to generate the same random for two concurrent calls, but there is also a chance the value will be shifted out from the value range, like t << 25 will be called many times in a row by different threads without carrying the rotation it will become just simply 0.
I think the proper way would be if there is a shared value that may be changed by any concurrent call and work with that value in the calculation methods, since these values are atomic (at least withing CPU cores) it is not a problem if many calculations are using it in the same time, but that is a problem if this value shifts out from the bitrange.
Is there any good solution to solve this problem? I'd be thankful for any help.
Edit: Ok, I've forgot to mention I have no control over the threads, because async tasks are calling this function, so threads are coming randomly from the threadpool, using thread ID is also a no solution, since there is a chance one specific thread never will call this method again at all, and keeping an instance for that ID is not a good thing.

A: Simply create one instance of Rand on each thread. Thread-safe, no locking, thus very performant. This can be achieved using the ThreadStaticAttribute.
public static class Rand
{
    [ThreadStatic] private static Rand defaultRand;
    public static Rand Default => defaultRand ??= new Rand();
    // Add extra methods for seeding the static instance...
}

// Then in any thread:
var randomNumber = Rand.Default.GetULong();

A: The less code we execute in the critical section, the faster it will work.
It runs 30-50% faster on my CPU.
You can also use an asynchronous process that will prepare the next collection
public sealed class Rand
{
    private ulong seed = 0;
    private readonly object lockObj = new object();

    public Rand()
    {

        unchecked
        {
            seed = (ulong) DateTime.Now.Ticks;
        }

        _current = 500;
    }

    public Rand(ulong seed)
    {
        this.seed = seed;
    }

    private ulong[] _batch = new ulong[501];
    private int _current = -1;

    public ulong GetULong2()
    {
        unchecked
        {
            ulong t = 0;
            lock (lockObj)
            {
                t ^= seed >> 12;
                t ^= t << 25;
                t ^= t >> 27;
                seed = t;
            }
            return t * 0x2545F4914F6CDD1D;
        }
    }

    public ulong GetULong5()
    {
        unchecked
        {

            var t = seed;
            t *= (uint)Thread.CurrentThread.ManagedThreadId;
            t ^= t >> 12;
            t ^= t << 25;
            t ^= t >> 27;
            seed = t;
            return t * 0x2545F4914F6CDD1D;
        }
    }
    public ulong GetULong()
    {

        unchecked
        {
            do
            {
            var current = Interlocked.Increment(ref _current);

            if (current < 501)
                return _batch[current];

            lock (lockObj)
            {
                if (_current >= 500)
                {
                    ulong t = seed;
                    for (int i = 0; i < 501; i++)
                    {
                        t ^= t >> 12;
                        t ^= t << 25;
                        t ^= t >> 27;
                        var result = t * 0x2545F4914F6CDD1D;
                        _batch[i] = result;

                    }
                    seed = t;

                    _current = -1;
                }
            }
            }while(true);

        }
    }

}

A: You can do it without locking and still be threadsafe. Assuming the calculation is very fast (it is) and there is slower code executing around it, it's likely faster to simply recalculate if another thread changes it in between starting the calculation and finishing it. You can do that with an Interlocked.CompareExchange spin loop. The only difficulty is that there is no ulong version of that so we have to use an unsafe method to get the equivalent.
private static unsafe ulong InterlockedCompareExchange(ref ulong location,
     ulong value, ulong comparand)
{
    fixed (ulong* ptr = &location)
    {
         return (ulong)Interlocked.CompareExchange(ref *(long*)ptr, (long)value, (long)comparand);
    }
 }

public ulong GetULong()
{
    unchecked
    {
       ulong prev = seed;

       ulong t = prev;
       t ^= t >> 12;
       t ^= t << 25;
       t ^= t >> 27;

       while (InterlockedCompareExchange(ref seed, t, prev) != prev)
       {
            prev = seed;
            t = prev;
            t ^= t >> 12;
            t ^= t << 25;
            t ^= t >> 27;
       }

       return t * 0x2545F4914F6CDD1D;
    }
}

A: Ok this solution by l33t is a very nice and elegant way to fix the cross-thread issue, and this solution by Stanislav also a suitable way to prevent on-demand generation by pre-generating and caching batches. Thanks everyone for the ideas.
Meanwhile I changed the bitshift to rotate, this will avoid shifting out the seed to 0, and I could omit the locking. Apparently it works just fine, and with very small latency (200 concurrent threads with about 100-120ns/call)
public class Rand
{
    ulong seed = 0;
    object lockObj = new object();

    public Rand()
    {
        unchecked
        {
            seed = (ulong)DateTime.Now.Ticks;
        }
    }

    public Rand(ulong seed)
    {
        this.seed = seed;
    }

    public ulong GetULong()
    {
        unchecked
        {
            seed ^= (seed >> 12) | (seed << (64 - 12));
            seed ^= (seed << 25) | (seed >> (64 - 25));
            seed ^= (seed >> 27) | (seed << (64 - 27));
            seed *= 0x2545F4914F6CDD1D;

            int s = Environment.CurrentManagedThreadId % 64;

            return (seed >> s) | (seed << (64 - s));
        }
    }

    // even faster
    public ulong GetULong2()
    {
        unchecked
        {
            seed ^= (seed >> 12) | (seed << (64 - 12));
            seed ^= (seed << 25) | (seed >> (64 - 25));
            seed ^= (seed >> 27) | (seed << (64 - 27));
            ulong r = seed * 0x2545F4914F6CDD1D;
            seed = r;

            int s = Environment.CurrentManagedThreadId % 64;

            return (seed >> s) | (seed << (64 - s));
        }
    }

    // better entropy
    public ulong GetULong3()
    {
        unchecked
        {
            int s = Environment.CurrentManagedThreadId % 12;

            seed ^= (seed >> (12 - s)) | (seed << (64 - (12 - s)));
            seed ^= (seed << (25 - s)) | (seed >> (64 - (25 - s)));
            seed ^= (seed >> (27 - s)) | (seed << (64 - (27 - s)));
            ulong r = seed * 0x2545F4914F6CDD1D;
            seed = r;

            s = Environment.CurrentManagedThreadId % 64;

            return (r >> s) | (r << (64 - s));
        }
    }
}

While this solution fits my demands the most, I will not mark it as an answer because it does not produce the same randoms as the one in the question, but still produces seemingly unique randoms across all threads, so still might be a solution.
Edit: Ok, after some experimenting GetULong() was the fastest, but from 100 million random generations produced more than 23000 colliding values on 200 concurrent threads. Same with GetULong2(). Added a little extra for GetULong3() method to increase entropy, that produced only about 210 colliding values from 100 million generations on 200 concurrent threads, and only about 50 colliding values from 100 million generations on 500 concurrent threads.
For me this kind of entropy is more than enougn, because they must be unique, so in my application after each generation they are tried to be added to a collection atomically and if there is already one with the same key, then random is called again. 50-200 retry in 100 million events is acceptable even on general random generators, so this is more than enough for me, especially, because it is fast, and can be used tread-safe with only one instance of the random generator.
Thank you everyone for the help, I hope this may help others also.


text:
Q: Eval in the context of another class I have the following code
class Tester

  def eval_something(string)
    eval(string)  # How to change?
  end

  def printer
    p "Not what I want"
  end
end

class MyClass

  def printer
    p "Hello World"
  end
end

t = Tester.new
t.eval_something("printer")

I want a Tester instance's eval_something  to evaluate the code in the context of MyClass. So for example, I want this script to print out Hello World instead of Not what I want.
Can this be achieved?

A: Not quite sure if this would work for your purposes, but you can try this:
class Tester
  def eval_something(string)
    MyClass.send(string.to_sym)  # Send will evaluate the symbol passed to it.  Equivalent of calling MyClass.printer in this case
  end

  def printer
    p "Not what I want"
  end
end

class MyClass
  def self.printer   # This needs to be a class method since MyClass does not inherit from Tester in this example
    p "Hello World"
  end
end

t = Tester.new
t.eval_something("printer")

=> "Hello World"

A: In your example, you can use the instance_eval method and pass a MyClass reference:
t = Tester.new
t.instance_eval do
  MyClass.new.printer
end

This will return "Hello World".
The instance_eval runs the code block that you pass in the context of the object. In this case you can access any instance variable. For example:
class Test
  def initialize any
    @any = any
  end
end

t = Test.new('abc')
t.instance_eval {puts @any}

It will print 'abc'.
It is recommendable to use the instance_eval and class_eval methods, since it gives to you more control to what it will execute. It is a safer option.
The eval method can execute an arbitrary code. If you do not control the content of string, it will be very risk option.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to delete table row by using both row id and table id in javascript?

          Relationship Type
          Date of Birth
          Gender

          Spouse
          1980-22-03
          female
          <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(2)"

          Child
          2008-23-06
          female
           <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(3)"

I want to delete the row by using both table id and row id in javascript. javascript code looks like this:
var child = document.getElementById(rowid);
child.parentNode.removeChild(child);

Here I am facing problem, the jsp page having multiple tables. So if I am trying to delete the row,it is deleting the other table rows. If I specify the table id along with row id the code will work fine.

A: Ids are suppose to be unique across your DOM, but you can first get the table
var table = document.getElementById("tableid");

var row = table.querySelector("tr[id='rowid']");

I recommend to use a different attribute other than id something like data-id
Now delete the row as
row.parentNode.removeChild(row)

var table = document.getElementById("dsTable");

var row = table.querySelector("tr[data-id='1']");

row.parentElement.removeChild(row);

          Relationship Type
          Date of Birth
          Gender

          Spouse
          1980-22-03
          female
          <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(2)"

          Child
          2008-23-06
          female
           <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(3)"


text:
Q: Why is this method of variable assignment causing issues? How does this style of variable assignment (it's inside an object so the "this" variable refers to said object)):
var prop       = this.properties;
var properties = this.properties;

Differ from this?
var prop = properties = this.properties;

When I changed to the latter it caused issues. Is it a referencing issue?

A: The difference is that with the second one, you're trying to assign to a properties variable that you haven't declared. The var only applies to prop, not properties because properties is on the right-hand side of the = after prop, so it's part of the initializer for prop. Here's how it's grouped:
var prop = (properties = this.properties);
//         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^−−−− initializer for `prop`

In loose mode, that means you're falling prey to what I call The Horror of Implicit Globals — it creates a global called properties. In strict mode, assigning to an undeclared identifier is the error it always should have been. (All new code should be written using strict mode.)
You can declare multiple variables with var, etc., but you can't assign to them all using the same value source (without repeating it).
You could do:
var prop, properties;
prop = properties = this.properties;

if you liked. Or alternatively:
var prop = this.properties, properties = prop;

That works because the initializers in a var (or let or const) with multiple declarations are executed in source code order, left-to-right, so prop = this.properties happens before properties = prop does.

Side note: var shouldn't be used in new code, use let or const. (If you have to support obsolete JavaScript engines, you can transpile modern code to ES5.)


text:
Q: get RSS where there is none Sorry for the long title and perhaps confusing half good now as we come. I'm asking advice or guidance on how I can get an RSS feed from a page that does not have RSS enabled by default.  But that is not the problem itself. The problem is when on that page I am asked to enter a username and password. Well so otherwise would be the thing...
PROBLEM:
Get the RSS of a forum which does not have an RSS feed enabled and to see the 'news' we need to be logged.
POSSIBLE SOLUTIONS that come to mind:

*

*There are several web sites which offer services in English to get RSS on pages where they are not. That's fine, but the problem is when these sites don't offer an option to login with a username and password to the web page where I want to get the info, so these types of sites are excluded.

*I did not login via url and so put that url on web sites listed above (item 1) of the forum with the username and password variables directly from the url spec: www.forosinrss/login.php?usuario = me & password = your pff and I'm bounced the forum, telling me I'm not getting the correct data as we will be. Another problem is that the password is md5 encrypted, so I'm prevented from logging in with the URL (fk T_T).

*Try using "SELECT * FROM DB Internet", or in other words, to use YQL. But it came out almost as much as they found no way to insert and log into user and password and also to generate a cookie for the forum is not happy I voted.

I need suggestions, recommendations, tips or complaints.

A: Download the page using something like cURL or fsockopen if you're feeling brave, then transform the page from html to rss using XSLT Stylesheets.

A: Once upon a time I wrote an app in PHP to do this with ok-ish results:

*

*use curl to get the page and keep a copy

*run a custom filter regular expression to select the bit of the page that actually matters (some sites have dynamic text like ads or just displaying the current date and time)

*after a timeout, use curl to get the page again and run the same filter on it

*run diff old_page, new_page and pipe the result into an rss template

The system worked ok but was fiddly filtering the page down to content that I wanted to get the feed from and it broke a lot because these kinds of sites are often hand edited so you can't guarantee any consistency.


text:
Q: Filter out a key from an object for send I am trying to filter 1 key out of an object for send. I have a big json tree that has a few sub levels and I just want to filter out the bottom most level before I send it , partly because it's huge and partly because the bottom most level of data is completely un used ( so I would like to cut it out).
So the object has levels like this
Account: {name: name, id: id,
                            school: {name: name, id: id,
                                              classroom: {name: name, id: id } } }

So I'm trying to simply cut out the classroom level inside this object -keep in mind there are about a hundred accounts so there are tons).
I previously received a great answer for filtering down to only 1 object (For send) like so
 $scope.ids = $scope.myScope.map( function(obj){
    return obj.id;
});

I'm wondering, is it maybe possible to use the array.map to say use everything except the classrooms? Or should I be approaching this in  a different way?

A: One iterative solution will be to go through each and remove the classroom object like this
obj = {"Account": {"name": "name", "id": "id",
                            "school": {"name": "name", "id": "id",
                                     "classroom": {"name": "name", "id": "id" } } }}

for (key in obj){
    try{
        delete obj[key].school.classroom
    }
    catch(err){
        console.log("didn't have classroom object")
        }
}

This has a linear complexity but is this the best solution.. not sure. Ill learn from this too


text:
Q: QGRID: Is it possible to enable a left-right scrollbar when displayed in Jupyter notebook? I checked the qgrid documentation, which is based on the SlickGrid library.  The SlickGrid grid options do not show something.  However it seems odd that a web based library would not allow scrolling left or right if all of the data does not fit within the current view.  As you can see below, my dataframe has 95 columns and only 10 are visible, with no scrollbar top access the other ones.

thx


text:
Q: screenshot with timer Hey Guys i have 1 More Problem . i want to take Screenshot with timer its works but it only take 1 screenshot after that it give me error i dont know what to do here is my CODE
i will show u error also
private static void GetScreenShot()
    {
        Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);

        Graphics graphics = Graphics.FromImage(bitmap as Image);

        graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);

        bitmap.Save("screenshot.jpeg", ImageFormat.Jpeg);

        }

    private void timer1_Tick(object sender, EventArgs e)
    {
        GetScreenShot();
        email.Send("HAMMAD");
        MessageBox.Show("DONE");

    }

A: Make a counter and then assign counter value to the filename.
Note 1: Bitmap parent class Image implements IDisposable interface so you could enclose the Bitmap class declaration within using block to make sure its disposal.
Note 2: Graphics class implements IDisposable interface so you could enclose the Graphics class declaration within using block to make sure its disposal.
Try This:
int counter = 0;
private void timer1_Tick(object sender, EventArgs e)
{
    counter =counter+1;
    GetScreenShot(counter);
    email.Send("HAMMAD");
    MessageBox.Show("DONE");

}

private static void GetScreenShot(int counter)
{
    using(Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                                          Screen.PrimaryScreen.Bounds.Height))
   {
      using(Graphics graphics = Graphics.FromImage(bitmap as Image))
      {
         graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
      }
      bitmap.Save("screenshot"+counter+".jpeg", ImageFormat.Jpeg);
   }
}

EDIT: for sending proper screenshot in email try this:
private void timer1_Tick(object sender, EventArgs e)
{
    counter =counter+1;
    GetScreenShot(counter);
    email.Send("screenshot"+counter+".jpeg");
    MessageBox.Show("DONE");
}


text:
Q: How to avoid 'require is undefined' error on the frontend when compiling 3rd party libraries I'm using GulpJS to compile all the 3rd party libraries that my app needs (for the frontend). I install these libraries via NPM, and use Gulp to concatenate and compile them into a single 'vendor' JS file. They get compiled correctly, but when I load the app in the browser, I get a "require is not defined" error. This is because some of the 3rd party libraries are using the 'require' syntax that is usually used in a node server environment. This pattern is getting popular on the frontend, however, I am not sure the best way to resolve this problem for my app.
From reading online, it seems like a gulp browserify plugin could be used, or requireJS. I currently don't have either installed. I tried the gulp browserify method but abandoned it as things were getting complex (I am not against trying this again if it is the recommended method). What is odd to me is that in the past, this was never a problem with the same 3rd party libraries. It seems like our app is behind the times.
Expected: all 3rd party libraries compile into a single file and the browser loads it fine.
Actual: all 3rd party libraries get compiled into a single file, but that file uses the 'require' syntax and therefore throws an error in the browser when the app tries to load.


text:
Q: macOS Swift 3 - Handling notification alert action button I'm new to Swift (but not to programming). I have simple app that provides an alert based on specific conditionals. I would like to execute a function (or even just set a variable) when one of the buttons is pressed. Ideally, I just need one button, but if for whatever reason, only the notification.actionButtonTitle can have a handler, that's fine with me.
My notification code is currently in a Swift file as a helper.
import Foundation

    class NotificationHelper {
      static func sampleNotification(notification: NSUserNotification) {
        let notificationCenter = NSUserNotificationCenter.default

        notification.identifier = "unique-id-123"
        notification.hasActionButton = true
        notification.otherButtonTitle = "Close"
        notification.actionButtonTitle = "Show"
        notification.title = "Hello"
        notification.subtitle = "How are you?"
        notification.informativeText = "This is a test"
        notificationCenter.deliver(notification)
      }
    }

Currently in AppDelegate, this is defined:
let notification = NSUserNotification()

…and I call the notification like this:
NotificationHelper.sampleNotification(notification: notification)

The resulting notification works, as you can see in the screenshot below. However, I cannot seem to listen to the button action. I have tried adding this to the AppDelegate as well as the NotificationHelper file, but I did not have any success with it:
func userNotificationCenter(center: NSUserNotificationCenter, didActivateNotification notification: NSUserNotification) {
  print("checking notification response")

}

Any idea of what I'm missing?
Thanks!

A: You'll need to assign something as the delegate of the NSUserNotificationCenter:
NSUserNotificationCenter.default.delegate = self
If you add this to your AppDelegate and make your AppDelegate conform to NSUserNotificationCenterDelegate:
class AppDelegate: NSObject, NSUserNotificationCenterDelegate {

}


text:
Q: Change Permission on ASP.NET folder after Publishing in Visual Studio I have a folder in my website which I need to make world readable after publishing it to my web server. Unfortunately just changing the permissions on the folder is no good as when I publish again it gets deleted as part of the publish process ad thus the permissions are reset to the permissions of the parent directory.
Is there an easy way to set these post deployment permissions or what is the equivalent of a post build step for the publish action. I get very few useful results if I search for post publish step.

A: Since we're talking folder NTFS (ACL) permissions here rather than web security permissions (I think), the answer is complicated.  You have to add a custom target to Visual Studio's web publishing pipeline.  I can't detail it better than Sayed Ibrahim Hashimi does here.


text:
Q: Supporting iOS 11 location permissions while disallowing "when in use" on iOS 10 When using iOS 10 I need users to choose between never allowing location and always allowing locations, so I added the key NSLocationAlwaysUsageDescription in the Info.plist.
Now with the new iOS 11 release, I need to add the following two keys to get the location permission prompt - NSLocationAlwaysAndWhenInUseUsageDescription and NSLocationWhenInUseUsageDescription.
When I try to remove the seemingly redundant NSLocationWhenInUseUsageDescription, it doesn't allow showing the location prompt on iOS 11
The problem is now my users on iOS 10 have a "when in use" option in their settings, which I don't want.
Is there any way to create a version which allows "never" and "always" for iOS 10 and allows all three options on iOS 11?

A: You are required to include the NSLocationWhenInUseUsageDescription and NSLocationAlwaysAndWhenInUsageDescription keys in your app's Info.plist file. (If your app supports iOS 10 and earlier, the NSLocationAlwaysUsageDescription key is also required.) If those keys are not present, authorization requests fail immediately.
https://developer.apple.com/documentation/corelocation/choosing_the_authorization_level_for_location_services/request_always_authorization#see-also


text:
Q: Android Requires MinSdk <=9 When I am trying to make a new Google Maps Activity, its grey and I cant click the option. (New --> Google --> Google Maps Activity (Requires MinSdk >=9)
I got the same message when I create a new app and try to choose the activity while setting up a new project.
C:\Users\Joey\AppData\Local\Android\sdk\platforms

Android-23
And when opening the SDK manager in Android Studio I got the following SDK tools.

Can someone tell me if Im missing something?

A: In your application level build.gradle file do you have minSdkVersion 9 or greater than 9 like this:
    defaultConfig {
        minSdkVersion 15 //this should be greater than or equal to 9
        targetSdkVersion 23
        //...
    }


text:
Q: A Vector Space is a Set - Axiom or Derivation? I understand that structures with the properties of the real and complex numbers can be defined and derived from the axioms of ZFC set theory.
But can a structure with the properties of a (possibly uncountably infinite dimensional) vector space be derived from ZFC or is it axiomatic statement that a vector space is a set (and that therefore the axioms of set theory apply to it) ?
I think the question becomes relevant in the proof that every vector space has a basis (from Zorn's lemma = axiom of choice). It's not just a matter of whether one accepts the axiom of choice in set theory, but how one gets to believe that a vector space complies with set theory axioms.

A: This is just a continuation from the definition of $\Bbb R$ as a set. The vector space $\Bbb R^n$, for example, is just the set of tuples with pointwise addition. And trivially, if $V$ is a real vector space whose basis is $B$, then $V$ can be thought of as the set of all functions from $B$ into $\Bbb R$ such that only finitely many elements are mapped to a non-zero element.
The axioms of set theory do not stop, or even begin to stop, at the real numbers or the complex numbers. They go well beyond your wildest dreams1. And then some.

Footnotes:

*

*At least if you dream about mathematics and set theory.

A: One can define
Definition. A vector space over a field $F$ is an abelian group $V$ together with an action $F\times V\to V$ of the field on it.
Definition. An abelian group is a group where the compostion is abelian.
Definition. A group is a set with a binary operation satisfying ...
Ultimately, this makes a vector space essentially a set - that is: A vector space is a tuple of several things and structures, the most important one being the set of vectors of the space.

A: There is a general construction beginning with the natural numbers.
I prefer to go from the non-zero natural numbers to the positive rationals.  Ordered pairs of naturals inherit the order relation of the naturals through the arithmetic of ratios.  Hence,
these ordered pairs can be collected into equivalence classes and called positive rational numbers.
By a similar process of using ordered pairs, one goes from the positive rationals to the full set of rationals.  In this case, ordered pairs are interpreted by signed differences.  If an ordered pair has the same positive rational for both elements, it will be in the equivalence class designated as 0.
From the rationals, you perform the Dedekind cut construction.  By the power set operation applied to omega in the set universe, you know that there is set in the universe of the proper cardinality.  The set of all countable sequences of natural numbers is uncountable.  If I recall correctly, it referred to as the Baire space.  It relates to the order relations of the Dedekind cuts through the arithmetic of continued fractions.  So, you have a set in the universe corresponding to your construction.
By the constructions thus far, you already have many of your needed operations.  You must consider anything more you may need to satisfy the definitions of a vector space or an inner product space on your construction.  This is all algebraic.  And, this is also where you accommodate dimensionality.
To obtain a Euclidean manifold, you must use a Cartesian product of your construction and an individual copy of your construction.  An affine space (vector space) or a Euclidean point space (inner product space) is obtained by a mapping from the Cartesian product into
the individual copy.  The Cartesian product in this case is "just a set".  The individual copy carries the vector space structure or the inner product structure.
As a disclaimer, let me say that serious mathematicians will see every mistake I have made in describing this.  But, I think they would concede that this description has met the general sense of how such a construction ought to proceed.

A: Vector spaces are sets, Cartesian products of fields, and therefore by definition rely on the set axioms.
An other question is how well vector spaces model the real space that surround us all. In the real space there are no dots or lines. In real space there are only relative distances. The real space isn't isomorphic with $\mathbb R^n$ at all. And is no set either.


text:
Q: Refresh token for Reddit API using Python requests I want to refresh access token but somehow my code returns empty response
response = requests.post(auth_url,data=refresh_data,auth=client_auth,headers=headers)

where refresh_data is
refresh_data = {'grant_type' : 'refresh_token',
'refresh_token' : '31763629822-aRVYmfxTAW4Sx5mihFB89sqwQno'
}

Here is code
import requests
import requests.auth
from requests import Request
from bs4 import BeautifulSoup
import json
url = 'https://www.reddit.com/dev/api/'

oauth_url = 'https://oauth.reddit.com/'

auth_url = 'https://www.reddit.com/api/v1/access_token'

CLIENT_ID = 'api key'
CLIENT_SECRET = 'api secret'

refresh_data = {'grant_type' : 'refresh_token', 'refresh_token' : '31763629822-aRVYmfxTAW4Sx5mihFB89sqwQno'}

headers = {'User Agent' : 'Test Client v/1.0 '}

 response = requests.post(auth_url,data=refresh_data,auth=(CLIENT_ID,CLIENT_SECRET),headers=headers)

print(response.json())

can you help me find the error ?

A: wrong header
headers = {'User-Agent' : 'Test Client v/1.0 '}


text:
Q: How to execute script after system reboot by using kickstart I'm using PXE to install ISO. There are two scripts for environment configuration, I want to added them in kickstart file, so the environment will be setup completely and automatically after the system installed.
However, my situation is:

*

*Script 1 must reboot (has been added in script1.sh)

*Script 2 depends on script 1

Here part of kickstart file:
...
...
%post

wget http://xxx/script1.sh
wget http://xxx/script2.sh

sh -x script1.sh | tee script1.log
sh -x script2.sh | tee script2.log

%end

So, is there anyway that script 2 can be executed after system reboot by using kickstart file? Or the other way, just executed the script 2 once after reboot.
Thanks.

A: The way I have done this is to make a startup script that calls secondary script(s), which in your case are script1.sh and script2.sh.
Here is one reference about configuring RHEL 6 Runlevels and Services.  Alternatively, if have access to an existing RHEL/CentOS system you could browse /etc/init.d/ and copy one of the simpler startup scripts there as the basis for your own.
To put this all together, you'll need to:
In your kickstart file

*

*Add an additional wget call to download the startup script you created.

*You'll need to copy/move the startup script to /etc/init.d .  Keep in mind that %post is run in a chroot environment.

*Enable the startup script on boot with chkconfig.

In your startup script

*Upon successful completion of script2.sh, disable the startup script with another chkconfig *service_name* off so it isn't run on future reboots.


text:
Q: How to dump command line instruction itself into output file? In the Windows command line, I want to dump the command line instruction directly into output file, aka
For instance, if I execute:
dir "C:\Program Files\*.exe" /B /S /O:GNE > "ExeList PgmFiles.txt"

I want into the output file "ExeList PgmFiles.txt" a first line with with the command line instructions itself(to keep track of what is actually executed), so in this example:
dir "C:\Program Files\*.exe" /B /S /O:GNE > "ExeList PgmFiles.txt"

then the file will get the actual execution output.
I tried:
dir "C:\Program Files\*.exe" /B /S /O:GNE 1 > "ExeList PgmFiles.txt" 0>&1

without success

A: You can sort of get this result by assigning the command to a variable, then echoing the variable into a file, then executing the variable and appending the output into the same file.
The variable that contains all passed parameters is %*.
Let's put this into a batchfile "doit.bat":
@echo off
echo %*
%*

You can now prefix your command with "doit.bat" like this:
doit dir "C:\Program Files\*.exe" /B /S /O:GNE > "ExeList PgmFiles.txt"

A: The numbers in 1> or 0>&1 have got the following meanings (consult the article Redirection to learn more):

*

*handle 0 points to STDIN, that is the console or keyboard input

*handle 1 points to STDOUT, that is the console or display output

*handle 2 points to STDERR, that is the error display output

So you cannot redirect 0 (STDIN) to get the executed command line written to the redirection target.
One possible way was to simply echo the command line in advance, escape any special characters and redirect to the same target file, like this (note the escape sequence ^>):
echo dir "C:\Program Files\*.exe" /B /S /O:GNE ^> "ExeList PgmFiles.txt" > "ExeList PgmFiles.txt"
dir "C:\Program Files\*.exe" /B /S /O:GNE >> "ExeList PgmFiles.txt"

But you may agree this is not quite elegant.
An alternative is to use the command echoes, which you can redirect together with the command output when you wrap around a for loop that iterates once only, like this:
(for %Z in (.) do dir "C:\Program Files\*.exe" /B /S /O:GNE) > "ExeList PgmFiles.txt"

The command echoes must of course be enabled (by typing @echo on, for instance), so the hosting cmd.exe instance must not have been started with the /Q option.
If you want to use the code in a batch-file, make sure to change %Z to %%Z.


text:
Q: LWC Dual list box setting the value getting Uncaught (in promise) TypeError: this.value.forEach is not a function Trying to set dual list box value getting below error **Uncaught (in promise) TypeError: this.value.forEach is not a function at ie.get computedSelectedList [as computedSelectedList]**
HTML

                  Rule

                  Notification Type

         <template for:each={getSchedulerDetails} for:item="it"
            for:index="index">

                     {it.rowNum}

                     {it.rule}

                     {it.notificationType}

                     <lightning-button-icon
                        data-id={it.recId}
                        data-schedulertype={it.schedulerType}
                        data-schedulerdate={it.schedulerDate}
                        data-schedulerwhen={it.schedulerWhen}
                        data-noofdate={it.noOfDate}
                        data-notificationtype={it.notificationType}
                        icon-name="utility:edit"
                        variant="brand"
                        alternative-text="edit"
                        onclick={handleonclickEditRuleModal}>
                     </lightning-button-icon>

                     <lightning-button-icon
                        icon-name="utility:delete"
                        data-id={it.recId} variant="brand"
                        alternative-text="delete"
                        onclick={handleonclickDeleteRuleModal}>
                     </lightning-button-icon>

         </template>

JS
handleonclickEditRuleModal(event) {
this.selectNotificationType = event.currentTarget.dataset.notificationtype;
        console.log(this.selectNotificationType);
}

Trying to add selectNotificationType value in the below dual listbox
<lightning-dual-listbox id="selectOptions" name="Select Options" label=" "
                                            source-label="Notification Types"
                                            selected-label="Selected Notification Types" value={selectNotificationType}
                                            options={notificationTypesOptions} onchange={handleChangeDualPicklist}>
                                        </lightning-dual-listbox>

APEX
    List <String> ptlist = new list <string>();
            if(sch.emitcs2__Notification_Type__c !=null){
                List<String> lstnotf = sch.emitcs2__Notification_Type__c.split(';');
                for(string pt: lstnotf ){
                    system.debug('pt' + pt);
                    ptlist.add(pt);
                }
                wrapper.notificationType = ptlist;
            }

Can you please help what I am doing wrong here.

A: You need to wait for the data to load. Something like this:
<lightning-dual-listbox if:true={selectNotificationType} ...

A: I had similar error.
Issue in my case was that the value was incorrect type as it was string instead of array. You should make sure that the variable that assign is an array
value={selectNotificationType}


text:
Q: Trying to insert data into mysql table, but it all ends up in one column I'm trying to insert data from a tsv file into a mysql table. The data is formatted like this:
ID            rate    votes
tt0000004     6.4     98

It is to be inserted into a table formatted like this:
CREATE TABLE mytable (ID VARCHAR(15), Average_Rating DOUBLE, Number_of_Votes INT, PRIMARY KEY(ID))

This is how I'm trying to insert it:
LOAD DATA LOCAL INFILE 'ratingshort.tsv'
INTO TABLE db1.mytable
FIELDS TERMINATED BY '\t';

However, when I view the table, it looks like this:
ID                            Average_Rating    Number_of_Votes
tt0000004     6.4     98      NULL              NULL

Does anyone know why it's only inserting itself into the first column and how I could fix this? Thanks!


text:
Q: Any hosting provider with scalability, unix, MySQL, managed server? I work for a company that runs several websites, most of them made with CakePHP (so lots of PHP and SQL). They are currently in a 1&1 shared unix hosting, and we're looking to move somewhere else.
We're looking for a solution that obviously allows us to move all those websites and create similar ones (so with PHP, MySQL database, unix...). We would like it to be easily scalable in terms of computing power, since right now we don't have a lot of users navigating the websites at the same time, but that could dramatically change during this year.
We don't have experience managing/maintaining servers, so we would need some sort of managed service (like a managed dedicated server maybe?).
We've been looking to Amazon's EC2, but it looks a little bit overkill for us, and since they don't provide any kind of managing service, it requires for us to hire some other company to do that, which for what I've seen so far increases the cost a lot.
Any advice on this topic would be much appreciated!

A: Rackspace provides managed hosting - http://www.rackspace.com/managed_hosting/

A: Since you don't have any experience managing servers, you should go with a regular web hosting.
If you want a scalable one, you can use Gandi Simple Hosting for example or Pagoda Box


text:
Q: JavaScript change input type="text" to type="file" So I have a code that is like this:
<script type="text/javascript">
function fundx() {
    var input = document.getElementById("id");
    var input2 = input.cloneNode(false);
    if (document.getElementById("butid").value == 'Upload') {
        input2.type = 'text';
        input.parentNode.replaceChild(input2, input);
        document.getElementById("butid").value = 'URL';
    } else {
        input2.type = 'file';
        input.parentNode.replaceChild(input2, input);
        document.getElementById("butid").value = 'Upload';
    }
}
</script>
<input id="id" type="text" name="id"  value="Upload" />
<input type="button" id="butid" value="Upload" onclick="fundx()" />

It is supposed to change the text field to a file upload field and vise versa.
The current code isn't working. Any ideas of what I should do to fix this?

A: The problem is with the cloning. You cannot change the type of an existing element, you can only set the type for a new element (once).
Try this
function fundx() {
    var input = document.getElementById("id");
    var input2 = document.createElement('input');
    input2.id = input.id;
    input2.name = input.name;
    input2.value = input.value;
    if (document.getElementById("butid").value == 'Upload') {
        input2.type = 'text';
        input.parentNode.replaceChild(input2, input);
        document.getElementById("butid").value = 'URL';
    } else {
        input2.type = 'file';
        input.parentNode.replaceChild(input2, input);
        document.getElementById("butid").value = 'Upload';
    }
}

Working example on jsbin


text:
Q: Generic type lost when using a nested interface I'm having trouble using generics with 'nested' interfaces and ReadonlyArray. How can I run the filterList function without losing the type for the list parameter?
interface INumber {
    value: number
}

interface IState {
    readonly numbers: ReadonlyArray<INumber>
}

var state: IState = {
    numbers: [{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }]
}

function filterList<T>(list: T) {
    return list.filter(x => x.value > 2);
}

// Error: Property 'filter' does not exist on type 'T'.
const res = filterList(state.numbers);

Changing the filterList function to the below will fail due to using ReadonlyArray.
function filterList(list: INumber[]) {...}

// Error: Argument of type 'ReadonlyArray<INumber>' is not assignable
// to parameter of type 'INumber[]'. Property 'pop' is missing in
// type 'ReadonlyArray<INumber>'.
const res = filterList(state.numbers);

Whats the best practice for handling this situation?
Thanks!

A: You have several choices. ReadonlyArray<T> si a subset of Array, so we can constain T to be a ReadonlyArray of something that has a value:
var state: IState = {
  numbers: [{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }]
}

function filterList<T extends ReadonlyArray<{value : number }>>(list: T){
  return list.filter(x => x.value > 2);
}

const res = filterList(state.numbers); // ok

var arr = [{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }]
const res2 = filterList(arr); //ok

Although you don't get much out of having the type parameter being the list, as filter will return a regular array for both ReadonlyArray and Array, so this will work as well:
function filterList<T extends {value : number }>(list: ReadonlyArray<T>){
  return list.filter(x => x.value > 2);
}
const res = filterList(state.numbers); // ok

var arr = [{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }]
const res2 = filterList(arr); //ok

If you want filterList to preserve whether a readonly array or a regular array was passed in, you can use the first version and return T, but you will need to use a type assertion to make the result of filter pe typed as a ReadonlyArray
function filterList<T extends ReadonlyArray<{value : number }>>(list: T): T{
  return list.filter(x => x.value > 2) as any;
}

const res = filterList(state.numbers); // ok, res is ReadonlyArray<INumber>

var arr = [{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }]
const res2 = filterList(arr); //ok, res s { value: number; }[]


text:
Q: Sub-Domain auto pointing So I am just starting on building a new application with codeigniter. What I am wanting to do is the following.
Have an auto-generated string stored in a database -- got this part covered.
// Auto Generated String
gc149354

Share the auto-generated string appended to my regular domain name in an email to a client -- got this part covered as well.
// Appended to the domain name
http://gc149354.mycoolurl.com

All this is pretty standard coding with php and codeigniter. But where it gets tricky is actually having that url http://gc149354.mycoolurl.com direct the user somewhere.
I want it to direct the client to a controller in codeigniter called newsite.php which is stored in controllers/new-site/newsite.php And the controller will handle everything from there.
I am imagining I will need something in .htaccess on the root of my directory. Maybe like so:
RewriteEngine On    # Turn on the rewriting engine

RewriteRule     (gc[0-9]+)/     /get-started    [NC]

Except that calls for mycoolurl.com/gc149354 and not gc149354.mycoolurl.com right?
So how can I route all sub-domains that start with gc follwed by 6 numbers 1-9 get routed to the getstarted controller in codeigniter?

A: Are you referring to something like:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(gc[0-9]+)\.mycoolurl\.com$ [NC]
RewriteRule ^/?$ /controllers/new-site/newsite.php?sub=%1 [L,QSA]

And the "sub" GET parameter will be given the subdomain string. Or, if your controller can look at the subdomain, you can just get rid of the ?sub=%1 part.


text:
Q: sailsjs - unexpected token for spread operator (...) So I downloaded sailsjs and using it to develop my API. All ES6 features work fine, but when I use the spread operator it throw an unexpected token error
const a = {test: 'test'};
const b = { something: 'something', ...a };

I am totally new to nodejs. If the answer to this is adding some packages (babel or something), then would appreciated some detailed explanation of steps for a newbie. And also, how would I deploy (I am using circleci) that extra build step?

A: Spread in object literals is currently not supported by nodejs, because it is a proposal. It works in the jsfiddle.net because it is supported by Chrome and Firefox, although it is marked as an error by the parser. For more info see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax


text:
Q: How to use a whitelist with grep I have a list of email addresses. I also have a list of common first and last names. I want to filter the email list against the one with common first and last names, thus only printing emails with either a common first and / or last name in the output file.
So, I tried:
cat file | egrep -e -i < whitelist | tee emails_with_common_first_and_last_names.txt

At first, this seemed like it was working. Then, after examining the output, it did not seem to do anything.
wc -l input output

This revealed that nothing was filtered.
So, how else can I do this or what am I doing incorrectly?
Here is a sample of the file that I would like filtered:
aynz@falskdf.com
8zlkhsdf0@fmail.com
afjsg@domain.com

Here is a sample of the whitelist that I would like to use as a reference to filer the file:
ALEX
johnson
WINTERS
miles
christina
tonya
jackson
schmidt
jake

So, if an email contains any of these, grep or whatever needs to print it to a output file.


text:
Q: Delete Query not working in MySQL from a form <form>
<input type='text' name='source' placeholder='source'/>
<input type='text' name='destination' placeholder='destination'/>
<input type='text' name='trainid' placeholder='trainid'/>
<input type='submit' name='deletetrainid'/>
</form>
<?php
if(isset($_POST['deleteTrain'])){
echo "ENTER TRAINID,SOURCE AND DESTINATION TO DELETE TRAIN ROUTE";
echo "<form action='adminPage.php' method='POST'><input type='text'
name='trainid'/>";
echo"<input type='text' name='source' placeholder='ENTER SOURCE'/>";
echo"<input type='text' name='destination' placeholder='ENTER
DESTINATION'/>";
echo"<input type='submit' name='deletetrainid'/>";
echo"</form>";
if (isset($_POST['deletetrainid'])) {
    $source = $_POST['source'];
    $destination = $_POST['destination'];
    $trainid =  $_POST['trainid'];
    $query = "DELETE FROM trains WHERE trainid=$trainid AND source=$source
    AND destination=$destination";
    $result = mysqli_query($connection, $query);
    if(!$result){
        die("QUERY FAILED". mysqli_error($connection));
    }
    else
    echo "Record Deleted";
    }
    }

On clicking the button having name=deletetrainid nothing happens and the input fields are shown empty be filled again. No data/row is deleted. Any help please?

A: Looking at your code I can see several things that could go wrong. SQL injection attacks being just one of them, like mentioned @Luca.
But well, I did my own version of your code, and here's what I could fix for you to get the information somewhere.
<form action='adminPage.php' method='POST'>
    <input type='text' name='source' placeholder='source'/>
    <input type='text' name='destination' placeholder='destination'/>
    <input type='text' name='trainid' placeholder='trainid'/>
    <input type='submit' value'Submit'/>
</form>
<?php
    if (isset($_POST)) {
        $source = $_POST['source'];
        $destination = $_POST['destination'];
        $trainid =  $_POST['trainid'];
        $query = "DELETE FROM
                      trains
                  WHERE
                      trainid=$trainid
                  AND
                      source='$source'
                  AND destination='$destination'";
        $result = mysqli_query($connection, $query);
        if(!$result){
            die("QUERY FAILED". mysqli_error($connection));
        }
        else
        echo "Record Deleted";
    } else {
        echo "Houston, we have a problem.";
    }

So, FIRST:
The information you expect on the first ISSET deleteTrain is not displayed anywhere, and not set anywhere, it would never trigger the form.
SECOND:
You don't need two forms, plus, only the second one had the method='POST' and action set, you could set that in the first one.. without this, you would only get the information by $_GET.
THIRD:
You forgot to put quotes on the text variables on the query. That wouldn't work since strings are required to be quoted.
You are bound to make mistakes (several of them, really), so don't let that pull you down.
Make use of things like: var_dump, get_defined_vars(), print|echo|print_r, die()...
Everything that can help you figure out what's happening with your code before you need to ask for help, so you can, at least, have a general idea of what's wrong and where.

A: In your form, you can't add attributes: action and method.
the value in action in your subject is "" and that of method is POST


text:
Q: Create user with install4j for linux installer I have a requirement where I am installing with sudo as I need root access for some actions.
I have to create couple of unix users with install4j and then use these users in systemd file to start a particular service.
I was not able to find any action for creating users. So I have used Run executable or batch file action to run a shell script for adding users and giving proper ownership using these users to certain directories.
I have 2 questions here :

*

*Is this approach good for creating users ? or any better approach is available

*If any of the command in shell script fails, installer can fail..but users are not aware of what went wrong.

Please pardon me , I am new to install4j

A: As of install4j 8, there is no elevation of privileges for Linux/Unix media files.
The recommendation is to run the entire installer with sudo, if elevated privileges are required.


text:
Q: Issue sending multipart/form-data I'm attempting to utilize BIMTrack's REST API to post an image. To do this the API requires me to send a json file with but prior to the image, inherently requiring multipart/form-data.
Failure post the json fill will be met with the error code: 415 and error message: The content-type of the first file of the request must be application\json.
I've successfully made this post request using the web debugging proxies of Postman & Fiddler but am unable to repeat my successes within python requests.
Python Code (This doesn't work) :
image = r"C:\Users\aflemming\Desktop\Images\DBMICon.png"
jsonFile = r"C:\Users\aflemming\source\repos\IfcOpenShell\IfcOpenShell\BIM\myjson.json"

headers = {'Authorization' : 'Bearer <MyToken>'}

files = {
    'Json': (None, open(jsonFile, 'rb'), 'application/json'),
    'Image': (None, open(image, 'rb'), 'image/png')
}

r = requests.post(https://api.bimtrackapp.co/v3/hubs/07La7cOZ/projects/20767/issues/3161484/viewpoints, files=files, headers=headers)

Fiddler Raw Request (This works) :
User-Agent:Fiddler Everywhere
Authorization:Bearer eb5e3983a7546dad76067418ff93175ef42b816dd57f78f54101f0b63862542e
Host:api.bimtrackapp.co
Content-Length:11322
Content-Type:multipart/form-data;boundary=-------------------------acebdf13572468

---------------------------acebdf13572468
Content-Disposition: form-data; name="description"
the_text_is_here
---------------------------acebdf13572468
Content-Disposition: form-data; name="jsonfile"; filename="myjson.json"
Content-Type: application/json

<@INCLUDE *C:\Users\aflemming\source\repos\IfcOpenShell\IfcOpenShell\BIM\myjson.json*@>
---------------------------acebdf13572468
Content-Disposition: form-data; name="image"; filename="DBMICon.png"
Content-Type: image/png

<@INCLUDE *C:\Users\aflemming\Desktop\Images\DBMICon.png*@>
---------------------------acebdf13572468--

Postman Request (This also works):

BIMTrack's REST API: https://api.bimtrackapp.co/swagger/ui/index
I'm happy to provide more information where required.

A: I found a solution by altering the request method (using requests.request over requests.post) and setting the verify=False parameter.
It seems as though the request was encountering an SSLCertVerificationError and bypassing the certificate resolved this.
Final Code:
image = r"C:\Users\aflemming\Desktop\Images\DBMICon.png"
jsonFile = r"C:\Users\aflemming\source\repos\IfcOpenShell\IfcOpenShell\BIM\myjson.json"
url = "https://api.bimtrackapp.co/v3/hubs/07La7cOZ/projects/20767/issues/3161484/viewpoints"

files = [
    ('Json', ('Json2', open(jsonFile,'rb'), 'application/json')),
    ('Image', ('Image2', open(image,'rb'), 'image/png'))
]

headers = {
    'Authorization': 'Bearer <MyToken>'
}

response = requests.request("POST", url, headers=headers, files = files, verify=False)


text:
Q: How to distribute a 200MB database to a locally executed HTML5 web page I am building a search tool that is designed to be run at my organization. My deployment strategy is:

*

*HTML5 web page that's stored on the file server.

*200MB JSON or JavaScript file that's in another file.

Right now the 200MB file is a .js file with statements like:
var data = {....};

Where {....} is about 200MB in size. This is working on Apple Safari on a Mac but it causes performance problems on Chrome. Firefox takes several minutes to load, but then it's fine. It seems like a memory problem.
Another option is to store it in a .json file and to load it with JQuery.
Is there a better way to do this?  The 200MB file contains several hundred thousand records.
EDIT YES, the entire database must be local, because I do not have a web server with backend logic.
ALSO, it is unclear to me at the moment if the 200MB object is better distributed as a JSON Object or as an Array.
EDIT I've now determined that I can't store it in a JSON object, because you can't use JQuery to read a file:// URL (even if the HTML comes from a file:// URL). So now my plan is to encode the 200MB file as 200,000 1K statements that insert the values into a {}.

A: You should read these articles:
https://www.html5rocks.com/en/tutorials/file/dndfiles/
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data
Also there isn't a really good choice of doing that, cause memory leak. I think isn't right choice.

A: I suggest you to store data in some database in this case.
Your search-tool must send input data from client's browser and then your server must return response in json format that you need. This is most common solution for big data

A: I have an answer. Instead of dumping a single JSON object, I dumped an empty object and then filled in the fields. Sort of like this:
var all_files = {};
all_files[".489454.padl"] = [3601335];
all_files[".bash_history"] = [3601336];
all_files[".bash_profile"] = [3601337, 4243581];
all_files[".bash_profile-anaconda.bak"] = [3601338];
all_files[".bashrc"] = [3601339, 4243582];
all_files[".CFUserTextEncoding"] = [3601340, 3953453, 3953467, 3953492, 3953506, 3953520, 3953534, 3953655, 3953669, 3953683, 3954184, 3954198, 3954212, 3954226, 3954240, 3954254, 3954268, 3954282, 3954298, 3954741, 3954755, 3954771, 3954786, 3954817, 3954833, 3954847, 3954863, 3954884, 3954898, 3954912, 3954928, 3955916, 3955930, 3955944, 3955958, 3955983, 3955997, 3956011, 3956025, 3956039, 3956055, 3956069, 3956083, 3956097, 3956111, 3956125, 3956139, 3956153, 3956167, 3956181, 3956195, 3956209, 3956223, 3956237, 3956257, 3956273, 3956287, 3956301, 3956328, 3956347, 3956361, 3956375, 3956393, 3956407, 3956421, 3956441, 3956457, 3956494, 3956508, 3956522, 3956541, 3956557, 3956574, 3956588, 3956602, 3956618, 3956632, 3956649, 3956665, 3956765, 3956779, 3956793, 3956808, 3956824, 3956838, 3966259, 3966273, 3966288, 3966308, 3966326, 3966340, 3966354, 3966369, 3966384, 3966402, 3966416, 3966432, 3966453, 3966469, 3966483, 3966497, 3966542, 3966556, 3966570, 3966584, 3966598, 3966612, 3966636, 3966652, 3966666, 3966682, 3966697, 3966711, 3966729, 3966756, 3966770, 3966784, 3966798, 3966812, 3966826, 3966887, 3966901, 3966917, 3966931, 3966947, 3966962, 3966977, 3966991, 3967008, 3967024, 3967041, 3967058, 3967072, 3967086, 3967100, 3967114, 3967129, 3967144, 3967158, 3967172, 3967186, 3967200, 3967214, 3967228, 3967242, 3967256, 3967270, 3967284, 3967298, 3967315, 3967332, 3967349, 3967366, 3967383, 3967400, 3967414, 3967432, 3967472, 3967494, 3967519, 3967539, 3967553, 3967567, 3967581, 3967596, 3967610, 3967627, 3967641, 3967655, 3967669, 3967686, 3967701, 3967715, 3967813, 3967835, 3967849, 3967863, 3967877, 3967891, 3967912, 3967926, 3967940, 3967954, 3967969, 3967983, 3967997, 3968179, 3968201, 3968216, 3968232, 3968375, 3968549, 3968563, 3968613, 3968725, 3968739, 3968754, 3968769, 3968783, 3968797, 3968812, 3969411, 3969425, 3969439, 3969453, 3969468, 3969482, 3969496, 3969510, 3969524];
all_files[".DS_Store"] = [3601341, 3601457, 3601614, 3601622, 3682878, 3682900, 3683109, 3683116, 3683131, 3683159, 3683837, 3683838, 3683864, 3685165, 3685689, 3686006, 3686154, 3686208, 3686658, 3686951, 3688568, 3691304, 3691654, 3691706, 3698223, 3702806, 3703841, 3705589, 3707517, 3709434, 3709601, 3712204, 3712575, 3713471, 3714040, 3723182, 3723186, 3723577, 3723619, 3723697, 3724289, 3724323, 3724354, 3724644, 3724666, 3724687, 3724711, 3724929, 3729720, 3729721, 3729808, 3729859, 3745259, 3745417, 3749212, 3749214, 3752731, 3754225, 3754282, 3754697, 3754725, 3758418, 3762019, 3762050, 3762076, 3762135, 3762484, 3764339, 3767112, 3767162, 3770129, 3770205, 3770401, 3782075, 3782082, 3782103, 3782110, 3782128, 3782144, 3782158, 3782227, 3782297, 3782335, 3782453, 3782531, 3782575, 3782681, 3782800, 3782843, 3782912, 3782939, 3782994, 3785013, 3785271, 3786663, 3787204, 3787259, 3787266, 3788923, 3790797, 3790803, 3790941, 3790974, 3791013, 3791036, 3791053, 3791056, 3791205, 3792915, 3793142, 3793522, 3793765, 3799643, 3799796, 3804461, 3804592, 3804679, 3804763, 3804843, 3804857, 3804863, 3804891, 3804983, 3805631, 3806138, 3806264, 3806518, 3807440, 3807461, 3807473, 3816174, 3832254, 3834259, 3834271, 3834289, 3834708, 3835089, 3835661, 3835780, 3836513, 3836635, 3836990, 3837258, 3837281, 3838040, 3842299, 3842361, 3842362, 3842443, 3843321, 3843712, 3844005, 3845137, 3845205, 3848494, 3848643, 3850301, 3851318, 3851539, 3851581, 3851586, 3851718, 3851749, 3855131, 3856267, 3856405, 3856600, 3856617, 3856733, 3856789, 3856825, 3857691, 3857694, 3857714, 3858011, 3858087, 3858201, 3858261, 3858427, 3858440, 3858451, 3858466, 3858484, 3858512, 3858518, 3858632, 3858647, 3859178, 3859226, 3859817, 3859860, 3860031, 3860078, 3862433, 3862466, 3862493, 3862556, 3862629, 3862669, 3862785, 3863120, 3863137, 3863143, 3863189, 3863190, 3863298, 3863402, 3863624, 3863912, 3863919, 3868043, 3868103, 3937674, 3937883, 3939101, 3953451, 3966103, 3966148, 3966208, 3971417, 3972095, 3972176, 4000541, 4001581, 4001584, 4013248, 4073121, 4097129, 4124083, 4140856, 4205726, 4208195, 4208198, 4219015, 4219018, 4219025, 4219165, 4220286, 4221936, 4221956, 4222034, 4222073, 4222114, 4222208, 4222241, 4222369, 4222372, 4222417, 4222458, 4222533, 4222554, 4222608, 4222677, 4222688, 4222706, 4222777, 4222893, 4222992, 4223033, 4223088, 4223161, 4243924, 4244119, 4244333, 4245043, 4245045, 4245051, 4245057];
all_files[".emacs"] = [3601342, 4243585];
all_files[".gitconfig"] = [3601343];
all_files[".iterm2_shell_integration.bash"] = [3601344];
all_files[".julia_history"] = [3601345];
all_files[".lesshst"] = [3601346];
all_files[".profile"] = [3601347, 4243588];
all_files[".python_history"] = [3601348];
all_files[".pythonhistory"] = [3601349];
all_files[".rnd"] = [3601350];
...

The whole file ends up being about 90MB (at the moment). Time to load on my 4-year-old MacBook Pro with Google Chrome is 502ms, which is completely reasonable.


text:
Q: How to use the Either type in C#? Zoran Horvat proposed the usage of the Either type to avoid null checks and to not forget to handle problems during the execution of an operation. Either is common in functional programming.
To illustrate its usage, Zoran shows an example similar to this:
void Main()
{
    var result = Operation();

    var str = result
        .MapLeft(failure => $"An error has ocurred {failure}")
        .Reduce(resource => resource.Data);

    Console.WriteLine(str);
}

Either<Failed, Resource> Operation()
{
    return new Right<Failed, Resource>(new Resource("Success"));
}

class Failed { }

class NotFound : Failed { }

class Resource
{
    public string Data { get; }

    public Resource(string data)
    {
        this.Data = data;
    }
}

public abstract class Either<TLeft, TRight>
{
    public abstract Either<TNewLeft, TRight>
        MapLeft<TNewLeft>(Func<TLeft, TNewLeft> mapping);

    public abstract Either<TLeft, TNewRight>
        MapRight<TNewRight>(Func<TRight, TNewRight> mapping);

    public abstract TLeft Reduce(Func<TRight, TLeft> mapping);
}

public class Left<TLeft, TRight> : Either<TLeft, TRight>
{
    TLeft Value { get; }

    public Left(TLeft value)
    {
        this.Value = value;
    }

    public override Either<TNewLeft, TRight> MapLeft<TNewLeft>(
        Func<TLeft, TNewLeft> mapping) =>
        new Left<TNewLeft, TRight>(mapping(this.Value));

    public override Either<TLeft, TNewRight> MapRight<TNewRight>(
        Func<TRight, TNewRight> mapping) =>
        new Left<TLeft, TNewRight>(this.Value);

    public override TLeft Reduce(Func<TRight, TLeft> mapping) =>
        this.Value;
}

public class Right<TLeft, TRight> : Either<TLeft, TRight>
{
    TRight Value { get; }

    public Right(TRight value)
    {
        this.Value = value;
    }

    public override Either<TNewLeft, TRight> MapLeft<TNewLeft>(
        Func<TLeft, TNewLeft> mapping) =>
        new Right<TNewLeft, TRight>(this.Value);

    public override Either<TLeft, TNewRight> MapRight<TNewRight>(
        Func<TRight, TNewRight> mapping) =>
        new Right<TLeft, TNewRight>(mapping(this.Value));

    public override TLeft Reduce(Func<TRight, TLeft> mapping) =>
        mapping(this.Value);
}

As you see, the Operation returns Either<Failture, Resource> that can later be used to form a single value without forgetting to handle the case in which the operation has failed. Notice that all the failures derive from the Failure class, in case there are several of them.
The problem with this approach is that consuming the value can be difficult.
I'm showcasing the complexity with a simple program:
void Main()
{
    var result = Evaluate();

    Console.WriteLine(result);
}

int Evaluate()
{
    var result = Op1() + Op2();

    return result;
}

int Op1()
{
    Throw.ExceptionRandomly("Op1 failed");

    return 1;
}

int Op2()
{
    Throw.ExceptionRandomly("Op2 failed");

    return 2;
}

class Throw
{
    static Random random = new Random();

    public static void ExceptionRandomly(string message)
    {
        if (random.Next(0, 3) == 0)
        {
            throw new InvalidOperationException(message);
        }
    }
}

Please, notice that this sample doesn't user the Either type at all, but the author himself told me that it's possible to do that.
Precisely, I would like to convert the sample above the Evaluation to use Either.
In other words, I want to convert my code to use Either and use it properly
NOTE
It makes sense to have a Failure class that contains the information about the eventual error and a Success class that contains the int value
Extra
It would be very interesting that a Failure could contain a summary of all the problems that may have occurred during the evaluation. This behavior would be awesome to give the caller more information about the failure. Not only the first failing operation, but also the subsequent failures. I think of compilers during a semantic analysis. I wouldn't want the stage to bail out on the first error it detects, but to gather all the problems for better experience.

A: Either Type Basics
Either type is coming from functional languages where exceptions are (rightfully) considered a side-effect, and therefore not appropriate to pass domain errors. Mind the difference between different kinds of errors: Some of them belong to domain, others don't. E.g. null reference exception or index out of bounds are not related to domain - they rather indicate a defect.
Either is defined as a generic type with two branches - success and failure: Either<TResult, TError>. It can appear in two forms, where it contains an object of TResult, or where it contains an object of TError. It cannot appear in both states at once, or in none of them. Therefore, if one possesses an Either instance, it either contains a successfully produced result, or contains an error object.
Either and Exceptions
Either type is replacing exceptions in those scenarios where exception would represent an event important to the domain. It doesn't replace exceptions in other scenarios, though.
Story about exceptions is a long one, spanning from unwanted side-effects to plain leaky abstractions. By the way, leaky abstractions are the reason why use of the throws keyword has faded over time in the Java language.
Either and Side Effects
It is equally interesting when it comes to side-effects, especially when combined with immutable types. In any language, functional, OOP or mixed (C#, Java, Python, included), programmers behave specifically when they know a certain type is immutable. For one thing, they sometimes tend to cache results - with full right! - which helps them avoid costly calls later, like operations that involve network calls or even database.
Caching can also be subtle, like using an in-memory object a couple of times before the operation ends. Now, if an immutable type has a separate channel for domain error results, then they will defeat the purpose of caching. Will the object we have be useful several times, or should we call the generating function every time we need its result? It is a tough question, where ignorance occasionally leads to defects in code.
Functional Either Type Implementation
That is where Either type comes to help. We can disregard its internal complexity, because it is a library type, and only focus on its API. Minimum Either type allows to:

*

*Map result to a different result, or result of a different type - useful to chain happy path transforms

*Handle an error, effectively turning failure into success - useful in the top level, e.g. when representing both success and failure as a HTTP response

*Transform one error into another - useful when passing layer boundaries (set of domain errors in one layer needs to be translated into set of domain errors of another layer)

The most obvious benefit from using Either is that functions that return it will explicitly state both channels over which they return a result. And, results will become stable, which means that we can freely cache them if we need so. On the other hand, binding operations on the Either type alone help avoid pollution in the rest of the code. Functions will never receive an Either, for one thing. They will be divided into those operating on a regular object (contained in the Success variant of Either), or those operating on domain error objects (contained in the Failed variant of Either). It is the binding operation on Either that chooses which of the functions will effectively be invoked. Consider the example:
var response = ReadUser(input) // returns Either<User, Error>
  .Map(FindProduct)            // returns Either<Product, Error>
  .Map(ReadTechnicalDetails)   // returns Either<ProductDetails, Error>
  .Map(View)                   // returns Either<HttpResponse, Error>
  .Handle(ErrorView);          // returns HttpResponse in either case

Signatures of all methods used is straight-forward, and none of them will receive the Either type. Those methods that can detect an error, are allowed to return Either. Those that don't, will just return a plain result.
Either<User, Error> ReadUser(input);
Product FindProduct(User);
Either<ProductDetails, Error> ReadTechnicalDetails(Product);
HttpResponse View(Product);
HttpResponse ErrorView(Product);

All these disparate methods can be bound to Either, which will choose whether to effectively call them, or to keep going with what it already contains. Basically, the Map operation would pass if called on Failed, and call the operation on Success.
That is the principle which lets us only code the happy path and handle the error in the moment when it becomes possible. In most cases, it will be impossible to handle error all the way until the top-most layer is reached. Application will normally "handle" error by turning it into an error response. That scenario is precisely where Either type shines, because no other code will ever notice that errors need to be handled.
Either Type in Practice
There are scenarios, like form validation, where multiple errors need to be collected along the route. For that scenario, Either type would contain List, not just an Error. Previously proposed Either.Map function would suffice in this scenario as well, only with a modification. Common Either<Result, Error>.Map(f) doesn't call f in Failed state. But Either<Result, List<Error>>.Map(f), where f returns Either<Result, Error> would still choose to call f, only to see if it returned an error and to append that error to the current list.
After this analysis, it is obvious that Either type is representing a programming principle, a pattern if you like, not a solution. If any application has some specific needs, and Either fits those needs, then implementation boils down to choosing appropriate bindings which would then be applied by the Either object to target objects. Programming with Either becomes declarative. It is the duty of the caller to declare which functions apply to positive and negative scenario, and the Either object will decide whether and which function to call at run time.
Simple Example
Consider a problem of calculating an arithmetic expression. Nodes are evaluated in-depth by a calculation function, which returns Either<Value, ArithmeticError>. Errors are like overflow, underflow, division by zero, etc. - typical domain errors. Implementing the calculator is then straight-forward: Define nodes, which can either be plain values or operations, and then implement some Evaluate function for each of them.
// Plain value node
class Value : Node
{
    private int content;
    ...
    Either<int, Error> Evaluate() => this.content;
}

// Division node
class Division : Node
{
    private Node left;
    private Node right;
    ...
    public Either<Value, ArithmeticError> Evaluate() =>
        this.left.Map(value => this.Evaluate(value));

    private Either<Value, ArithmeticError> Evaluate(int leftValue) =>
        this.right.Map(rightValue => rightValue == 0
            ? Either.Fail(new DivideByZero())
            : Either.Success(new Value(leftValue / rightValue));
}
...
// Consuming code
Node expression = ...;
string report = expression.Evaluate()
    .Map(result => $"Result = {result}")
    .Handle(error => $"ERROR: {error}");
Console.WriteLine(report);

This example demonstrates how evaluation can cause an arithmetic error to pop up at any point, and all nodes in the system would simply ignore it. Nodes will only evaluate their happy path, or generate an error themselves. Error will be considered for the first time only at the UI, when something needs to be displayed to the user.
Complex Example
In a more complicated arithmetic evaluator, one might want to see all errors, not just one. That problem requires customization on at least two accounts: (1) Either must contain a list of errors, and (2) New API must be added to combine two Either instances.
public Either<int, ArithErrorList> Combine(
    Either<int, ArithErrorList> a,
    Either<int, ArithErrorList> b,
    Func<int, int, Either<int, ArithErrorList>> map) =>
    a.Map(aValue => Combine(aValue, b, map);

private Either<int, ArithErrorList> Combine(
    int aValue,
    Either<int, ArithErrorList> b,
    Func<int, int, Either<int, ArithErrorList>> map) =>
    b.Map(bValue => map(aValue, bValue));  // retains b error list otherwise

private Either<int, ArithErrorList> Combine(
    ArithErrorList aError,
    Either<int, ArithErrorList> b,
    Func<int, int, Either<int, ArithErrorList>> map) =>
    b.MapError(bError => aError.Concat(bError))
        .Map(_ => bError);    // Either concatenate both errors, or just keep b error
...
// Operation implementation
class Divide : Node
{
    private Node left;
    private Node right;
    ...
    public Either<int, AirthErrorList> Evaluate() =>
        helper.Combine(left.Evaluate(), right.Evaluate(), this.Evaluate);

    private Either<int, ArithErrorList> Evaluate(int a, int b) =>
        b == 0 ? (ArithErrorList)new DivideByZero() : a / b;
}

In this implementation, the public Combine method is the entry point which can concatenate errors from two Either instances (if both are Failed), retain one list of errors (if only one is Failed), or call the mapping function (if both are Success). Note that even the last scenario, with both Either objects being Success, can eventually produce a Failed result!
Note to Implementers
It is important to note that Combine methods are library code. It is a general rule that cryptic, complex transforms must be hidden from the consuming code. It is only the plain and simple API that the consumer will ever see.
In that respect, the Combine method could be an extension method attached, for example, to the Either<TResult, List<TError>> or Either<TReuslt, ImmutableList<TError>> type, so that it becomes available (unobtrusively!) in those cases where errors can be combined. In all other cases, when error type is not a list, the Combine method would not be available.

A: For those that are still wondering, there are the Maybe and Result (AKA Either) types in this handy library by Vladimir Khorikov.
https://github.com/vkhorikov/CSharpFunctionalExtensions.
I'm posting this because it's ready to use, powerful and well designed.


text:
Q: How do I get this to work 3.2 "TFT 480x320? Help please. I am using STM32F401CCU board to connect to 3.2 "TFT 480x320. I can't get it to work, the display just glows white and nothing happens.
[http://imgs.elgrad.net/Upload/sub-4/21450.pdf]2
Main.c  ***************************************************************
#include "stm32f4xx.h"
#include "SPI.h"
int main(void)
{
SystemInit();

SPI_init();

while(1)
{
    SPI1_Write(0x34);
}

}
SPI.c ********************************************************************
#include "stm32f4xx.h"
#include "SPI.h"
void SPI_init(){
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;// Включаем тактирование портов А
RCC->APB2ENR |= RCC_APB2ENR_SPI1EN;// Включаем тактирование SPI 1
GPIOA->MODER |= GPIO_MODER_MODER5_1 | GPIO_MODER_MODER6_1 | GPIO_MODER_MODER7_1 |
GPIO_MODER_MODER4_0 | GPIO_MODER_MODER3_0 | GPIO_MODER_MODER2_0;
GPIOA->AFR[0] |= (5<<20);// AF7 на ноге CLK  - PA5
GPIOA->AFR[0] |= (5<<24);// AF7 на ноге MISO - PA6
GPIOA->AFR[0] |= (5<<28);// AF7 на ноге MOSI - PA7

GPIOA->ODR |= GPIO_ODR_ODR_2;//RS
GPIOA->ODR |= GPIO_ODR_ODR_3;//CS
GPIOA->ODR |= GPIO_ODR_ODR_4;//RESET

SPI1->CR1 |=  SPI_CR1_BR_2;// Скорость передачи fPCLK/32
SPI1->CR1 &= ~SPI_CR1_DFF;// Выбор размера передаваемых данных 8 бит
SPI1->CR1 &= ~SPI_CR1_SSM;
SPI1->CR1 |=  SPI_CR1_MSTR;
SPI1->CR1 &=  ~SPI_CR1_LSBFIRST;
SPI1->CR1 &= ~SPI_CR1_BIDIMODE;

SPI1->CR1 &= ~SPI_CR1_CPOL;
SPI1->CR1 &= ~SPI_CR1_CPHA;

SPI1->CR1 |=  SPI_CR1_SPE;

}
void SPI1_Write(uint16_t data){
while(!(SPI1->SR & SPI_SR_TXE));
SPI1->DR = data;
}

A: The datasheet of the display says it has a 16-bit parallel interface.
There is no way the display can be used via SPI interface.


text:
Q: I am not able to get google map through ReactJS This is my code for Map component which is not rendering the map.
I have my root component where I am calling this component.When I remove this Map component from root component then everything works.
 import React from "react";
    import {GoogleMapLoader, GoogleMap, Marker} from "react-google-maps";

    export class Maps extends React.Component{
        render()
        {
            const mapContainer =

            return(
                <GoogleMapLoader
                    containerElement={ mapContainer }
                    googleMapElement={
                        <GoogleMap
                            defaultZoom={15}
                            defaultCenter={this.props.center}
                            options={{streetViewControl:false, mapTypeControl:false}}>
                        </GoogleMap>
                    } />
                );
        }
    }

This is my html code which is displaying the map
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>

    <link rel="stylesheet" href="">

Error in console window of browser
Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `Maps`.
    at invariant (bundle.js:1916)
    at createFiberFromElement (bundle.js:22993)
    at reconcileSingleElement (bundle.js:24794)
    at reconcileChildFibers (bundle.js:24898)
    at reconcileChildrenAtExpirationTime (bundle.js:25022)
    at reconcileChildren (bundle.js:25013)
    at finishClassComponent (bundle.js:25149)
    at updateClassComponent (bundle.js:25121)
    at beginWork (bundle.js:25495)
    at performUnitOfWork (bundle.js:27486)

A: <GoogleMapLoader
    containerElement={ mapContainer }
    googleMapElement={ () =>
        <GoogleMap
            defaultZoom={15}
            defaultCenter={this.props.center}
            options={{streetViewControl:false, mapTypeControl:false}}>
        </GoogleMap>
    }
 />

You can't pass JSX to props, you must use a closure so that the JSX is interpreted.


text:
Q: Mac terminal writes these lines every time I build Jekyll site Every time I build my site with Jekyll through the terminal (Mac), everything works fine but theses lines show up:
[2013-02-21 16:17:38] INFO  WEBrick 1.3.1
[2013-02-21 16:17:38] INFO  ruby 1.8.7 (2012-02-08) [universal-darwin11.0]
[2013-02-21 16:18:38] INFO  WEBrick::HTTPServer#start: pid=897 port=4000

Then I'm unable to enter anything – the little grey square is displayed, but not the name of my computer followed by a semicolon as usual. If I want to type something again, I need to close/reopen the terminal window with this message:
"Closing this window will terminate the running processes: login, bash, ruby."
Please, note that I'm not a terminal stuff expert ;-)

A: What command are you using to build the site? What you see on those 3 lines is a local webserver that is running and serving your site. If you are running jekyll --server you'll get this webserver; open localhost:4000 in your browser and you'll see your site.
If you just want to generate the site, just run jekyll without the --server flag.
In the terminal you can cancel any running processes, such as the webserver, by pressing Ctrl-C. That way you don't need to close the window if you accidentally run the wrong command.


text:
Q: Create two dataframes from two dataframes based on multiindex in one dataframe and columns in another dataframe I m not sure if this has been answered before. But my requirement is that
I have a dataframe like this:
df1:
         A  B
I1 I2

x11 x12  a11 b11
x12 x22  a21 b21

Note that this has multiindex of [I1, I2] and columns [A, B]
and then another dataframe like this:
df2:
    I1   I2
  0  x11  x12
  1  y11  y12

This has columns [I1, I2] which is the same as multiindex of df1.
Now what I would like to create is two dataframes like below:
df3 which has rows for which the index in df1 matches to that of column values in df2
A  B
a11 b11

df4 with the remaining i.e.
A  B
a21 b21

I know how to do this using iterrows() but it is not efficient. Looking for a vectorized solution. Thanks.

A: Let us try reset_index with merge
df3=df1.reset_index().merge(df2).set_index(['I1','I2'])
df4=df1.drop(df3.index)

Or
idx=pd.MultiIndex.from_frame(df2)
df3=df1.reindex(idx).dropna()
df4=df1.drop(df3.index)

A: Just to record another way of doing it, posting this:
I could set_index on df2 with [I1, I2] and then do a isin like:
is_index_there = df1.index.isin(df2.set_index([I1, I2]).index)
and then use that to create separate dfs like :
df3 = df1.loc[is_index_there == True] and
df4 = df2.loc[is_index_there == False]


text:
Q: Why does Melosh not consider the term $\vec{v}\frac{dm}{dt}$ in Newton's second law for a meteorite that loses mass by ablation? While studying the dynamics of a meteorite entering the atmosfphere, the book "Impact Cratering - A geological Process" by H.J. Melosh considers the forces of drag, lift and gravity and compares their sum to $m\vec{a}$. This is okay if the mass of the meteorite is constant, but then he writes that, due to the process of ablation, th mass changes following this equation:
$$\frac{dm}{dt}=-\frac{C_H\rho Av}{2\xi}(v^2-v_{cr}^2)$$
where $v=|\vec{v}|$ and the other terms are constants depending on the shape and material of the meteorite and the density of the atmosphere.
My question is: if the mass changes during the motion, shouldn't we add a term $$\vec{v}\frac{dm}{dt}$$ to Newton's second law? And, if not, how do I know in which cases I must not consider that term even if mass is changing? (Why is ablation different from other ways the mass of an object changes?)

A: The equation $\vec{F}=\frac{d\vec{p}}{dt}$ cannot just blindly be applied to systems in which mass is entering or leaving the system. You have to consider how mass enters or leaves a system. For example, if the mass is being ejected in the opposite direction of $\vec{p}$ (a rocket) this will increase $\vec{p}$, while if the mass is being isotropically ejected this will decrease $\vec{p}$ (since the mass of the body decreases, but the speed does not). The equation $\vec{F}=m\frac{d\vec{v}}{dt}+\frac{dm}{dt}\vec{v}$ is simply not a true equation, and should not be applied. I would go so far as to call it a dangerous equation, because there are specific cases in which it is true and this often misleads students (and even occasional textbook authors!) to think it is a general rule.
The general rule for a variable mass system is
$$
\vec{F}+\vec{v}_{rel}\frac{dm}{dt}=m\frac{d\vec{v}}{dt}
$$
where $\vec{v}_{rel}$ is the relative velocity between the mass that is lost and the object you care about. Notice that if $\vec{v}_{rel}$ is opposite $\vec{v}$, it tends to increase $\vec{v}$, as in the case of a rocket. If $\vec{v}_{rel}=-\vec{v}$, we get the "dangerous" equation, which only holds in this case. Finally, in the case of meteor ablation, we have $\vec{v}_{rel}=0$, because the pieces falling off the meteor have the same initial speed as the meteor. Thus, we can ignore the $\frac{dm}{dt}$ term entirely.

A: I think you are right, but we should think about it like this:
$$\frac{d\vec{p}}{dt}=\vec{F}\rightarrow \frac{d(m\vec{v})}{dt}=\frac{dm}{dt}\vec{v}+m\frac{d\vec{v}}{dt}=\vec{F}$$
Assuming those forces do not depend on the mass, you should actually be subtracting that from the acceleration:
$$\frac{d\vec{v}}{dt}=\frac{F}{m(t)}-\frac{1}{m}\frac{dm}{dt}\vec{v}$$
But just to be clear, that $\vec{F}$ (which is net force, of course), is probably velocity-dependent as well (since the drag force is). So we are now solving some complicated differential equation, which is a polynomial in $\vec{v}$.
EDIT: To try and clarify and summarize what's wrong with this (my) answer. The relationship between Newton's laws and momentum relies on interactions transferring momentum. This makes sense in the case of objects either collecting mass (via interactions) or ejecting mass (via interactions). However, in the case of a meteorite, the prevailing model uses interactions that do not transfer momentum, at least not in the direction of motion. The model of a meteorite traveling through the atmosphere is to treat the solid rock as a collection of smaller rocks, traveling together but not interacting. The interaction of the atmosphere pulls rocks away from the clump (possibly transferring momentum in the longitudinal direction), but the rest of the meteorite "doesn't know anything about it". As long as this happens roughly evenly across the body of the asteroid, it's path remains approximately 1-dimensional.
In this way, $\vec{F}=\frac{d\vec{p}}{dt}$ can be applied consistently, as long as one carefully specifies how momentum is being transferred.
EDIT EDIT: Another answer with more detail on this consistency, and an article from EJP.


text:
Q: Is there any way to use "Find in Files" the way Visual Studio used to work? I just want to navigate to a root folder, specify the text string to find, specify the file types to search in, and see the results!!  Sounds so simple and it used to be!!! But, I am giving up with trying to figure out how to do such a simple friggin operation!!  Can someone please enlighten me??
So..  I would have included the version information the first time if it had seemed comprehensible to me.
Version: 1.58.2 (user setup)
Commit: c3f126316369cd610563c75b1b1725e0679adfb3
Date: 2021-07-14T22:10:15.214Z
Electron: 12.0.13
Chrome: 89.0.4389.128
Node.js: 14.16.0
V8: 8.9.255.25-electron.0
OS: Windows_NT x64 10.0.19042

What I am trying is selecting the menu command, Edit-> Find in Files.  A search pane is shown where it seems like the first field would be the text to search for - of course it doesn't say that and given how screwed up they have made this, maybe not??  The second field is "files to include" and the third field is "files to exclude".  As for what is happening?  I want to navigate to a folder on my C drive as my root folder and then search that folder and all sub-folders on . for the occurrence of a single string.  I can fill in the first field but no ideas on how to work through any others.  Thanks..


text:
Q: Saving a plot in Octave with a transparent background I've plotted some GPS tracks and heading vectors using Octave.
I'd like to overlay the plot on a satellite image, but when I save the plot it has a white background. Is there a way to save it with a transparent background?

A: I think using print with the "pngalpha" device does what you want, e.g.:
print(gcf,'-dpngalpha', 'myplot.png');

This is poorly documented unfortunately. I browsed the source code extensively to find a way to hack/patch octave to do this, only to find out this was already possible.


text:
Q: Good Site Builder I am currently working on a website and i kinda need something like a cms/site builder to be integrated int the site, but not very complicated.
for example let's say i have a few templates and the users can modify them as they please(add a picture, some text, etc)
Please help.
Thank you!

A: look at N2 if you are working in .Net  http://n2cms.com/

A: try joomla, drupal, or wordpress. There are also some basic wiki sites that are easy to setup and use like TWiki.

A: If you want to keep things very basic then SnippetMaster is an option. Your users can edit odd bits of text and even add pictures. It works best for sites with only a few pages to update. For a large site you may want to look at something more advanced.

A: You could use Joomla (PHP) or Windows SharePoint Services (.NET), but it depends what kind of thing you are really after...
Also, you could use something like VS Web Developer 2008 Express edition which'll create a basic template for you.

A: You can build a site these days with WordPress. Actually I recommend this even if you have more complicated stuff. There are a lot of plugins and themes and over all support. If you want something simple you can have it in minutes.

A: Here's an awesome link that I just happened to have someone send me yesterday:
Top 10 free content management systems for web site designers


text:
Q: Adding mysql driver to tomcat openshift I have deployed my war file on openshift tomcat.
As suggested to deploy war file directly we need to remove the src and pom.xml before coping the war file in webapps folder. pre compiled java applications (WAR and EAR files) onto your OpenShift
Now since my application uses mysql driver - when tomcat starts on open shift it throws error of mysql driver classses not found.
How else can I add the mysql driver to openshift tomcat. Putting them in the web-inf/lib directory does not work since the datasources are configured on tomcat context.xml


text:
Q: How to extract requires clause with two parameter packs into a concept? I have this (supposedly not so useful) class template with templated constructor which is a candidate for perfect forwarding. I, however, wanted to make sure that the types passed to the constructor are the exact same as the ones specified for the whole class (without cvref qualifiers):
template <typename... Ts>
struct foo {
    template <typename... CTs>
    requires (std::same_as<std::remove_cvref_t<Ts>, std::remove_cvref_t<CTs>> && ...)
    foo(CTs&& ...) {
        std::cout << "called with " << (sizeof...(CTs)) << " args\n";
    }
};

Now I can make:
auto f = foo<int, int>(1, 1);

and I can't make:
auto f = foo<float, int>(1, 1);

which is good.

But I wanted to extract the requires ... body to a concept:
template <typename... T1s, typename... T2s>
concept same_unqualified_types = (
        std::same_as<
                std::remove_cvref_t<T1s>,
                std::remove_cvref_t<T2s>
        > && ...
);

template <typename... Ts>
struct foo {
    template <typename... CTs>
    requires same_unqualified_types<Ts..., CTs...>
    foo(CTs&& ...) {                // 16
        std::cout << "called with " << (sizeof...(CTs)) << " args\n";
    }
};

int main() {
    auto f = foo<int, int>(1, 1);   // 22
}

But this gives me this error:

main.cpp: In function 'int main()':
main.cpp:22:32: error: no matching function for call to 'foo<int, int>::foo(int, int)'
22 |     auto f = foo<int, int>(1, 1);
   |
main.cpp:16:5: note: candidate: 'template<class ... CTs>  requires  same_unqualified_types<Ts ..., CTs ...> foo<Ts>::foo(CTs&& ...) [with CTs = {CTs ...}; Ts = {int, int}]'
16 |     foo(CTs&& ...) {
   |     ^~~
main.cpp:16:5: note:   template argument deduction/substitution failed:
main.cpp:16:5: note: constraints not satisfied
main.cpp: In substitution of 'template<class ... CTs>  requires  same_unqualified_types<Ts ..., CTs ...> foo<int, int>::foo(CTs&& ...) [with CTs = {int, int}]':
main.cpp:22:32:   required from here
main.cpp:5:9:   required for the satisfaction of 'same_unqualified_types<Ts ..., CTs ...>' [with CTs = {int, int}; Ts = {int, int}]
main.cpp:22:32: error: mismatched argument pack lengths while expanding 'same_as<typename std::remove_cvref<T1s>::type, typename std::remove_cvref<T2s>::type>'
22 |     auto f = foo<int, int>(1, 1);
   |

I suppose I might be doing something wrong with the concept same_unqualified_types where I'm trying to have two parameter packs. I've tried to test it manually, but it doesn't seem to work, even if I do same_unqualified_types<int, int> or same_unqualified_types<int, int, Pack...>, where Pack... is a parameter pack of two ints.
Where is my logic flawed? Can I extract that requires clause to a concept?
Disclaimer: I know I can achieve something similar with CTAD and deduction guides - without even needing any concepts. I just wish to know where my understanding is flawed.

A: Concepts don't get special privileges with regard to template parameter packs. You can't have two packs in a set of template parameters unless there's something to distinguish them in terms of the arguments passed to them (one could be a series of types while the other is a series of values, or you have access to template argument deduction to differentiate them, or something like that).
The best you're going to be able to do is to create an unqualified equivalent of same_as and just use that with pack expansion as needed:

template<typename T, typename U>
concept same_as_unqual = std::same_as<<std::remove_cvref_t<T>, <std::remove_cvref_t<U>>;

template <typename... Ts>
struct foo {
    template <typename... CTs>
    requires (same_as_unqual<Ts, CTs> && ...)
    ...

A single concept that does the pair-wise comparison between the parameters just isn't possible. Well, it's possible, but it'd be a lot more verbose, as you would likely need to bundle them in some kind of type-list. I don't think same_as_all<type_list<Ts...>, type_list<Us...>> is better than doing an explicit expansion.


text:
Q: Ada compiler chooses incorrect overloaded function

I am using avr-ada to compile my program. I want to right shift an unsigned_16 variable twice.
Interfaces.Shift_Right is overloaded and provides for both Unsigned_8 and Unisgned_16.
When I compile, I get the error 'expected type "Interfaces.Unsigned_8"', 'found type "Interfaces.Unsigned_16"'. I have tried to specify that the input is an Unsigned_16, but it won't work. How do I specify the correct function?
with AVR;                          use AVR;
with AVR.MCU;
with AVR.Timer0;
with AVR.ADC;
with Interfaces;
use Interfaces;
procedure Flash_Led is

   adc_result_10 : Unsigned_16 := 0;
   adc_result_8 : Unsigned_8 := 0;

begin
   -- set OC0A pin as output, required for output toggling
   MCU.DDRD_Bits := (others => DD_Output);
   -- set all pins low
   MCU.PortD := 16#00#;

   -- clear register
   MCU.TCCR0B := 16#00#;

   --  initialize timer to Clear Timer on Compare, scale the input
   --  clock and set a value to compare the timer against.
   Timer0.Init_CTC (Timer0.Scale_By_1024, Overflow => 1);

   --  Toggle the OC0(A)-Pin on compare match
   Timer0.Set_Output_Compare_Mode_Toggle;

   -- Initialize ADC
   ADC.Init(ADC.Scale_By_64, Ref => ADC.Is_Vcc);

   loop   -- loop forever
      adc_result_10 := ADC.Convert_10bit(Ch => 0);
      adc_result_10 := Shift_Right(Unsigned_16'(adc_result_10), 2); --'
      adc_result_8 := Unsigned_8(adc_result_10);
      Timer0.Set_Overflow_At(adc_result_10);
   end loop;
end Flash_Led;

A: The line:
Timer0.Set_Overflow_At(adc_result_10);

Should have been:
Timer0.Set_Overflow_At(adc_result_8);

I didn't look at the line number in the error message closely enough. Oops.

A: If you are unsure which function is being called (given that it is overloaded) you can always construct a unique name through renames...
function My16_Shift_Right (Item : in Unsigned_16; Amount : Natural) return Unsigned_16
    renames Interfaces.Shift_Right;

and then test the way you are thinking about your program.