text:
Q: Can I use run_time in Scheduled Query with New Big Query UI? I'm using BigQuery scheduled query in BigQuery Classic UI (old UI).
In the old UI, I was able to use as a Destination table: {run_time-15h|"%Y%m%d"}.
I would like to use {run_time} as a Destination table in the New BigQuery UI.
However, If I set {run_time|"%Y%m%d"} as Destination Table, the Schedule button disables.
SELECT *
FROM SOME_TABLE
WHERE
    _TABLE_SUFFIX = FORMAT_DATE(
        "%Y%m%d",
        DATE_SUB(
             DATE(@run_time,"Asia/Tokyo"),
             INTERVAL 1 DAY))

I'm using as destination table: page_{run_time-15h|"%Y%m%d"} and write preference: WRITE_TRUNCATE
How do I use {run_time} as Destination table in New BigQuery UI?


text:
Q: Checking for case insensitive parameters in flash/actionscript you can provide flashvars to the movie.
in actionscript you can access them like this:
var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;

then i can check a parameter like this:
if (paramObj["somekey"] == someValue)
{
}

now i want to make this check case-insensitive. so that it matches SomeKey or soMekEY, etc.
what is the best way to do this?

A: You could create a public (static) method that gets the parameters, given the param name, that converts the param name to lower case:
class Utility
{
    public static GetParam(name:String): String
    {
        if ( paramObj == null )
            paramObj = LoaderInfo(this.root.loaderInfo).parameters;

        var lowerCasedName:String  = name.toLowerCase();
        for (keyStr in paramObj)
        {
           if ( keyStr.toLowerCase() == lowerCasedName )
               return String(paramObj[keyStr]);
        }
        return null;
    }

    static var paramObj:Object = null;
}

You have no other option than scanning all the keys in the parameter object.

A: I faced this problem a few years ago when I was working with ColdFusion and Flash, because ColdFusion is case insensitive whereas AS3 is not.
So here's what I did to get around that problem.
public class ObjectUtil {

    public static function getParameter(obj:Object, name:String):Object {
        if(obj==null || name="" || name=="undefined") {
            return null;
        }

        for (var key:String in obj) {
            if(key.toLowerCase() == name.toLowerCase()) {
                return obj[key]
            }
        }
        return null;
    }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Accessing a Word(.docx) file's content with Microsoft Graph REST API? Is there a way to obtain the content of a Word document stored in the cloud through the Microsoft Graph API without having to download the file locally?
The goal is to build an app that analyzes a Word document's inner content and produce some interesting data from it. However after searching through Microsoft's Dev Center, Graph Explorer, and their API's documentation repository, I can't find any API endpoints that can serve me that data.
I can find some endpoints that deal with manipulating Excel's contents, but not one that deals with Word. Does Microsoft Graph not support retrieving a Word document's content?
EDIT: For example, I know I can read the contents of a "message" and even apply a search on it through query parameters, as demonstrated by one of Microsoft's samples. But I can't seem to find how to do this with Word documents.

A: Well, it's possible to download the content of the document.
See: Download the contents of a DriveItem.
For example:
GET /v1.0/me/drive/root:/some-folder/document.docx:/content

But you'll get the entire docx, with embedded images and all. Don't know if this is what you are looking for.

As an example, see the helix-word2md project that fetches a docx and converts it to markdown.

A: I'm afraid you can't direly access word content. What you can do is use web URL property of a DriveItem opening a document the associated Word Online or native world if it is installed.
You can use this below to show specific item or all items:
GET /users/{userId}/drive/items/{itemId}
GET me/drive/root/children/

This is the result below:
{
    "@microsoft.graph.downloadUrl": "",
    "createdDateTime": "2018-08-10T01:43:00Z",
    "eTag": "\"{00000000-3E94-4161-9B82-0000000},2\"",
    "id": "00000000IOJA4ONFB6MFAZXARX7L7RU4NV",
    "lastModifiedDateTime": "2018-08-10T01:43:00Z",
    "name": "daily check.docx",
    "webUrl": "https://xxxxxxx",
    "cTag": "\"c:{00000000-3E94-4161-9B82-37FAFF1A71B5},2\"",
    "size": 26330,
    "createdBy": {
        "user": {
            "email": "000000.onmicrosoft.com",
            "id": "000000-93dc-41b7-b89b-760c4128455a",
            "displayName": "Chris"
        }
    },
    "lastModifiedBy": {
        "user": {
            "email": "0000@0000.onmicrosoft.com",
            "id": "00000000-93dc-41b7-b89b-00000000",
            "displayName": "Chris"
        }
    },
    "parentReference": {
        "driveId":
   "b!000000000gdQMtns72t31yqWMhnFCjmCqO3tR5ypOf17NKl2USqo1bNqhOzrZ",
        "driveType": "business",
        "id": "00000VN6Y2GOVW7725BZO354PWSELRRZ",
        "path": "/drive/root:"
    },
    "file": {
        "mimeType": "application/vnd.openxmlformats-
   officedocument.wordprocessingml.document",
        "hashes": {
            "quickXorHash": "OSOK7r2hIVSeY1+FjaCnlOxn2p8="
        }
    },
    "fileSystemInfo": {
        "createdDateTime": "2018-08-10T01:43:00Z",
        "lastModifiedDateTime": "2018-08-10T01:43:00Z"
    }
}


text:
Q: Cast generics based on condition I am trying to return derived class, but for some implementations I have to provide a little bit more setup, so I have if, but the compiler is not smart enough to know that once it enters the if, it should be able to cast T to Derived1. Is there any other way to do it?

Cannot convert type 'Derived1' to type T

public T GetData<T>(string name) where T : Data
{
    if (_cache.ContainsKey(name))
        return (T)_cache[name];

    using (var db = new LiteDatabase(_dbPath))
    {
        if (typeof(T) is ChartData)
        {
            var collection = db.GetCollection<ChartData>("Data");
            var chunksColl = db.GetCollection<ValuesChunk>(nameof(ValuesChunk));

            var data = collection.Include(d => d.Series).FindOne(Query.EQ(nameof(ChartData.Name), name));
            foreach (var series in data.Series)
            {
                for (int index = 0; index < series.Chunks.Count; index++)
                {
                    var chunk = chunksColl.FindById(series.Chunks[index].ChunkId);
                    series.ChangeChunk(index, chunk);
                }
            }

            _cache.Add(name, data);
            return (Data)data;
        }
        else
        {
            var collection = db.GetCollection<T>();
            return collection.FindOne(Query.EQ(nameof(ChartData.Name), name));
        }
    }
}

public abstract class Data {/*properties*/}
public class ChartData : Data {/*properties*/}
public class ScriptData : Data {/*properties*/}

A: Couple of mistakes in the above, this works (whether its the best design is a different question):
public T Get<T>() where T : Base
{
    if (typeof(T) == typeof(Derived1)) //correction to this line
    {
        var derived = new Derived1();
        derived.Property1 = 5;
        return derived as T; //correction to this line
    }
    else
    {
        // return (T)myMethod;
    }

    return null;
}

or with your edited version:
public T GetData<T>(string name) where T : Data
{
    if (_cache.ContainsKey(name))
        return (T)_cache[name];

    using (var db = new LiteDatabase(_dbPath))
    {
        if (typeof(T) == typeof( ChartData)) //<======CORRECTION HERE
        {
            var collection = db.GetCollection<ChartData>("Data");
            var chunksColl = db.GetCollection<ValuesChunk>(nameof(ValuesChunk));

            var data = collection.Include(d => d.Series).FindOne(Query.EQ(nameof(ChartData.Name), name));
            foreach (var series in data.Series)
            {
                for (int index = 0; index < series.Chunks.Count; index++)
                {
                    var chunk = chunksColl.FindById(series.Chunks[index].ChunkId);
                    series.ChangeChunk(index, chunk);
                }
            }

            _cache.Add(name, data);
            return data as Data;//<======CORRECTION HERE
        }
        else
        {
            var collection = db.GetCollection<T>();
            return collection.FindOne(Query.EQ(nameof(ChartData.Name), name));
        }
    }
}


text:
Q: how can rename file upload name after adding it it wwwroot folder and keep also old name i craeted file upload control with angular and asp.net core and i need to rename upload file name before adding it in wwwroot to solve problem when user upload another file with the same name
but i found that FileName proberty readonly in angualr and asp.net core also
angular code
  upload() {
    let selectedFile = this.uploader.queue.find(s => s.id == id);
    if (selectedFile) {
      const formData = new FormData();
      formData.append(selectedFile.file.name, selectedFile.file);
      const uploadReq = this.uploadSrv.HTTPRequestServ(
        "POST",
        this.pathAPI + `api/Upload/upload`,
        formData
      );

      this.mySubscription = this.http.request(uploadReq).subscribe(event => {
        debugger;

      });
    }
  }

asp.net core code
 public ActionResult upload()
        {
            try
            {
                var file = Request.Form.Files[0];
                string folderName = "Upload";
                string webRootPath = _hostingEnvironment.WebRootPath;

                string newPath = Path.Combine(webRootPath, folderName);
                if (!Directory.Exists(newPath))
                {
                    Directory.CreateDirectory(newPath);
                }

                if (file.Length > 0)
                {

                    string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    string fullPath = Path.Combine(newPath, fileName);

                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);

                    }
                }

                return Json("Upload Successful.");
            }
            catch (Exception ex)
            {
                return Json("Upload Failed: " + ex.Message);
            }
        }

A: In your ASP.NET Core code, you should change the name when copying the file:
using (var stream = new FileStream(Path.Combine(newPath, "<my_file_name>"), FileMode.Create)
{
    file.CopyTo(stream);
}


text:
Q: How to add icon to autocomplete in PrimeVue I've run into this issue. There is a feature request for this at the moment.
I've provided my workaround in the answer below.

A: Anyone looking for alternatives can either add a placeholder value to the Autocomplete with emojis as 'icons'
Option 1
<AutoComplete
  class="inputSearch"
  id="artist"
  v-model="selectedArtist"
  :suggestions="filteredArtists"
  @complete="searchArtist($event)"
  placeholder=" Search Artist"
>
</AutoComplete>

Option 2 (better)
OR use this method where you add icons as a background image and indent the text away from it. You can remove the focus from the example if you want to keep the icon.
If you have primeicons imported, you can put the path to your desired icon in the url section of background-image. Additionally, you can add
background-size: 0.8em;
background-position: left;

under the input in the CSS with your desired values to position and size the icon.
Final CSS in my case looks like this:
.inputSearch input {
  background-image: url("../../node_modules/primeicons/raw-svg/search.svg");
  background-size: 0.8em;
  background-position: left;
  background-repeat: no-repeat;
  text-indent: 20px;
}

If you inspect the Autocomplete in a browser, you'll see an input wrapped in a span. That's why this works. I may copy those icons to my public folder later on. Not ideal, but a workaround for now.

A: I don't have enough reputation to upvote/comment on the answer above - it inspired me to make a few tweaks in order to add an icon to PrimeVue's Autocomplete
Result: Image of Autocomplete with icon
I changed the background-position to be located at a more specific position. I also targeted the p-autocomplete-input class.

.p-autocomplete-input {
  background-image: url("../../node_modules/primeicons/raw-svg/search.svg");
  background-size: 1.5em;
  background-position: left 10px top 17px;
  background-repeat: no-repeat;
  text-indent: 30px;
  padding: 20px;
  width: 350px;
}
    <AutoComplete
      type="text"
      v-model="searchQuery"
      @input="search"
      placeholder="Search for an Address"
      :scrollHeight="'300'"
    />

A: I came up with another workaround which uses PrimeVue's inbuilt CSS class to add icon in a normal InputText.
<span class="p-input-icon-right">
    <AutoComplete placeholder="Search here..." loadingIcon=null></AutoComplete>
    <i class="pi pi-search" />
</span>

I am setting loadingIcon as null for this workaround to prevent icons overlapping.
Here is the output (my custom style attributes applied):


text: Q: Serial to USB adapter for thermal receipt printer PC won't recognize device I have a WASP RP-300 Thermal Receipt Printer and purchased a Serial to USB adapter for a Windows 7 PC. It only appears to register the adapter and when it installed it stated, "Your Device is Ready to USE (USB Printing Support -Ready to use, No Printer Attached -Ready to use)", but the printer is nowhere to be found. What do I need to do?Dialog after installation


text:
Q: How to figure out which of three equations: $y=-2x+1, y=2x+1, y=x+1$ is linearly dependent on the others? I have three equations:
$$y=-2x+1$$
$$y=2x+1$$
$$y=x+1$$
I am trying to see which of these is linearly dependent on the others. Normally I can just eyeball it, but here it is very hard to see. Does anyone know a general method to see which equation is causing the linear dependency? thanks!

A: In truth, a set of equations itself is linearly (in)dependent; not some equation is linearly dependent on another one, although this is a common linguistic abuse.
As others have said, any two equations from your set of three form a linearly independent (sub)set, but the three of them form a linearly dependent set. There's no particular one that depends on the others.

A: The problem is that the system of equations is inconsistent in this case. Solving the first two equations, we get y = 1, x = 0, but that is obviously not what the last equation wants.
There is no way you can construct the linear dependency in this case.

A: Add $3/4$ times the second to $1/4$ times the first and you get the third. So in that sense, the third depends on the first two.
But add $-3$ times the second to $4$ times the third and you get the first. So in that sense, the first depends on the latter two.
Similarly, there is a way to express the middle one as "depending" on the first and last.
So it's not about "which one" depends on the other two. As a whole, the set is a "dependent" set.


text:
Q: What does "Quick Launch" and "Start Menu" shortcut in installation wizards translate to in Windows 8.x? Most installation wizards for Windows programs have the options for defining installation path, file type associations, and creating shortcuts. Shortcuts can be created on the desktop, on the start menu, and on the quick launch. However, in Windows 8.x there is no traditional start menu, and there is no quick launch on the Taskbar. See example below.

So what does it mean to create a "start menu shortcut" and a "quick launch shortcut" in a Windows 8.x environment? Are these options doing anything useful?

A: Quick Launch is the lower Bar with Startorb, open windows, Trayicons, Clock. Quick Launch is normally right of the Startbutton (if enabled). For me a quicklaunch exists on Windows 8.
If the icon is not added as a tile in the Metro Interface it will be added in the Menu which you see after clicking right on a blank area inside metro. In the lower right corner an icon will pop up "all apps".

A: This is what a clean version of Windows 8.1 with Update 1 looks like and behaves like. I will use the Adobe Digital Editions program as an example.
Desktop Shortcut

Showing Start button in the left corner, and desktop shortcut to Adobe DE.
Creating shortcuts on the desktop works the same way here as in old versions of Windows. A new shortcut is created on the desktop when the installation is complete.
Start Menu Shortcuts

After installing Adobe Digital Editions, I got the desktop shortcut and icon. I didn't get any Quick Launch icon, even though I selected to create one. I also got two sets of icons on Start Screen.

One icon here...

... another two here.
I'm not sure why they split up like this. I would have expected them to be grouped together. Does this mean that the first one is a Windows 8 "app" while the other two in the "Adobe" group are classic Windows programs? Anyway! This is what it means to create a "start menu shortcut" in Windows 8. These are all found in the all apps list.
In Windows 8.1 and 8.1 Update 1 you access this list by clicking on an arrow button in the lower right corner on Start Screen. In Windows 8.0 you right click on an empty space on Start Screen, and from the App Bar that appears on the bottom you click on "All apps".
That's all the icons I have for Adobe DE now. There was nothing added to the Start Screen, no tiles. And no Quick Launch icons. Now that I think about it, since Quick Launch has been removed in Windows 8.x the option "create quick launch shortcut" should translate to creating a tile on the Start Screen... no?
Update! This grouping and sorting behavior of apps and programs can be changed by clicking next to the "Apps" header where it says "by name" and changing it to "by category. I like it better this way. Also! This list includes both Windows apps and Windows programs (even though it's collectively called "apps"). And it appears that only true apps (not programs) will have a tile on the Start Screen.
Quick Launch Shortcut

At first, creating Quick Launch shortcuts in Windows 8 doesn't appear to be doing anything. It does, but it's not made apparent because Quick Launch toolbar has been removed from Taskbar. What it does is, it creates a shortcut in the following location.
%appdata%\Microsoft\Internet Explorer\Quick Launch

The shortcut is created, but since there is no Quick Launch toolbar, it adds no value in Windows 8 environments. Save 1–5 kB by choosing not to create it in Windows 8.


text:
Q: pandas.io.data get_data_yahoo ^DJI retrieval error I am using Python 2.7.3 in Snow Leopard with the currently (April 2 2013) newest version of pandas 0.10.1
I am trying to use the pandas Yahoo finance API to get stock values (the date in the query is not important here).
This works :
import pandas.io.data as web

GOOG = web.get_data_yahoo('GOOG', '8/19/2004')

This does not :
import pandas.io.data as web

DJI = web.get_data_yahoo('^DJI', '8/19/2004')

The ^ seems to be the problem.  Yahoo finance replaces the ^ with %5E or maybe @%5E.  I've tried directly substituting these with no success.  I also found this commit from 2 months ago, which seems to address this on line 232.  I had a look at my own pandas/io/data.py and it isn't quite the same and it does not mention this is issue.
Is there an easy solution to use the API?
I suppose I could use Beautiful Soup or something myself and jam the result into a DataFrame but I'd much prefer to find a way to use the API as it keeps it clean and the work is already done.

A: I think the problem is the source of data is missing. For example, the source for GOOG is http://ichart.yahoo.com/table.csv?s=GOOG, it seems ok. Also, some symbols with "^" are also works, for example, http://ichart.yahoo.com/table.csv?s=%5ETWII also works. However, http://ichart.yahoo.com/table.csv?s=%5EDJI doesn't work. Note that "^" will be encoded as %5e
And, what the link is broken? Probably you can find some answers here


text:
Q: Realm + Xamarin Forms Update Query I'm using Realm + Xamarin Forms to do what I figure is about the most basic operation possible: a list view shows a collection of items, with a search bar filtering the results as the user types.
I have a get only collection property used as the list view's items source, initially populated from a Realm query, and this gets updated automatically with any changes to data, but I can't figure out how to update the search text without adding a set and literally replacing the entire collection.
This is very inefficient--I assume this is triggering re-registration of a bunch of notify-changed event listeners for the collection and each item in it and generally causing mass chaos with each letter tapped.
In the past I've created my own wrapping observable collection with a search method to handle this and I suppose that is an option here as well, but is there any way to do this with Realm? That is, to update the query without recreating the entire collection, some way to re-run the original query?

A: Update: This technique not longer works.

*

*https://github.com/realm/realm-dotnet/issues/1569
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

...it also differs from the behavior of LINQ to Objects, where every iteration will reevaluate expressions, meaning that changes to both sides of a condition will affect the result. A Realm query will evaluate the right-hand sides of the conditions on the first run.

When you construct a query that contains Where parameters that are based upon non-Realm based conditions the query results do not update when those variable/parameters are changed unless you update/execute the query again.

Realm queries are live, in the sense that they will continue to represent the current state of the database.

So what I do is to create a filter class (RealmObject), then if you instance a "filter object", save it to Realm, you can base your Linq's Where parameters upon one or more of the "filter" properties. Updating this RealmObject filter via Realm.Add(filterObject, true) your queries based upon that object are also updated

Realm queries are live, in the sense that they will continue to represent the current state of the database.

The results are lighting fast filtering that works great in any UI Search routine.
Example Model:
public class ARealmClass : RealmObject
{
    public int Key { get; set; }
    public string KeyString { get; set; }
}

public class ARealmClassFilter : RealmObject
{
    [PrimaryKey]
    public int Key { get; set; }
    public int FilterKeyBy { get; set; }
}

Populate a Realm with some test data
var realm = Realm.GetInstance();
var all = realm.All<ARealmClass>();
if (all.Count() == 0)
{
    realm.Write(() =>
    {
        for (int i = 0; i < 1000; i++)
        {
            var obj = new ARealmClass { Key = i, KeyString = i.ToString() };
            realm.Add(obj);
        }
    });
}

Dynamic Live Query Example:
var realm = Realm.GetInstance();
var all = realm.All<ARealmClass>();
Console.WriteLine(all.Count());
var filterItem = new ARealmClassFilter { Key = 1, FilterKeyBy = 500 };
realm.Write(() =>
{
    realm.Add(filterItem);
});
var filtered = all.Where(_ => _.Key > filterItem.FilterKeyBy);
Console.WriteLine(filtered.Count());
realm.Write(() =>
{
    filterItem.FilterKeyBy = 750;
    realm.Add(filterItem, true);
});
Console.WriteLine(filtered.Count());

Output:
2017-04-24 11:53:20.376 ios_build_foo[24496:3239020] 1000
2017-04-24 11:53:20.423 ios_build_foo[24496:3239020] 499
2017-04-24 11:53:20.425 ios_build_foo[24496:3239020] 249

Note: Quoted text @ https://realm.io/docs/xamarin/latest/api/linqsupport.html


text:
Q: Having Trouble using For Loops to make two triangles of different characters fit into a rectangle? Examples of input:
3

4

Examples of output (assume that spaces = new lines.)
QQQH
QQHH
QHHH

QQQQH
QQQHH
QQHHH
QHHHH

So far, the fragment of code that attempts to print this is (Assume that all variables are pre-defined):
public int getSize()
{
    for (int i = size; i > 0; i--){
        for (int j = 1; j < size; j++){
            out.print("Q");
            out.print("H");
        }
        out.println("");
    }
    return 0;
}

It just prints: (assume that spaces = new lines.)
QHQHQHQHQH
QHQHQHQHQH
QHQHQHQHQH
QHQHQHQHQH
QHQHQHQHQH

For input of 5. I'm not quite sure how to make it print only the number of times of its respective integer value. Can someone explain?

A: You could break the inner loop it two, like this:
    for (int i = size; i > 0; i--) {
        for (int j = 0; j < i; j++) {
            out.print("Q");
        }
        for (int j = i; j < size + 1; j++) {
            out.print("H");
        }
        out.println();
    }

Output:
QQQH
QQHH
QHHH

QQQQH
QQQHH
QQHHH
QHHHH

Or if you don't want to break the loop, you can use the ternary operator:
for (int i = size; i > 0; i--) {
    for (int j = 0; j < size + 1; j++) {
        out.print(j < i ? 'Q' : 'H');
    }
    out.println();
}

A: try this code block instead:
int j=0;
for (int i = size; i > 0; i--)
{
    j=0;
    while(j < i)
    {
        out.print("Q");
        j++;
    }
    j=i;
    while(j < size+ 1)
    {
        out.print("H");
        j++;
    }
    out.println();
}

A: Try this
for (int i = 0; i < size; i++) {
 for (int j = 1; j <= size-i; j++) {
   System.out.print("Q");
 }
 for (int k = 0; k <= i; k++) {
   System.out.print("H");
 }
 System.out.println("");
}

A: Tested with sample inputs. Working fine
public int getSize() {
    for (int i = 1; i < size+1; i++) {
        for (int j = 0; j < size+1; j++) {
            int Qtimes = size-i;
            if(j <= Qtimes) {
                System.out.print("Q");
            } else{
                System.out.print("H");
            }
        }
        System.out.println("");
    }
    return 0;
}

A: This works if the input is 4 - for example -change it to any number
public int getSize()
{
    int cnt = 0;
    int i,j,k = 0;

    for ( i = 4; i > 0; i--){

        for ( j = 0; j < i; j++){

        System.out.print("Q");

        }
        cnt ++;
        for( k = 0 ; k <cnt ; k++) {
            System.out.print("H");
        }

        System.out.println("");

    }

    return 0;
}

output is
QQQQH
QQQHH
QQHHH
QHHHH


text:
Q: Why the controller response are setting model field names into lower case? In my .NET Core project, in the response of all controllers, the object fields are coming in lower case in the first one or two letters of the field name:
{
  "iD_PARAM": "foo",
  "cD_PROM": "bar",
  "txT_OFFICER": "lorem",
  "cN_NEW_PARAM": "fubá",
  "iD_SITUATION": "XX",
  "iD_NEW_USER": "ipsun",
}

It's strange, because the model has all fields in UPPER case:
public partial class MyModel {
   public long ID_PARAM { get; set; }
   public long CD_PROM { get; set; }
   public string TXT_OFFICER { get; set; }
   public int CN_NEW_PARAM { get; set; }
   public int ID_SITUATION { get; set; }
   public int ID_NEW_USER { get; set; }
}

For more detail, this is the controller where I set the values and the response:
[HttpPost("receive")]

    public async Task<IActionResult> Get()
    {
      try
      {
        MyModel newParam = new MyModel ();

        newParam.ID_PARAM = "foo";
        newParam.CD_PROM = "foo";
        newParam.TXT_OFFICER = "lorem";
        newParam.CN_NEW_PARAM = "fubá";
        newParam.ID_SITUATION = "XX";
        newParam.ID_NEW_USER = "ipsun";

        return Ok(newParam);
      }
      catch (Exception ex)
      {
        return BadRequest(ex);
      }
    }

A: Assuming you are using Newtonsoft Json, if you want your Json properties to be uppercase, try decorating your Model with JsonProperty like this to prevent the Serializer try to infer the property name :
public partial class MyModel {
  [JsonProperty("ID_PARAM")]
  public long ID_PARAM { get; set; }
  [JsonProperty("CD_PROM")]
  public long CD_PROM { get; set; }
  [JsonProperty("TXT_OFFICER")]
  public string TXT_OFFICER { get; set; }
  [JsonProperty("CN_NEW_PARAM")]
  public int CN_NEW_PARAM { get; set; }
  [JsonProperty("ID_SITUATION")]
  public int ID_SITUATION { get; set; }
  [JsonProperty("ID_NEW_USER")]
  public int ID_NEW_USER { get; set; }
}

A: You should change the ContractResolver, just add below code in startup ConfigurSservices
services.AddMvc().AddJsonOptions(options =>
        {
            options.SerializerSettings.ContractResolver = new DefaultContractResolver();
        });

Refer to Lowercase property names from Json() in .Net core


text:
Q: Why do we only time-evolve one operator in the Lieb-Robinson bound? Background
The Lieb-Robinson bound is said to provide some notion of causality in  non-relativistic quantum systems with bounded local interactions. Formally, it can be stated as follows.

Theorem (Lieb-Robinson): Consider a $k$-local Hamiltonian $H = \sum_{Z} h_{Z}$, where the sum runs over subsets $Z$ of qudits. Assume there exist constants $\mu, s > 0$ such that, for all qudits $i$, we can bound the interaction strengths as $\sum_{Z \ni i} \lVert h_{Z} \rVert \leq s e^{-\mu}$, where $\lVert \cdot \rVert$ is the operator norm. Now consider operators $A_{X}$ and $B_{Y}$ which are supported on subsets $X$ and $Y$ of qudits respectively. Define the time-evolved operator $A_{X}(t) = U^{\dagger}(t) A_{X} U(t)$, where $U(t) = \exp(-i H t)$. Then we have the following bound:
$$\lVert \left[ A_{X}(t) , B_{Y} \right] \rVert \leq 2 \lVert A_{X} \rVert \lVert B_{Y} \rVert \min\left\{|X|, |Y|\right\} e^{-\mu (d_{H}(X,Y) - v_{LR} t)},
$$
where $d_{H}(X,Y)$ is the interaction distance between subsets $X$ and $Y$, and $v_{LR} = 2 k s / \mu$ is the Lieb-Robinson velocity.

This is said to capture the notion of causality because the appearance of the $e^{-\mu (d_{H}(X,Y) - v_{LR} t)}$ factor shows that the commutator $\left[ A_{X}(t) , B_{Y} \right]$ dies off exponentially outside the "lightcone" defined by $d_{H}(X,Y) - v_{LR} t \leq 0$.
Motivation for question
My question is essentially about why it is natural to consider the quantity $\left[ A_{X}(t) , B_{Y} \right]$ where only one-operator is time-evolved, rather than $\left[ A_{X}(t) , B_{Y}(t) \right]$ where both operators are evaluated at the same time. Intuitively, the latter seems more natural to me, since it seems like it should capture something about the behaviour of the overlap of these operators as they evolve in time. However, it fails to do so, as the following argument shows.
Suppose the subsets $X$ and $Y$ are disjoint, so initially $\left[ A_{X}, B_{Y} \right] = 0$. Then notice that
$$
\left[ A_{X}(t) , B_{Y}(t) \right] = \left[ U^{\dagger}(t) A_{X} U(t) \,,\, U^{\dagger}(t) B_{Y} U(t) \right] = U^{\dagger}(t) \left[ A_{X}, B_{Y} \right] U(t) = 0,
$$
so if the operators initially commute, they also commute at later times.
Generically, for arbitrary $t > 0$ the operators $A_{X}(t)$ and $B_{Y}(t)$ will have support on the whole Hilbert space, yet the above calculation shows that if they initially act on disjoint subsets then they will still commute for all times, despite their overlap. So, clearly, $\left[ A_{X}(t) , B_{Y}(t) \right]$ is not the right quantity to consider if we're interested in notions of causality, yet the only argument I have for why is the rather unsatisfying "because it doesn't tell us anything non-trivial".
Question
Is there a way to see that $\left[ A_{X}(t) , B_{Y} \right]$, where only one-operator is time-evolved, rather than $\left[ A_{X}(t) , B_{Y}(t) \right]$, where both operators are evaluated at the same time, is the more natural quantity to consider when dealing with notions of causality? Specifically I am looking for an answer that is not "because the latter doesn't tell us anything non-trivial".
Thoughts on an answer
When I asked my lecturer about this, he didn't have a complete answer, but thought that it could be related to the fact that
$$
\lVert \left[ A_{X}(t) , B_{Y} \right] \rVert = \lVert \left[ A_{X}(t/2) , B_{Y}(-t/2) \right] \rVert
$$
due to the unitary invariance of the operator norm. In other words, evolving one operator forwards in time by $t$ is equivalent (at least for the purposes of the Lieb-Robinson bound) to evolving both operators in time by $t/2$, but one forwards in time and one backwards in time. However, I'm not sure why this might make this a more "natural" quantity to consider.

A: You want to see that there is a light-cone like structure: If Alice applies some operation at time $0$ and position $0$ and Bob at time $t$ and position $x$, their actions commute (i.e., are space-like separated) if Bob is outside the lightcone of Alice. (Just try to think of a Minkowski diagram.) This is formalized by the fact that Alice's time evolved observable $A(t)$ commutes with Bob's observable.

Let us do this more formally: Let's say Alice tries to pass a message to Bob by applying some unitary $U_A$ at time $0$, starting from an initial state $|\psi\rangle$.  Bob then tries to infer through a measurement $M_B$ at time $t$ whether Alice has applied $U_A$ (or which $U_A$ she applied). ($M_B$ could, e.g., be a POVM element whose outcome probability would give information about $U_A$.)
The state after time $t$ is then
$$
|\psi(t)\rangle = e^{-iHt}U_A|\psi\rangle\ ,
$$
and Bob's measurement $M_B$ will yield
\begin{align*}
\langle \psi(t) | M_B |\psi(t)\rangle
&=
\langle\psi|U_A^\dagger e^{iHt}M_B
e^{-iHt}U_A|\psi\rangle
\\
&=
\langle\psi|U_A^\dagger M_B(t) U_A|\psi\rangle\ .
\end{align*}
As long as we are inside the Lieb-Robinson-cone, this is, Alice and Bob are spacelike separated, $U_A$ and $M_B(t)$ commute (up to an exponentially small correction, the terms arising from which can be easily bounded), and thus
\begin{align*}
\langle \psi(t) | M_B |\psi(t)\rangle
&=
\langle\psi|U_A^\dagger M_B(t) U_A|\psi\rangle
\\
&=
\langle\psi|U_A^\dagger U_A M_B(t)|\psi\rangle
\\
&=
\langle\psi|M_B(t)|\psi\rangle\ ,
\end{align*}
i.e., the measurement outcome of Bob is independent of $U_A$, and thus, Alice cannot pass any information to Bob.


text:
Q: How to let JAXB render boolean as 0 and 1, not true and false Got a quick question. Does anyone know how to let JAXB (marshall) render boolean fields as 1 and 0 instead of printing out "true" and "false"?

A: Having the same problem as user20298, I followed the hint by mtpettyp, and adapted it for my configuration.
My configuration is:
- maven to build the project.
- "org.jvnet.jaxb2.maven2" plugin in maven.
- jaxb 2.2.6
- In this occasion, I was making Java classes for the kml 2.2 (ogckml22.xsd)
And I stumbled upon the problem of the booleans to be rendered as 'true/false', when Google maps wants them to be as '1/0'
This is the plugin configuration in maven:
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<executions>
    <execution>
        <phase>generate-sources</phase>
        <goals>
            <goal>generate</goal>
        </goals>
    </execution>
</executions>
<configuration>
    <generateDirectory>src/main/generated</generateDirectory>
    <extension>true</extension>
    <removeOldOutput>true</removeOldOutput>
</configuration>

I added to the src/main/resources folder a jaxb-bindings.xjb file with the following content:
    <?xml version="1.0" ?>
<bindings xmlns="http://java.sun.com/xml/ns/jaxb"
          version="2.1"
          xmlns:kml="http://www.opengis.net/kml/2.2"
          xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <globalBindings>
        <xjc:simple/>
        <xjc:javaType name="java.lang.Boolean"
                      xmlType="xsd:boolean"
                      adapter="path.to.my.JaxbBooleanAdapter"/>
    </globalBindings>
    ...
    ...
</bindings>

The adapter class is like:
package path.to.my;

import javax.xml.bind.annotation.adapters.XmlAdapter;

/**
 * Utility class to correctly render the xml types used in JAXB.
 */
public class JaxbBooleanAdapter extends XmlAdapter<String, Boolean>
{
    @Override
    public Boolean unmarshal(String v) throws Exception
    {
        if ("1".equals(v))
        {
            return true;
        }
        return false;
    }

    @Override
    public String marshal(Boolean v) throws Exception
    {
        if (v == null)
        {
            return null;
        }
        if (v)
        {
            return "1";
        }
        return "0";
    }
}

A: JAXB provides a flexible way to customize your bindings. You simply have to write an XML file that will indicate how you want to bind your XML and Java types. In your case, you could use a <javaType> declaration, in which you can specify a parseMethod and a printMethod. These methods could be as simple as
public boolean myParseBool(String s)
{
    return s.equals("1");
}

public String myPrintBool(boolean b)
{
    return b ? "1" : "0";
}

There might exist easier ways, maybe using DatatypeConverter, but I'm not enough aware of this subject to help you more !

A: The adapter class:
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class BooleanAdapter extends XmlAdapter<Integer, Boolean>
{
    @Override
    public Boolean unmarshal( Integer s )
    {
        return s == null ? null : s == 1;
    }

    @Override
    public Integer marshal( Boolean c )
    {
        return c == null ? null : c ? 1 : 0;
    }
}

Usage:
@XmlElement( name = "enabled" )
@XmlJavaTypeAdapter( BooleanAdapter.class )
public Boolean getEnabled()
{
    return enabled;
}

A: I would probably create a type adapter for converting a boolean to an int. There are some examples in the JAXB users guide.

A: You can write a pair of parser/writers and define the property mapping in binding JAXB XML.


text:
Q: Adding Object in Entity Framework In an Application it has Data Access layer.In which it has DataEntityModel.edmx  (entityframework model)  and repository class.

Below code is my repository class.
namespace DataModel.Repository
{
 public class ProductRepository
 {
    internal WebApiDbEntities Context;
    internal DbSet<Product> DbSet;

     public ProductRepository(WebApiDbEntities context)
    {
        this.Context = context;
        this.DbSet = context.Set<Product>();
    }

    public virtual void Insert(Product entity)
    {
        DbSet.Add(entity);
    }

}

}

Question is I have used DbSet.Add(entity) method to insert . But Entity Framework will generate it's own Add method Context.Products.Add(entity)
So, What is the difference between those two methods. Why Most of the
  time DbSet.Add(entity) is used ??

A: A repository replaces the use of the DbContext.
So to add an entity, instead of:
var dbContext = new WebApiDataModel();
dbContext.Products.Add(entity)

You use a repository:
var dbContext = new WebApiDataModel();
var productRepository = new ProductRepository(dbContext);
productRepository.Insert(entity);

In the end, both call DbSet<Product>.Add(), but there are reasons why you may want to introduce the repository pattern with Entity Framework.


text:
Q: How to represent connection string in app.config file I have an app.config file which is having an entry like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
        <add key="ServerFilePath" value="file://c:\sybase\ini\sql.ini?"/>
  </appSettings>

As mentioned in the above code, the setting is for Sybase database. Now, i need to change this file for the SQL Server 2008R2 and we don't use any kind of ini file in sql server.
Please suggest me how to represent connection string for Sql Server.

A: Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername;
Password=myPassword;

More here

A: There's a very handy reference for this sort of thing online.  SQL Server connection strings generally look like these:

*

*Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;

*Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;

*Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf;Database=dbname;
Trusted_Connection=Yes;
And so on, depending on the options for connection.


text:
Q: Correct way to use UIActionSheet Delegate? Pointers Mapped to identical Memory I am using the actionSheet variable passed by actionSheet:didDismissWithButtonIndex: to compare the calling actionSheet to a list of UIActionSheet variables in my class. This seems to be the way the delegate method was designed to differentiate between events.
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {

if (actionSheet == actionSheet1) {
    switch (buttonIndex) {
        case 0:
            // Do Something
            break;
        case 1:
            // Do Something Else
            break;
        case 2:
            // Cancel
            break;
    }
}

if (actionSheet == actionSheet2) {
    switch (buttonIndex) {
        case 0:
            // Do Something
            break;
        case 1:
            // Do Something Else
            break;
        case 2:
            // Cancel
            break;
    }
}

}
Each time a UIActionSheet is displayed, I alloc an instance of UIActionSheet to  one of the class variables, set the display properties, display it, and release it.
This works smoothly, at first. The problem is that after running for a while, eventually both UIActionSheet pointers (class variables actionSheet1 & actionSheet2 in the code example above) will end up pointing to the same memory, depending on what happens at runtime, thereby causing both if statements in the delegate method to evaluate true. Not good.
Now, if I were to alloc each UIActionSheet only once per run and hold on to the memory (never call release), this should not happen. But I am trying to be conservative here. Does Apple intend for the delegate to be used in this way?

A: When you create your UIActionSheet, give it a tag:
actionSheet.tag = 1; // or 2 or 3 or ...

Then, in your delegate method, switch based on the tag to determine the behavior of that particular sheet.


text:
Q: What will the _escaped_fragment_ request look like for this AJAX URL? Say I have an AJAX application with this URL:  http://www.foo.com/bar#!a=1&b=2&c=3
What will the crawable AJAX request from GoogleBot look like?
I assumed this:
A) http://www.foo.com/bar?_escaped_fragment_=a%3D1%26b%3D2%26c%3D3
But it looks like it's really this: (i.e. the =s are not url encoded)
B) http://www.foo.com/bar?_escaped_fragment_=a=1%26b=2%26c=3
Is it correct that B) is the actual request I'll receive?
On close examination of the spec it looks like B) is correct, but I still find it a bit surprising since many canned query string parsers will probably not give you the result you want with this input.

A: I'll answer this myself.
The correct answer seems be be neither A) or B) in the above question.  If the "clean" AJAX URL is http://www.foo.com/bar#!a=1&b=2&c=3, the "ugly" _escaped_fragment_ version is http://www.foo.com/bar?_escaped_fragment_=a=1%26b=2%26c=3.  So the = are not escaped, but the & are.  This is covered in the spec.


text:
Q: undefined method `lastname' for nil:NilClass rails - Avatar issues OK, not sure what I did.. but it was working before and now it stopped.
I'm currently trying to add initials as the avatar to users' navbar, following this step by step guide
It all makes sense and I did what was required, but for some reason I'm now getting the error of undefined method..
I'm not sure what am I doing wrong to be honest...Obviosly, users have attribute of firstname and lastname.. Any help would be greatly appreciated. Thank you!
UsersHelper
module UsersHelper
    def show_avatar(user)
        render partial: 'users/avatar'
    end

end

Avatar partial under users/_avatar

        <%= @user.lastname[0..1].upcase %>

Page navbar shared/_navbar

      <%= show_avatar(@user) %>

A: As discussed in chat, since you're using Devise, you can use current_user instead of setting a new @user variable.


text:
Q: Changing the theme of Google Map on click - React Native I have react native maps and I am setting the custom map theme as this.state.mapTheme.
constructor() {
    super();
    this.state = {
        mapTheme: Themes.SANANDREAS
    }
}

And I have the render method as such:
render() {
    return (
        <Container style ={styles.container}>
            <Button rounded style={styles.contributeButton} onPress={() => {
                this.setState({
                    mapTheme: Themes.BROWNTHEME
                })
            }} iconLeft light>
              <Icon name='hand' />
              <Text>Contribute</Text>
            </Button>
            <MapView
                style={styles.map}
                provider = { MapView.PROVIDER_GOOGLE }
                customMapStyle = { this.state.mapTheme }
            ></MapView>
        </Container>
);}

It all seems to be working, but when I change the state on press of the button, the render method is getting called but the theme does
not change. Both of my themes are working but on press nothing happens. The page reloads but without the new theme being used. What am I doing wrong here?

A: Considering the MapView component's lifecycle functions it won't update the styles automatically if new style props is passed. You should force it by calling _updateStyle after theme change directly with the help of 'ref':
setMapRef = ref => this.mapRef = ref;

handleButtonClick = () => {
  this.setState({ mapTheme: Themes.BROWNTHEME }, () => {
    this.mapRef._updateStyle();
  })
}

render() {
  return (
     <Container>
       <Button onPress={this.handleButtonClick}
         title="Update map theme"
       />
       <MapView
         ref={this.setMapRef}
         customMapStyle={this.state.mapTheme}
       />
     </Container>
  );
}


text:
Q: 1/x + 1/y = 1/N(factorial) The question is, how to solve 1/x + 1/y = 1/N! (N factorial). Find the number of values that satisfy x and y for large values of N.
I've solved the problem for relatively small values of N (any N! that'll fit into a long). So, I know I solve the problem by getting all the divisors of (N!)^2. But that starts failing when (N!)^2 fails to fit into a long. I also know I can find all the divisors of N! by adding up all the prime factors of each number factored in N!. What I am missing is how I can use all the numbers in the factorial to find the x and y values.
EDIT: Not looking for the "answer" just a hint or two.

A: It's more to math than programming.
Your equation implies xy = n!(x+y).
Let c = gcd(x,y), so x = cx', y= cy', and gcd(x', y')=1.
Then c^2 x' y'=n! c (x'+y'), so cx'y' = n!(x' + y').
Now, as x' and y' are coprime, and cannot be divisible be x'+y', c should be.
So c = a(x'+y'), which gives ax'y'=n!.
To solve your problem, you should find all two coprime divisors of n!, every pair of which will give a solution as ( n!(x'+y')/y', n!(x'+y')/x').

A: Problem : To find the count of factors of (N!)^2.
Hints :
1) You don't really need to compute (N!)^2 to find its prime factors.
Why?
Say you find the prime factorization of N! as (p1^k1) x (p2^k2) .... (pi^ki)
where pj's are primes and kj's are exponents.
Now the number of factors of N! is as obvious as
(k1 + 1) x (k2 + 1) x ... x (ki + 1).
2) For (N!)^2, the above expression would be,
(2*k1 + 1) * (2*k2 + 1) * .... * (2*k1 + 1)
which is essentially what we are looking for.
For example, lets take N=4, N! = 24 and (N!)^2 = 576;
24 = 2^3 * 3^1;
Hence no of factors = (3+1) * (1+1) = 8, viz {1,2,3,4,6,8,12,24}
For 576 = 2^6 * 3^2, it is (2*3 + 1) * (2*1 + 1) = 21;
3) Basically you need to find the multiplicity of each primes <= N here.
Please correct me if i'm wrong somewhere till here.

A: Let F(N) be the number of (x,y) combinations that satisfy your requirements.
F(N+1) = F(N) + #(x,y) that satisfy the condition for N+1 and at least one of them (x or y) is not divisible N+1.
The intuition here is for all combinations (x,y) that work for N, (x*(N+1), y*(N+1)) would work for N+1. Also, if (x,y) is a solution for N+1 and both are divisible by n+1, then (x/(N+1),y/(N+1)) is a solution for N.
Now, I am not sure how difficult it is to find #(x,y) that work for (N+1) and at least one of them not divisible by N+1, but should be easier than solving the original problem.

A: Now Multiplicity or Exponent  for Prime p in N! can be found by below formula:\
Exponent of P in (N!)= [N/p] + [N/(P^2)] +[N/(P^3)] + [N/(P^4)] +...............
                 where [x]=Step function  E.g. [1.23]=integer part(1.23)=1

E.g. Exponent of 3 in 24! = [24/3] +[24/9]+ [24/27] + ... = 8 +2 +0 + 0+..=10
 Now whole problem reduces to identifying prime number below N and finding its Exponent in N!

A: Here is your hint.  Suppose that m = p1k1 · p2k2 · ... · pjkj.  Every factor of m will have from 0 to k1 factors of p1, 0 to k2 factors of p2, and so on.  Thus there are (1 + k1) · (1 + k2) · ... · (1 + kj) possible divisors.
So you need to figure out the prime factorization of n!2.
Note, this will count, for instance, 1⁄6 = 1⁄8 + 1⁄24 as being a different pair from 1⁄6 = 1⁄24 + 1⁄8.  If order does not matter, add 1 and divide by 2.  (The divide by 2 is because typically 2 divisors will lead to the same answer, with the add 1 for the exception that the divisor n! leads to a pair that pairs with itself.)


text:
Q: Is there a convention for maintaining both a free and pro app version from the same codebase in Eclipse? I am releasing two versions of an app--free and paid. The differences between the two are few, and I would like to release both using the same codebase (maybe a different constant defined for the other build?). Has anyone done this? Can someone point me in the right direction? Thanks!

A: Use an Android library project, which was specifically designed for your free/paid scenario.


text:
Q: radius of circle tangent to the parabola y=x^2 In the following diagram, what's the amount of r=?

I supposed the center of the small circle to be $(0,y)$. So I have
its distance from $(x, x^2)$ is $(x-0)^2+(y-x^2)^2=1400^2$ this question must have just one answer so the discriminant of the equation must be zero. But then I don't have any idea. how can I relate this to the bigger circle :(

A: You have the lower circle of radius $1400$. Assuming its center is $(0, a)$ then its equation is
$ x^2 + (y - a)^2 = 1400^2 $
At the tangency points $y = x^2 $, therefore
$ x^2 + (x^2 - a)^2 = 1400^2 $
Expanding, this becomes,
$ x^4 + x^2 (1 - 2 a) + a^2 - 1400^2 = 0 $
Since we want only one intersection point (actually two, but a single value of $x^2$), the discriminant must be zero, hence
$ (1 - 2 a)^2 - 4 (a^2 - 1400^2 ) = 0 $
Simplifying this becomes
$ 1 - 4 a + 4 (1400^2 ) = 0 $
From which,
$ a = \dfrac{ 1 + 4 (1400^2) }{4} = 1400^2 + \dfrac{1}{4} $
Now, we can move to the upper circle, its center is at $( 0, a + r )$ and radius $r$, thus its equation is
$ x^2 + ( y - (a + r) )^2 = r^2$
Again at the points of tangency, $y = x^2 $, so
$ x^2 + (x^2 - (a + r) )^2 = r^2 $
which simplifies to
$ x^4 + x^2 (1 - 2 (a + r) ) + (a + r)^2 - r^2 = 0 $
And we want the value of $x^2$ that solves this quadratic to be a single value, so again, the discriminant must be zero,
$ ( 1 - 2(a + r) )^2 - 4 ( a^2 + 2 a r ) = 0 $
Expanding,
$ 1 - 4 (a + r) + 4 (a^2 + 2 a r + r^2 ) - 4 (a^2 + 2 a r ) = 0 $
and this simplifies to
$ 1 - 4 (a + r) + 4 r^2 = 0 $
Knowing $a$ from the first circle, we can proceed to solve for $r$, there will be two values, and we should take the positive one. The other negative value corresponds to the circle that can drawn tangent to the '$1400$' circle but from below.
Can you take it from here ?

A: Consider an inscribed circle $\gamma$ of centre $C$ and tangency point $P=(x,x^2)$. The tangent at $P$ intersects $x$-axis at $M=(x/2,0)$ (easy to prove property of a parabola). If $H$ and $K$ are the projections of $P$ on cartesian axes, triangles $PHM$ and $PKC$ are similar (because $CP\perp PM$), hence:
$$
d:{x\over2}=r:\sqrt{x^4+{x^2\over4}}=x:x^2,
$$
where $d=CK$ and $r=CP$ is the radius of $\gamma$. It follows that:
$$
d={1\over2}
\quad\text{and}\quad
r=\sqrt{x^2+{1\over4}}.
$$
Hence:
$$OC=x^2+{1\over2}=r^2+{1\over4}.$$
If we have a larger circle $\gamma'$, tangent to the parabola and to $\gamma$, with center $O'$ and radius $r'$, we have then:
$$OC'=r'^2+{1\over4}.$$
But $CC'=r+r'$, that is:
$$
r'^2-r^2=r'+r,
\quad\text{whence:}\quad
r'-r=1.
$$

If the equation of the parabola were instead $y=ax^2$, we would obviously get:
$$r'-r={1\over a}.$$


text:
Q: Validate a Boolean expression with brackets in C# I want to validate a string in C# that contains a Boolean expression with brackets.
The string should only contain numbers 1-9, round brackets, "OR" , "AND".
Examples of good strings:
"1 AND 2"
"2 OR 4"
"4 AND (3 OR 5)"
"2"
And so on...
I am not sure if Regular Expression are flexible enough for this task.
Is there a nice short way of achieving this in C# ?

A: It's probably simpler to do this with a simple parser. But you can do this with .NET regex by using balancing groups and realizing that if the brackets are removed from the string you always have a string matched by a simple expression like ^\d+(?:\s+(?:AND|OR)\s+\d+)*\z.
So all you have to do is use balancing groups to make sure that the brackets are balanced (and are in the right place in the right form).
Rewriting the expression above a bit:
(?x)^
OPENING
\d+
CLOSING
(?:
    \s+(?:AND|OR)\s+
    OPENING
    \d+
    CLOSING
)*
BALANCED
\z

((?x) makes the regex engine ignore all whitespace and comments in the pattern, so it can be made more readable.)
Where OPENING matches any number (0 included) of opening brackets:
\s* (?: (?<open> \( ) \s* )*

CLOSING matches any number of closing brackets also making sure that the balancing group is balanced:
\s* (?: (?<-open> \) ) \s* )*

and BALANCED performs a balancing check, failing if there are more open brackets then closed:
(?(open)(?!))

Giving the expression:
(?x)^
\s* (?: (?<open> \( ) \s* )*
\d+
\s* (?: (?<-open> \) ) \s* )*
(?:
    \s+(?:AND|OR)\s+
    \s* (?: (?<open> \( ) \s* )*
    \d+
    \s* (?: (?<-open> \) ) \s* )*
)*
(?(open)(?!))
\z

If you do not want to allow random spaces remove every \s*.
Example
See demo at IdeOne. Output:
matched: '2'
matched: '1 AND 2'
matched: '12 OR 234'
matched: '(1) AND (2)'
matched: '(((1)) AND (2))'
matched: '1 AND 2 AND 3'
matched: '1 AND (2 OR (3 AND 4))'
matched: '1 AND (2 OR 3) AND 4'
matched: ' ( 1    AND ( 2 OR  ( 3 AND    4 )  )'
matched: '((1 AND 7) OR 6) AND ((2 AND 5) OR (3 AND 4))'
matched: '(1)'
matched: '(((1)))'
failed:  '1 2'
failed:  '1(2)'
failed:  '(1)(2)'
failed:  'AND'
failed:  '1 AND'
failed:  '(1 AND 2'
failed:  '1 AND 2)'
failed:  '1 (AND) 2'
failed:  '(1 AND 2))'
failed:  '(1) AND 2)'
failed:  '(1)() AND (2)'
failed:  '((1 AND 7) OR 6) AND (2 AND 5) OR (3 AND 4))'
failed:  '((1 AND 7) OR 6) AND ((2 AND 5 OR (3 AND 4))'
failed:  ''

A: If you consider a boolean expression as generated by a formal grammar writing a parser is easier.
I made an open source library to interpret simple boolean expressions. You can take a look at it on GitHub, in particular look at the AstParser class and Lexer.

A: If you just want to validate the input string, you can write a simple parser.
Each method consumes a certain kind of input (digit, brackets, operator) and returns the remaining string after matching. An exception is thrown if no match can be made.
public class ParseException : Exception { }

public static class ExprValidator
{
    public static bool Validate(string str)
    {
        try
        {
            string term = Term(str);
            string stripTrailing = Whitespace(term);

            return stripTrailing.Length == 0;
        }
        catch(ParseException) { return false; }
    }

    static string Term(string str)
    {
        if(str == string.Empty) return str;
        char current = str[0];

        if(current == '(')
        {
            string term = LBracket(str);
            string rBracket = Term(term);
            string temp = Whitespace(rBracket);
            return RBracket(temp);
        }
        else if(Char.IsDigit(current))
        {
            string rest = Digit(str);
            try
            {
                //possibly match op term
                string op = Op(rest);
                return Term(op);
            }
            catch(ParseException) { return rest; }
        }
        else if(Char.IsWhiteSpace(current))
        {
            string temp = Whitespace(str);
            return Term(temp);
        }
        else throw new ParseException();
    }

    static string Op(string str)
    {
        string t1 = Whitespace_(str);
        string op = MatchOp(t1);
        return Whitespace_(op);
    }

    static string MatchOp(string str)
    {
        if(str.StartsWith("AND")) return str.Substring(3);
        else if(str.StartsWith("OR")) return str.Substring(2);
        else throw new ParseException();
    }

    static string LBracket(string str)
    {
        return MatchChar('(')(str);
    }

    static string RBracket(string str)
    {
        return MatchChar(')')(str);
    }

    static string Digit(string str)
    {
        return MatchChar(Char.IsDigit)(str);
    }

    static string Whitespace(string str)
    {
        if(str == string.Empty) return str;

        int i = 0;
        while(i < str.Length && Char.IsWhiteSpace(str[i])) { i++; }

        return str.Substring(i);
    }

    //match at least one whitespace character
    static string Whitespace_(string str)
    {
        string stripFirst = MatchChar(Char.IsWhiteSpace)(str);
        return Whitespace(stripFirst);
    }

    static Func<string, string> MatchChar(char c)
    {
        return MatchChar(chr => chr == c);
    }

    static Func<string, string> MatchChar(Func<char, bool> pred)
    {
        return input => {
            if(input == string.Empty) throw new ParseException();
            else if(pred(input[0])) return input.Substring(1);
            else throw new ParseException();
        };
    }
}

A: ANTLR Parser Generator?

a short way of achieving this in C#

Although it may be an overkill if its just numbers and OR + AND

A: Pretty simply:
At first stage you must determ lexems (digit, bracket or operator) with simple string comparsion.
At second stage you must define variable of count of closed bracket (bracketPairs), which can be calculated by the following algorithm for each lexem:
if current lexem is '(', then bracketPairs++;
if current lexem is ')', then bracketPairs--.
Else do not modify bracketPairs.
At the end if all lexems are known and bracketPairs == 0 then input expression is valid.
The task is a bit more complex, if it's necesery to build AST.

A: what you want are "balanced groups", with them you can get all bracet definitions, then you just need a simple string parsing
http://blog.stevenlevithan.com/archives/balancing-groups
http://msdn.microsoft.com/en-us/library/bs2twtah.aspx#balancing_group_definition


text:
Q: AutoFilter applied to all files in a directory Objective: Loop through all files in a folder, and for each file, apply a filter based on Column 1 = "A". Then save over the ActiveWorkbook with the filter applied.
The below times out at ActiveSheet.Range("A1").AutoFilter Field:=1, Criteria1:="A" and i'm not sure why
Sub FilterApply()

Dim folderName As String
Dim filelocation As String

Dim FSOLibrary As Object
Dim FSOFolder As Object
Dim FSOFile As Object
Dim TargetWB As Workbook

'Set the file name to a variable
folderName = "X:\"
filelocation = "X:\"

'Set all the references to the FSO Library
Set FSOLibrary = CreateObject("Scripting.FileSystemObject")
Set FSOFolder = FSOLibrary.GetFolder(folderName)
Set FSOFile = FSOFolder.Files

'Apply Autofilter to all sheets in FSOFolder

For Each FSOFile In FSOFile
    If Not ActiveSheet.AutoFilterMode Then
        ActiveSheet.Range("A1").AutoFilter Field:=1, Criteria1:="A"
        ActiveWorkbook.Save
    End If
    Next

A: Apply Autofilter in Multiple Files

*

*You forgot to open the file: Workbooks.Open.

*This page contains a great example of how to handle the File System Object when handling files.

*Using the second code, you can monitor what is happening
in the Immediate window CRTL+G.

*If all the workbooks have worksheets with the same name, you should properly qualify them, e.g. Set ws = wb.Worksheets("Sheet1"). If they only have one worksheet than you don't have to bother. But if they have multiple worksheets you might get unexpected results, if you cannot be sure which worksheet was active before the last save.
The Code
Option Explicit

Sub FilterApply()

    Dim folderName As String

    Dim FSOLibrary As Object
    Dim FSOFolder As Object
    Dim FSOFiles As Object
    Dim FSOFile As Object

    'Set the file name to a variable
    folderName = "F:\Test\02.07.20"

    'Set all the references to the FSO Library
    Set FSOLibrary = CreateObject("Scripting.FileSystemObject")
    Set FSOFolder = FSOLibrary.GetFolder(folderName)
    Set FSOFiles = FSOFolder.Files

    'Apply Autofilter to all sheets in FSOFolder
    Dim wb As Workbook
    Dim ws As Worksheet
    For Each FSOFile In FSOFiles
        Set wb = Workbooks.Open(FSOFile.Path)
        Set ws = wb.ActiveSheet ' wb.worksheets("Sheet1") is safer.
        If Not ws.AutoFilterMode Then
            On Error Resume Next
            ws.Range("A1").AutoFilter Field:=1, Criteria1:="A"
            If Err.Number = 0 Then
                wb.Close SaveChanges:=True
            Else
                wb.Close SaveChanges:=False
            End If
            On Error GoTo 0
        Else
            wb.Close SaveChanges:=False
        End If
    Next

End Sub

Sub FilterApplyErr()

    Dim folderName As String

    Dim FSOLibrary As Object
    Dim FSOFolder As Object
    Dim FSOFiles As Object
    Dim FSOFile As Object

    'Set the file name to a variable
    folderName = "F:\Test\02.07.20"

    'Set all the references to the FSO Library
    Set FSOLibrary = CreateObject("Scripting.FileSystemObject")
    Set FSOFolder = FSOLibrary.GetFolder(folderName)
    Set FSOFiles = FSOFolder.Files

    'Apply Autofilter to all sheets in FSOFolder
    Dim wb As Workbook
    Dim ws As Worksheet
    For Each FSOFile In FSOFiles
        Set wb = Workbooks.Open(FSOFile.Path)
        Set ws = wb.ActiveSheet ' wb.worksheets("Sheet1") is safer.
        If Not ws.AutoFilterMode Then
            On Error Resume Next
            ws.Range("A1").AutoFilter Field:=1, Criteria1:="A"
            Select Case Err.Number
                Case 0
                    Debug.Print "The data in worksheet '" & ws.Name _
                              & "' of workbook '" & wb.Name _
                              & "' was filtered now."
                    wb.Close SaveChanges:=True
                Case 1004
                    If Err.Description = "AutoFilter method of Range class " _
                                       & "failed" Then
                        Debug.Print "Worksheet '" & ws.Name & "' in workbook " _
                                  & "'" & wb.Name & "' has no data in cell " _
                                  & "'A1'."
                        wb.Close SaveChanges:=False
                    Else
                        Debug.Print "Run-time error '" & Err.Number _
                                  & "': " & Err.Description
                        wb.Close SaveChanges:=False
                End If
            Case Else
                Debug.Print "Run-time error '" & Err.Number _
                          & "': " & Err.Description
                wb.Close SaveChanges:=False
            End Select
            On Error GoTo 0
        Else
            Debug.Print "The data in worksheet '" & ws.Name _
                      & "' of workbook '" & wb.Name _
                      & "' had already been filtered."
            wb.Close SaveChanges:=False
        End If
    Next

End Sub


text:
Q: set property grid's headers visible I know that hideHeaders: true hides the property grid's headers (names, values).
Now, if I want to make the headers visible from outside, how I can achieve that?
Example:
var grid = Ext.create('Ext.grid.property.Grid',
{
    id: 'grid',
    hideHeaders: true
});

// I get/create a source here
grid.setSource(data);

// now, since my grid is full, I want to show the headers
// tried this but did not work :/
grid.add({hideHeaders: false});

Thanks

A: I don't think that there is a way to do that built into the framework, but you could probably hack your way to the solution...
On your grid, add a listener to hide the headers:
listeners: {
    afterrender: function(grid) {
        grid.headerCt.setVisible(false);
    }
}

Then, when you're ready to show the headers again:
grid.headerCt.setVisible(true);


text:
Q: Element.update() prototype function not working in IE I was using Element.innerHTML but IE (8,9,10) doesn't like it, so I switched to Element.insert(), but IE doesn't like it either. Then decided to try with Element.update() - nope again!
Searched around and found out that .update() is actually the working replacement of .innerHTML for IE... Tried with passing a variable or even a direct string as parameter to the function - "nuh uh" says IE.
script
var dropdownHTML = '<option>Some text</option>';
$('size_list').update('<form ><select id="dropdown_options"></select></form>');
for (var element in jsonResponse){
  dropdownHTML += '<option>'+ someString + '</option>';
  ...
}
$('dropdown_options').update(dropdownHTML);

source
<div id="size_list" style="float:right;">
</div>

Needless to say, it all works in FF and Chrome. I made a working solution with jQuery.html() but my whole document is built up with prototype.js and I would not like to mix the 2 things.
Any suggestions?

A: Probably the simplest answer here is to use the Option constructor rather than setting the HTML of the select element.
var form = document.createElement('form');
var select = document.createElement('select');
select.id = "dropdown_options";
select.options.add(new Option("Some text"));
for (/*...whatever your loop is...*/) {
    select.options.add(new Option("text of the option", "optional value of the option"));
}
form.appendChild(select);
$("size_list").appendChild(form);

Note that you use add (rather than push) with the options collection (it's not an array; some implementations have push, but add is more reliable).


text:
Q: 2 decimal time display on audio player For my audio player, how can I display both times in just 2 decimals?
Right now the counter shows ... 0:7, 0:8, 0:9, 0:10, 0:11
But it should be like:
0:07, 0:08, 0:09, 0:10, 0:11
and the total time of the audio file is displayed like: 273.298866
But it should be:
4:13

var duration = document.getElementById('fullDuration');
var currentTime = document.getElementById('currentTime');

duration.innerHTML = mytrack.duration;

mytrack.addEventListener("loadedmetadata",function(){
    var minutes = parseInt(mytrack.duration / 60);
    var seconds = parseInt(mytrack.duration % 60);
    duration.innerHTML = minutes + ':' + seconds;
})

And
function update(){
  if(!mytrack.ended){
    var playedMinutes = parseInt(mytrack.currentTime/60);
    var playedSeconds = parseInt(mytrack.currentTime%60);
    currentTime.innerHTML = playedMinutes + ':' + playedSeconds;

    var size = parseInt(mytrack.currentTime*barSize/mytrack.duration);
    progressBar.style.width = size + "px";

  }
  else{
    currentTime.innerHTML = "0.00";
    playButton.style.backgroundImage = 'url(file:///Users/Pier/Desktop/Play%20button.png)';
    progressBar.style.width = "0px";
    window.clearInterval(updateTime);
  }
}

A: The modern way to do this is with String.padStart, but it doesn't work with IE:
currentTime.textContent = playedMinutes + ':' + playedSeconds.toString().padStart(2, '0');


text:
Q: Can a vector subspace have a unique complement in absence of choice? Let $V$ be a vector space (not necessarily finite dimensional and over some arbitrary field), and $W$ a proper non-zero subspace. If we assume existence of bases, it is easy to show that $W$ can be complemented, in a necessarily non-unique way. The non-uniqueness has been proved in Unique complement of a subspace, for example.
However, existence of a basis can fail in absence of axiom of choice. In such a situation, is it possible that $W$ has a unique complement? Or is there a proof that does not use the existence of a basis?
Is it possible that $W$ does not have a complement at all? This seems very likely, although I haven't found an example.
This question is motivated by a problem from Halmos' book "Finite Dimensional Vector Spaces" where he asks the question for presumably finite dimensional $V$.

A: First of all, note that even with the axiom of choice there isn't necessarily a unique complement.
For example, take $V=\Bbb R^2$ and $\newcommand{\sp}{\operatorname{span}}W=\sp\{(0,1)\}$. Then both $\sp\{(1,1)\}$ and $\sp\{(1,0)\}$ are direct complements of $W$,since their internal direct sum with $\sp\{(0,1)\}$ give $V=\Bbb R^2$, however neither is equal to the other.
In the case where we want an orthogonal complement, then we no longer talk about vector spaces, but rather we talk about inner product spaces.
Finally, the axiom of choice is equivalent to the statement that direct complements exist. That is, if $V$ is a vector space and $W$ is a subspace then there is some $U$ such that $W\cap U=\{0\}$ and $\sp(W\cup U)=V$. This means that when the axiom of choice fails then there is some vector space $V$ and a subspace $W$ such that $W$ has no direct complement, every subspace will either intersect nontrivially with $W$ or their sum won't be the entire space.
However the failure of the axiom of choice is as non-constructive as the axiom of choice itself. So we can't really construct an example. We can, though, use the fact that there is a family of non-empty sets which doesn't admit a choice function, and by analyzing the proof of the above equivalence construct a vector space and a subspace without a direct complement.
If one only wishes to produce a consistency result (i.e. construct a particular example), then one can use Läuchli's construction (and by extension the work I did in my masters) and show that it is possible to have a vector space which is not finitely dimensional, but every proper subspace has a finite dimension. Clearly, in such vector space there is no direct complement to any proper subspace.
Finally, now to answer the question in the title. Take a model where there is such a Läuchli space, $W$ and consider $V=W\oplus W$. Then the subspace $W\oplus\{0\}$ has a unique direct complement.


text:
Q: Haskell Snap Framework configuring custom logging? I want to implement custom logging in my Snap application so that I can pass my logs as JSON to Logstash / Kibana however I cannot figure out how to override the default logging behaviour.
Reading the code, I'm pretty sure that the logA (A for Access log) method is what is providing this logging format implicitly.
But I'm not sure how to override it. How do you override the custom logging in the snap framework? Is it impossible? Will I need to raise a PR? Cheers.

A: I have asked the Snap Core team if this was possible and the answer is: no, you cannot configure custom logging. Raised a feature request as a result which you can view here.


text:
Q: How to review seemingly well thought out first posts? So I've encountered a few posts for review specifically under first posts. These posts seem to be OK at a glance. They have no glaring format issues, no need for comment, and they fit the Stack Overflow guidelines.
The problem is that I can't necessarily tell if they are correct. I guess they should be skipped in this case perhaps. Is there a way to say that something has been "reviewed for standards compliance" without voting something up? Is there a protocol to follow, like "always make a comment on a first post regardless if it is a good or bad"?

A: This isn't strictly an answer, but I've come across much the same issue being here for about a month (after using SO for a few years). So I'm probably a good use-case.
I find it rather addictive to review other posts, but where I don't know if the post is applicable/accurate with regard to a particular subject I'll always skip it rather than upvote by default - that's just too easy and some just don't make the effort.
If anything, and where applicable, I'm more likely to correct grammar or fix layout/markdown failures, improve readability and hit I'm Done as my way of contributing.
What I do know is that posts are often well thought out, well structured and provide what I consider good effort - but, much like you, I can't accept/upvote them from a compliance perspective - I don't think it's a good idea to do so! From a personal perspective it's better to just skip and leave for those better experienced in a particular field - which I find myself doing on a regular basis.
I don't think a compliance-tick would be constructive, despite it's draw. Sure there could be a "looks good" button, but then domain experts could think it's utter rubbish.
Despite all my skips to date, I've never seen the first post queue beyond 20-30.

A: There have been many requests for a Looks Good! button in the first posts or late answers review queue here...
You are right in my opinion to Skip the review when you think that the post looks good, but you cannot tell if it's a correct answer or a valid question. Other reviewers more experienced on the topic in question might have a better idea about the quality of that post.
However I think there's another major drawback of a Looks Good! button: By clicking this button you would increase your review count for that queue (and thus work towards certain badges) without providing any useful feedback to the post owner. The only thing this review action then would do, is kicking this post out of the review queue and thus prevent other (in this case probably more experienced) users from reviewing it.
The Skip-button only kicks this post out of your review queue - so you don't need to worry about that post anymore ;)


text:
Q: pytorch custom urdu dataloader (text and images) I am new on pytorch lib and trying to load a dataset i acquire online. Its a OCR in Urdu language. the structure of the dataset is
-Train_image:
-name1.jpg
-name2.jpg
-train_labels.csv
-column 1 (Files name)
-name1
-name2
-column 2 (text in the corrosponding file)
-label1 (urdu text)
-label2 (urdu text)
now how can i load this data to train a CNN and A RNN for detection and recognition?


text:
Q: How come JQuery doesn't pass JSLint?
Possible Duplicate:
What good is JSLint if jQuery fails the validation

http://code.jquery.com/jquery-1.4.4.js
Go to there and paste it in www.jslint.com
Isn't Jquery supposed to be valid....

A: It's far too much work to comply with it AND be cross-browser compliant. JSLint is useful but its only a generic parser. jQuery has good reasons to throw errors in it.
Sometimes you just need simple dirty hacks to get code working in non-compliant browsers.
let's look at them one by one :

Problem at line 231 character 20:
Expected '===' and instead saw '=='.
return num == null ?

Here jQuery uses == on null to check for both undefined and null. Since jQuery is used as an external library it can't guarantee whether the input we pass to functions will be undefined or null. It is safer for it check for both.
Doing num === undefined || num === null to satisfy JSLint is ridiculous.

Problem at line 446 character 29:
Expected a conditional expression and
instead saw an assignment.
while ( (fn = ready[ i++ ]) ) {

Here JSLint complains about assignment instead of equals check. The reason JSLint throws this error is because its common to type = instead of == by mistake. Assigning in this while loop is done on purpose to make the code neater.

Problem at line 550 character 9: Empty
block.
var key; for ( key in obj ) {}
return key === undefined ||
hasOwn.call( obj, key );

JSLint complains about an empty for block. This here has been done on purpose because we don't want to do anything with key instead we want to enumerate over all the keys and only care about the last one.

Problem at line 554 character 15: Move
'var' declarations to the top of the
function.
for ( var name in obj ) {

JSLint insists on having variables declaration at the top of functions. This is a bit silly and can be ignored if you want to. It's a matter of style.
And then the parser crashes. Let me remove some of the code crashing it and see if I can find more complaints.

Problem at line 792 character 42: The
'&&' subexpression should be wrapped
in parens.
ua.indexOf("compatible") < 0 &&
rmozilla.exec( ua ) ||

I actually agree with this one (ua.indexO("compatile") < 0) && is better.

Problem at line 872 character 3: Move
the invocation into the parens that
contain the function.
})();

For closures like:
(function() {

})();
//}());

JSLint prefers to see the function invocation in the brackets as a matter of style. I also agree with this one but it really doesn't matter at all.

Problem at line 972 character 13: 'e'
is already defined.
} catch(e) {

Parser is complaining about the reuse of variable e In this case we know that e will only be used locally in that catch block so it doesn't matter if we alter it outside the catch block. Here I prefer the readability of re-using the variable name e

Problem at line 1097 character 21:
Expected '===' and instead saw '=='.
elem = elem == window ?

Ok, you caught me on this one. I'm stumped as to why jQuery doesn't use === on window

Problem at line 1621 character 24:
Expected an assignment or function
call and instead saw an expression.
parent.selectedIndex;

// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( name === "selected" && !jQuery.support.optSelected ) {
    var parent = elem.parentNode;
if ( parent ) {
    parent.selectedIndex;

Here's one of those cross-browser compliancy bugs that can be fixed but causes bad code

Problem at line 977 character 17:
Missing 'break' after 'case'.
case "last":

JSLint says you should always break after your cases. It's perfectly valid to drop through after a case. In most cases you forgot to break but here this is intentional.

Problem at line 1099 character 77:
Expected an assignment or function
call and instead saw an expression.
Array.prototype.slice.call(
document.documentElement.childNodes, 0
)[0].node...

// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
    Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;

The source here speaks for itself. It's a weird statement but if accessing it like this throws an error then it can be caught. It's still valid just JSLint tells you "did you really mean to do this?"

Problem at line 2377 character 15: Bad
for in variable 'name'.
for ( name in options ) {

Here JSLint complains about the use of name which can conflict with window.name in global scope. It's a "not quite reserved future keyword but still should be avoided". Were in a closure so it's safe.

Problem at line 2486 character 29: Too
many errors. (60% scanned).

JSLint's internal stack can't handle it. I'm going to stop now.
I think the point is illustrated.
JSLint has a lot of "Are you sure you want to do this" and we're telling it yes we want to do this. It might look like a mistake but it's not.

A: The rules that jslint uses are guidelines, not unbreakable rules.  There are many reasons you might want to disregard some of them.
There are quite a few detailed considerations of jslint rules out there; many people disagree with it.
Personally, I like it, but use the comments at the top of each JS file to switch on and off various warnings when I know that what I'm doing is appropriate.  We then run jslint against all of our JS as part of the CI tests and it catches a few trivial mistakes now and then without generally bothering us.


text:
Q: Rounding position with mouse constant update FIXED I'm making a mario maker style game in C# (unity) where everything has to snap to a grid. I want to, while I'm dragging it, have the item snap into place closest to each int.
 void FixedUpdate () {
      Vector2 pos = Input.mousePosition;
      pos.x = Mathf.Round(pos.x);
      pos.y = Mathf.Round(pos.y);
      pos = Camera.main.ScreenToWorldPoint (pos);
      transform.position = pos;
 }

This does not work for me, and I've been trying for hours to fix this. Nothing has helped so far, I've gone through every forum I could find to no avail. Please help!!

A: I think you should round values after changing pixel pos to world pos.
I mean, after
    pos = Camera.main.ScreenToWorldPoint (pos);
Let me know result.
If it not work, I would think another try.

A: update the rounded positions AFTER you do the mouse position changes.
void FixedUpdate () {
     Vector2 pos = Input.mousePosition;
     pos = Camera.main.ScreenToWorldPoint (pos);
     pos.x = Mathf.Round(pos.x);
     pos.y = Mathf.Round(pos.y);
     transform.position = pos;
}


text:
Q: is it possible to load EF metadata at runtime? I want to load EF metadata from database at runtime. Is that scenario possible? First get the data from database, then write it to .ssdl, .msl and .csdl files sounds ok. But how to tell EF to use what I've loaded? Do I need to compile it or something like that?

A: Yes, you can do that.
New up a MetadataWorkspace using the constructor which takes these files.
Then you can new up an EntityConnection passing the MetadataWorkspace to the overloaded constructor, and finally new the ObjectContext passing that.
With all that said, I wonder if this is the best approach to your problem.


text:
Q: What is the map from $H_j( \Sigma MSO(k)) \to H_{j-k}(BSO(k))$ on Tom Dieck page 537 I am reading Tom Dieck's page 537 and I am not sure what the vertical map that I put in the title is in the diagram in the bottom of the page.  This map is labeled Thom Isomorphism.  Here $MSO(k)$ is the thom space of the tautological bundle over $BSO(n)$.   There is a thom isomorphism from $H_{j-1}(MSO(k))\to H_{j-k-1}(BSO(k))$ giving by capping with the $k$ dimensional cohomology class of $H^k(MSO(K))$.
The suspension isomorphism on reduced homology is from $H_j(MSO(k)) \to H_{j-k}(\Sigma BSO(k))$.  I am skeptical that $H_{j-k}(\Sigma BSO(k))=H_{j-k}(BSO(k))$.  For example $\Sigma BSO(2)=\Sigma BS^1=\Sigma K(\mathbb{Z},2)=\Sigma \Omega K(\mathbb{Z},3)$ which admits an evaluation map that admits isomorphisms on low dimensional homotopy groups , to $K(\mathbb{Z},3)=$ which doesn't have the same low dimensional homoptopy groups as $BSO(2)=K(\mathbb{Z},2)$
Another random idea is I know that the thom isomorphism commutes with the boundary map and hence suspension.  Do you have any ideas on finding this map?

edit:  I put the wrong map in the title and consequentially my post made no sense.  It should be readable now.

A: It is just the map from $H_j(\Sigma MSO(k))=H_j(M(SO(k) \oplus SO(1))) \to H_{j-(k+1)}(B(SO(k) \oplus SO(1)))=H_{j-(k+1)}(B(SO(k)))$
But I don't know why the dimensions are not matching, for the degree of the thom isomorphism.
I personally think that tom tieck got his indices mixed up and that his book has a typo.


text:
Q: Newest tracks don't come up on top in embedded Spotify playlist? When I embed a Spotify playlist, the oldest tracks come up on top. Is there any way to to make the newest tracks come up on top instead?

A: Well, the Play button (I assume that's what you're using) displays the playlist in the playlist's order - if the user manually drags tracks to the top, they'll be at the top.
The problem here is that by default, the Spotify clients add new tracks to the end of the playlist. Changing that would need a change in the Spotify clients, which obviously is beyond the scope of this problem.


text:
Q: How can I find where Zend is installed on my server? I'm trying to use Zend's "Zend_Service_Amazon" class in my php script, but I'm not sure where it is installed.  I'm assuming I need to include the path to Zend before trying to call methods based on this error I get:
Fatal error: Class 'Zend_Service_Amazon' not found in /public_html/path/zend.php on line 3

I know Zend is installed based on the php -v output of:
Zend Engine v2.2.0, Copyright (c) 1998-2010 Zend Technologies
    with the ionCube PHP Loader v4.2.2, Copyright (c) 2002-2012, by ionCube Ltd., and
    with Zend Optimizer v3.3.9, Copyright (c) 1998-2009, by Zend Technologies

So how do I find out where it resides and how to include it in my php script?
If it makes a difference, I'm using cPanel.

A: *

*Based on the php -v output we can say that Zend Optimizer is installed. Nothing about Zend Framework there

*Zend Framework is a set of php scripts, nothing else. You don't need to have it installed on the server

*There is no way rather than finding through all the filesystem if ZF is installed somewhere

*As long as it is a good idea to rely on a particular software version - just distribute your script with zend framework

A: The Zend Engine is the interpreter for PHP and has nothing to do with the Zend Framework.
The Zend Framework is probably not installed on your server unless you have installed it yourself. See the quick start for more information and instructions on where and how to install Zend Framework.


text:
Q: How can I use an input without interfering with the user text input? Context: Socket based Chat - Python 3.9 Context:
I'm writing some Python scripts to build a realtime chat using sockets. I got to allow comunication, data flow and different message types and options. The problem is that the user needs a command input to operate the chat and everytime I call print() function, the text gets printed between the user input, nevertheless the user input keeps data integrity. What can I do to keep the user input clean all the time?
Client script:
def StablishConnection():
    ...

def SetConfiguration():
    ...

#  This one is for listening
def ListenServer():
    while True:
        global SERVER_SOCKET, BUFFER_SIZE
        try:
            data = SERVER_SOCKET.recv(BUFFER_SIZE).decode('utf-8')
            print(data)
        except Exception:
            pass

#  This one is for writing
def ChatRoutine():
    global SERVER_SOCKET, NICKNAME
    while True:
        try:
            mensaje = input(f'@{NICKNAME}: ')
            if not mensaje: continue
            SERVER_SOCKET.sendall(f'{MessageType.CONTENIDO_TEXTO.value}\{NICKNAME}\{mensaje}'.encode('utf-8'))
        except Exception:
            pass

if __name__ == '__main__':
    if len(sys.argv) > 1:
        HOST = sys.argv[1]

    StablishConnection()
    SetConfiguration()

    writing = threading.Thread(target=ChatRoutine)
    writing.setDaemon(True)
    writing.start()

    listening = threading.Thread(target=ListenServer)
    listening.setDaemon(True)
    listening.start()
    listening.join()

I hope you could give some clue or something, I've struggling with this for about 2 days. Thank you all!!!


text:
Q: System Property for VM arguements in IntelliJ Idea 14 In IntelliJ 14, I intend use a environment Variable's value for a VM argument, but intelliJ doesn't seem to understand. It variable name as it is as String.
How to use Environment Variable for VM arguments in IntelliJ 14.(Refer Screenshot below for what I have already tried)

Thanks for the help and support


text:
Q: How to add a new network device on CentOS 7? My VPS is assigned two IPs but "ip a" shows only one real network interface eth0 and one loopback interface lo. I copy /etc/sysconfig/network-scripts/ifcfg-eth0 to  /etc/sysconfig/network-scripts/ifcfg-eth1 and edit it to reflect the new ip. But systemctl restart network fails with the error: Bringing up interface eth1:  Error: Connection activation failed: No suitable device found for this connection.
So how can I add a new device for setting up eth1? Or, I cannot add a new device without adding another real network adapter? Then, can  I assign the two IPs to the same interface eth0? How?
Update:
I follow @A.B's method but still cannot make it work:
TYPE=Ethernet
BOOTPROTO0=none
NAME0=eth0
DEVICE0=eth0
ONBOOT0=yes
PREFIX0=24
IPADDR0=x.x.x.x
NETMASK0=255.255.255.0
GATEWAY0=x.x.x.1

TYPE=Ethernet
BOOTPROTO1=none
NAME1=eth1
DEVICE1=eth1
ONBOOT1=yes
PREFIX1=24
IPADDR1=y.y.y.y
NETMASK1=255.255.255.0
GATEWAY1=y.y.y.1

The following configuration is not working as well:
TYPE=Ethernet
BOOTPROTO0=none
NAME0=eth0
DEVICE0=eth0
ONBOOT0=yes
PREFIX0=24
IPADDR0=x.x.x.x
NETMASK0=255.255.255.0
GATEWAY0=x.x.x.1

TYPE=Ethernet
BOOTPROTO1=none
NAME1=eth0:1
DEVICE1=eth0
ONBOOT1=yes
PREFIX1=24
IPADDR1=y.y.y.y
NETMASK1=255.255.255.0
GATEWAY1=y.y.y.1

The systemctl restart network command succeeds but ifconfig shows only one interface eth0 and one lo interface.
Update:
Use the corrected configuration in @A.B's answer and use ip a, it works! The two ips are shown under the interface eth0.

A: You can configure the two IP addresses on the same interface.
This was documented in RHEL 6 but doesn't appear anymore in RHEL 7's documentation. Presumably this configuration is being phased out (eg: to the use of NetworkManager and nmtui) so this less frequent setting isn't officially documented anymore. As usual it's exactly the same with CentOS 6/CentOS 7.

IPADDRn=address
where address is the IPv4 address and the n is expected to be consecutive positive integers starting from 0 (for example, IPADDR0).
It is used for configurations with multiple IP addresses on an
interface. It can be omitted if there is only one address being
configured.

The content of the script /etc/sysconfig/network-scripts/network-functions shows it's still valid syntax:

expand_config ()
{
    local i=0 val
    for idx in '' {0..255} ; do
        ipaddr[$i]=$(eval echo '$'IPADDR$idx)
        if [ -z "${ipaddr[$i]}" ]; then
            [ "$idx" ] && [ $idx -ge 2 ] && break
            continue
        fi
        prefix[$i]=$(eval echo '$'PREFIX$idx)
        netmask[$i]=$(eval echo '$'NETMASK$idx)
        broadcast[$i]=$(eval echo '$'BROADCAST$idx)
        arpcheck[$i]=$(eval echo '$'ARPCHECK$idx)
        arpupdate[$i]=$(eval echo '$'ARPUPDATE$idx)

So in /etc/sysconfig/network-scripts/ifcfg-eth0 just change IPADDR= into IPADDR0= plus IPADDR1= and do the same for other similar settings in the list just above (eg: if you were using NETMASK= , change it into NETMASK0= plus NETMASK1= etc.).
UPDATE (after OP made configuration contents available): The only entries concerned in the list just above are these (only if initially used):
PREFIX
NETMASK
BROADCAST
ARPCHECK
ARPUPDATE

not any other and in particular not:

*

*NAME
There is only one interface. In addition using alias addresses as interface (eg: eth0:1) should absolutely be avoided, it's an obsolete concept that has become useless and prone to mistakes when configuring other settings. It was never suggested in this answer.

*GATEWAY
There is only one default route (even when actually having multiple interfaces which is not the case here). Multi-homing where two different separate routes to Internet are possible is a different beast and can't be answered in this same question here.
Then in the end the ifconfig command should never be used (it's part of the obsolete API that cannot display correctly multiple IPv4 addresses (on a single interface) that don't have a compatibility label). Instead use:
ip address

or ip -br address to display the configured addresses on the host interface(s). Likewise the command to display routes on Linux should better be:
ip route

instead of route.

In the end the configuration in ifcfg-eth0 should (only) be:
TYPE=Ethernet
BOOTPROTO=none
NAME=eth0
DEVICE=eth0
ONBOOT=yes
PREFIX0=24
IPADDR0=x.x.x.x
NETMASK0=255.255.255.0
PREFIX1=24
IPADDR1=y.y.y.y
NETMASK1=255.255.255.0
GATEWAY=x.x.x.1

The same gateway x.x.x.1 will in the end be used even for routing the y.y.y.y address, unless the host provider provided a detailed routing documentation telling otherwise (and in which case this would require a separate question anyway, because the configuration isn't only about ifcfg-eth0 anymore and is difficult to grasp). It's even possible that the 2nd address's prefix/netmask PREFIX1 should be 32 instead of 24 (and redundant NETMASK1 then 255.255.255.255), but this can't be known without the host provider's documentation and probably doesn't matter.


text:
Q: Целочисленное деление возвращает тип float В коде, в выделенной процедуре(24 строки), нужно полученную дату в формате unixtime преобразовать в целое число - определённый час по расписанию.
def post(date):  # date = 1637855378
    ...
    post_date = (date % hours(24)) // hours() # hours(t)=t*3600
    ...
    print(f'{post_date + 3}:00, {type(post_date)}')

Иногда возвращает тип float, но в основном int
>>> 15.0:00, <class 'float'>

Троеточие - то, что не влияет на результат.
Я конечно понимаю, что это можно исправить через int(post_date), но хочу разобраться в ошибке.
Код работает онлайн на Heroku(возможно у них там какие-то проблемы, но я очень сомневаюсь) такая "ошибка" начала выходить пару дней назад(23 ноября, но могло и раньше).

A: Оператор // при работе с целыми числами int возвращает int, а при работе с float возвращает float


text:
Q: Exclude WSL 2 VM from Windows Defender I'm trying to exclude my Ubuntu VM in WSL 2 running in an up to date Windows 11 Pro installation.
The problem is that my local build is terribly slow when Windows Defender is active.
Setup is as follows:
Java, maven, docker and code are all installed inside the ubuntu vm.
Im using IntelliJ 2022.1 in Windows to run and build the project using the wsl path:
\\wsl$\Ubuntu\home\<user>\<maven project>
This works and recognizes the correct JDK etc. from the VM.
The problem is that the process "Antimalware Service Executable" is blocking all I/O and makes the build extremely slow. (stuck for 40 minutes slow)
As soon as I deactivate realtime protection of Windows Defender, the build is very fast ->
https://medium.com/@leandrocrs/speeding-up-wsl-i-o-up-than-5x-fast-saving-a-lot-of-battery-life-cpu-usage-c3537dd03c74
This of course leaves the system basically without protection, which is not a real long term solution.
I read a lot of documentation and different threads about this problem, but almost all are about WSL 1 and advising to change to WSL2.
Especially this thread has a lot of Info on this topic: https://github.com/Microsoft/WSL/issues/1932
The main approach there is to exclude specific folders from being scanned by Windows Defender, which existed in WSL 1 but not anymore in WSL 2. This is because WSL 2 now uses an ext4 image and doesn't expose the local folders anymore.
I tried the same approach for WSL2.
The most important one, is the one for my VM:
\\wsl.localhost\Ubuntu
This is not working and doesn't exclude my project inside the vm from being scanned by Windows Defender.
Does anyone have an idea how to exlude folders / files from WSL 2 VMs?
My Windows Defender Exclusions

A: Turns out Microsoft has something called Credential Guard which uses virtualization based security. E. g. using Hyper-V in Defender security scans.
I cannot say how or why this got enabled on my machine, but it uses Hyper-V even though the optional Windows feature is disabled.
I found this only in an attempt of trying to compare performance with a new virtual machine in Oracle VirtualBox.
There virtualization only worked with software emulation, because Hyper-V was active (Hyper-V must be inactive for Virtualbox native virtualization).
Check this thread to analyze if Credential Guard is active and how to disable it:
https://social.technet.microsoft.com/Forums/en-US/8a1f9ba3-9d6b-439a-99a7-f2c318169f9c/why-is-the-hypervisor-running-even-after-hyperv-is-uninstalled-?forum=winserverhyperv
I don't know how this "feature" got enabled. On a second PC with a fresh Windows 11 installation and WSL2 this doesn't happen. After disabling it, performance went to normal with Defender being enabled.


text:
Q: Solr Facetting - Showing First 10 results and Other I am implementing a solution in Solr where I have a lot of values in my facet.
As opposed to displaying a long list of values(facets) down the side of my page I want to display the top 10. And also have one for other.
For instance I would be faceting on Nationality.
So, I do not want to have a list of every nationality, Nor do I want a "see all" button.
What I require is the top 10 nationalitys and then "Other".
When a user clicks on other, it facets on this?

A: This is quite easy in Solr.. All you need to do is add a
&facet.limit=10
e.g.
http://solrserver:8080/solr/select&version=2.2&q=solr&start=0&rows=0&indent=on&facet=on&facet.field= nationality&facet.limit=10

to your request and you should be able to limit the results.
For more information you can check out my blog post on faceting in solr:
http://www.craftyfella.com/2010/01/faceting-and-multifaceting-syntax-in.html
or the solr wiki here:
http://wiki.apache.org/solr/SimpleFacetParameters#facet.limit


text:
Q: Jasper + Struts2 Multiple reports in one action In struts.xml file
<action name="myJasperTest" class="com.sample.SupplierEnquiryReport">
            <result name="success" type="jasper">
                <param name="location">/reports/xyz.jasper</param>
                <param name="dataSource">myList</param>
                <param name="format">PDF</param>
            </result>
        </action>

I need to return multiple pdf files after one action.
Is it possible?

A: No, but from your UI JSP you can:

*

*open multiple actions, each one returning a PDF;

*open another JSP, with multiple <iframe>, each one pointing (with src attribute) to a different Action (or better, to the same, but passing different parameters), and returning a PDF.

Then several pages each one with a PDF, or a big page with several iframes, each iframe with a PDF.


text:
Q: Why do we see a default IIS page on a system where iis is enabled when we enter a public IP? I am navigating to my public Ip.On that ip/system IIS is running.By default we i get the IIS start page though I have no hosted website in inetpub/wwwrooot.What is the reason for this?

A: Open the IIS. Navigate to Sites > Default Web Site. As shown in this image: https://gyazo.com/fd237a8c74e66c15ff1d9773db7c587a
Open Default Documents, you will see the list of files that IIS will look into wwwRoot folder and display that file content. iisstart.htm is one of them and htm/html page don't need any specific tool to run.

A: Did you check If there is a default website running? It is probably running some sort of a default website.