text:
Q: Using dplyr mutate_at with custom function I want to take two variables from a table and divide them by a third variable and add these computations as two new columns. The mutate_at gets me very close but within the custom function, f below, I want to access another column in the data set. Any suggestions or alternate tidy tools approaches?
library(dplyr)
# this works fine but is NOT what I want
f <- function(fld){
  fld/5
}

# This IS what I want where wt is a field in the data
f <- function(fld){
  fld/wt
}

mutate_at(mtcars, .vars = vars(mpg, cyl), .funs = funs(xyz = f))

# This works but is pretty clumsy
f <- function(fld, dat) fld/dat$wt
mutate_at(mtcars, .vars = vars(mpg, cyl), .funs = funs(xyz = f(., mtcars)))

# This is closer but still it would be better if the function allowed the dataset to be submitted to the function without restating the name of the dataset

f <- function(fld, second){
  fld/second
}

mutate_at(mtcars, .vars = vars(mpg, cyl), .funs = funs(xyz = f(., wt)))

A: Maybe something like this?
f <- function(fld,var){
    fld/var
}

mtcars %>%
    mutate_at(vars(mpg,cyl), .funs = funs(xyz = f(.,wt)))

Edit (2020-08-24):
As of second semester of 2020, with the launch of dplyr 1.0.0, mutate_at has been superseded by combining mutate with the across function:
mtcars %>%
    mutate(across(c(mpg, cyl), ~ f(.,wt), .names = "{col}_xyz"))

A: Updated version for dplyr 1.0.6:
mtcars %>%
  mutate(across(c(mpg, cyl), ~ . / wt))

Or this, which may be slower
mtcars %>%
  mutate(across(c(mpg, cyl), `/`, wt))

Previous answer:
library(tidyverse)
f <- function(num, denom) num/denom

mtcars %>%
  mutate_at(vars(mpg, cyl), f, denom = quote(wt))

Although in this specific example, a custom function isn't needed.
mtcars %>%
  mutate_at(vars(mpg, cyl), `/`, quote(wt))

A: Why not simply
mutate(mtcars, mpg2 = mpg / wt, cyl2 = cyl / wt)

A: There is a cur_data() function that will help make the mutate_at() call more compact because you will not have to specify a second argument to the function that is being applied to each column:
f <- function(fld){
  fld / cur_data()$wt
}
mutate_at(mtcars, .vars=vars(mpg, cyl), .funs=funs(xyz = f))

Additional notes:

*

*If you need the function to reference a grouping variable, use cur_data_all()

*mutate_at is now superseded by mutate(.data, across()), so it would be better to do

mtcars %>% mutate(across(.cols=c(mpg, cyl), .fns=f, .names='{.col}_xyz'))


text:
Q: finishing activity on ProgressDialog's OnCancelListener does not work In my activity i load some data from a web service, during this i show a ProgressDialog to user ... i want the user to be able to close the Activity on pressing BACK D-Pad key.
I have done it as follows:
public class MyActivity implements OnCancelListener {
    /*  ...  */

    public void startDialog() {
        ProgressDialog pd = ProgressDialog.show(
            MyActivity.this,    // Context
            "",                 // title for dialog
            "Loading...",       // message for dialog
            true,               // indeterminate?
            true,               // cancellable?
            this                // onCancelListener()
        );
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        // I want to finish() this activity when dialog is canceled
        finish();
    }
}

You can see that i am finishing current activity in onCancel() method of Dialog's OnCancelListener interface. But this method is not called when i press BACK during the dialog is visible. The dialog disappears but onCancel is not called.
Y?

A: Perhaps it's android restriction. Try it using handler
public class MyActivity implements OnCancelListener {
    /*  ...  */

    private Handler mHandler = new Handler(){

        @Owerride
        public void handleMessage(Message message) {
        switch (message.what) {
        case 1:{
            finish();
        } break;
            }
        }
    };

    public void startDialog() {
        ProgressDialog pd = ProgressDialog.show(
            MyActivity.this,    // Context
            "",                 // title for dialog
            "Loading...",       // message for dialog
            true,               // indeterminate?
            true,               // cancellable?
            this                // onCancelListener()
        );
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        mHandler.sendEmptyMessage(1);
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: API or other method for accessing Finder icon preview images It appears that macOS now generates preview images for certain files (notably RAW image files) that are not custom icons but something else. (You can toggle them on/off in latish model macOS via "show icon preview" in Finder window "Show View Options".)
I'd love to be able to either obtain these images or use the API that generates them but I'm obviously googling the wrong terms. The usual APIs will get me the file icon (which is usually a generic document icon) and not the preview. The tricks for getting custom icons (e.g. .DS_Store etc.) do not apply.

A: The tool you want is qlmanage. In particular, look at qlmanage -t (thumbnail) and qlmanage -p (preview). By default, it opens a viewer for you. If you want to generate files to process yourself, see the -o option. For example:
qlmanage -t image.png -o .

This will create a thumbnail file called ./image.png.png (it attaches .png to whatever the filename is).
If you want to build your own tools around this, see the QuickLook framework.

A: A little more info w.r.t. using QuickLook framework. The key method is QLThumbnailImageCreate (QuickLook previews are PDFs which are not what I want and likely not what someone doing something similar wants).
Even though the function name indicates that it creates thumbnails, it can create an image of any size (and the size parameter dictates a maximum dimension).


text:
Q: Text pasted into VS Code Has Spaces but Doesn't Register All Spaces I pasted some text from a MS Word document into VS Code and when it renders, it doesn't render all the spaces.
I took a closer look and in the image below (screenshot from VS Code) noticed how there is a "dot" between the y and the a, but there is no "dot" between the a and the T. When this renders, the a and the T are right next to each other. Any idea why this happens or how to fix?

I tried modifying settings.json to include:
"editor.formatOnPaste": true,
"editor.formatOnSave": true,

But that didn't fix my problem. Has anybody ever seen this before, any ideas?


text:
Q: Auto detach entity from dbcontext services.AddDbContextPool<SecurityDBContext>(options =>
                options.UseSqlServer(GlobalConfig.Configuration["ConnectionStrings:DefaultConnection"],
                b => b.UseQuerySplittingBehavior(QuerySplittingBehavior.SingleQuery))
        );

This is how I added dbcontext,I used AddDbContextPool so the instance will be use over and over again for performance.
db.Entry(new AdminBlockClientConfig()
        {
            ActionId = input.aid.ToLongReturnZiro(),
            MaxValue = input.value.ToIntReturnZiro(),
            IsActive = input.isActive.ToBooleanReturnFalse(),
            SiteSettingId = siteSettingId.ToIntReturnZiro()
        }).State = EntityState.Added;
        db.SaveChanges();

This is my code for adding new entity.
 readonly SecurityDBContext db = null;
    static List<AdminBlockClientConfig> AdminBlockClientConfigs = null;

    public AdminBlockClientConfigService(SecurityDBContext db)
    {
        this.db = db;
    }

This is my service constructor
services.AddScoped<IAdminBlockClientConfigService, AdminBlockClientConfigService>();

And this is my service injection config
The problem:
I don't have any validation for ActionId inside of my add new entity so if the user posts -1 for ActionId the entity will not be insert into SQL Server (relation problem) the system raises an exception and everything is as planed but the main problem is that one of the instance of SecurityDBContext become corrupted and I am no longer be able to call save change on that instance because the entity instance is still attached to dbcontext.
What is need:
It would be great if I can detach the entity after an error automatically so I can save the context.
I know how to detach entity from dbcontext, I need to its happen automatically (there is so many validation need to be added to project and I can not put time for those validation and if I put that time there will be high change of missing some place and its will be bug that can destroy my application and for performance I don't like to change the way I added dbcontext instance).
Thanks for your time.
edited: AddDbContextPool is not the problem, if one of my services add invalid data to dbcontext the other services can not use that dbcontext


text:
Q: How to build third party references through build task in Azure DevOps build definition Am working on ASP.Net Web Application and Azure DevOps CI&CD Pipelines through GitHub repository. In my project, I have used some third party references(.dll's) which are running finely in local. But when am trying to build application through build pipeline in Azure DevOps after checking my code into GitHub, then am getting errors in the build task regarding

The type or namespace name 'xxxx' could not be found(are you missing a using directive or an assembly reference)

This is happening due to build task is unable to recognize the third party reference .dll files at the time of building which is in my local path. Can you please suggest me to "How to build the third party references in Build task"

A: You can have third party references in Azure devOps Artifacts & use Nuget restore to get packages using option "Feed to use" -> "Feed(s) I select here" radio button
sample


text:
Q: Using Flutter Downloader plugin, after download app closes **I use Flutter Downloader Package After complete download some file , my app closes automatically and disconnecte to the android studio. Any one help me to find soltutions.
    final status = await Permission.storage.request();
            if (status.isGranted) {
              await downloadPDF();
            }

downloadPDF() async {
    final externalDir = await getExternalStorageDirectory();
    taskId = await FlutterDownloader.enqueue(
      url: pdfURL,
      savedDir: externalDir.path,
      fileName: "Flamingo Order Details",
      showNotification: true,
      openFileFromNotification: true,
    );
  }

Here is my console error:
I/flutter (15913): Fatal: could not find callback
F/libc    (15913): Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0 in tid 15956 (1.raster), pid 15913 (le.order_system)
*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
Build fingerprint: 'motorola/chef/chef_sprout:10/QPTS30.61-18-16-8/03acd:user/release-keys'
Revision: 'pvt'
ABI: 'arm64'
Timestamp: 2021-04-23 16:39:38+0530
pid: 15913, tid: 15956, name: 1.raster  >>> com.example.order_system <<<
uid: 10870
signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0
Cause: null pointer dereference
    x0  000000741e5a6478  x1  00000074841cfa00  x2  0000000000000001  x3  0000000000000000
    x4  0000000000000000  x5  00000000ffffffff  x6  00000000ffffffff  x7  0000000b96c6a75c
    x8  0000000080000081  x9  658adf78f7e836ee  x10 0000000000000000  x11 0000000000000000
    x12 0000000000000001  x13 000000747b19fe80  x14 0000007489a0a280  x15 0000000000000000
    x16 000000747b19b050  x17 0000007515c9787c  x18 000000741d05e000  x19 000000741e5a6478
    x20 00000074841cfa00  x21 0000000000000001  x22 0000000000000000  x23 00000074843db380
    x24 000000741e5a7020  x25 000000741e5a7020  x26 0000000000000000  x27 0000000000000001
    x28 0000000000000043  x29 000000741e5a6450
    sp  000000741e5a6420  lr  000000747b013f84  pc  000000747b01c378
backtrace:
      #00 pc 00000000001d8378  /vendor/lib64/egl/libGLESv2_adreno.so (BuildId: 22cc95e0051ae85072c405eeeeeb312d)
      #01 pc 00000000001cff80  /vendor/lib64/egl/libGLESv2_adreno.so (BuildId: 22cc95e0051ae85072c405eeeeeb312d)
      #02 pc 00000000000207b0  /system/lib64/libEGL.so (android::eglSwapBuffersWithDamageKHRImpl(void*, void*, int*, int)+316) (BuildId: 248ba7f2d80e7bb9952a20e1c3493c86)
      #03 pc 000000000001d0a8  /system/lib64/libEGL.so (eglSwapBuffers+80) (BuildId: 248ba7f2d80e7bb9952a20e1c3493c86)
      #04 pc 00000000012ec528  /data/app/com.example.order_system-8XYsushVsEZPOltQ3k8npA==/lib/arm64/libflutter.so (BuildId: e14966237eb013b063fed6484195268f7398b594)
Lost connection to device.

A: Maybe it is late but it may help others. Recently I faced this error and I solved it. Your UI is rendering in Main isolate and your download events come from background isolate. Because codes in callback are run in the background isolate, so you have to handle the communication between two isolates. Usually, communication needs to take place to show download progress in the main UI. Implement the below code to handle communication:
import 'dart:isolate';
import 'dart:ui'; // You need to import these 2 libraries besides another libraries to work with this code

final ReceivePort _port = ReceivePort();

@override
  void initState() {
    super.initState();

    IsolateNameServer.registerPortWithName(_port.sendPort, 'downloader_send_port');
    _port.listen((dynamic data) {
      String id = data[0];
      DownloadTaskStatus status = data[1];
      int progress = data[2];
      setState((){ });
    });

    FlutterDownloader.registerCallback(downloadCallback);
  }

@override
  void dispose() {
    IsolateNameServer.removePortNameMapping('downloader_send_port');
    super.dispose();
  }

  static void downloadCallback(String id, DownloadTaskStatus status, int progress) {
    final SendPort send = IsolateNameServer.lookupPortByName('downloader_send_port')!;
    send.send([id, status, progress]);
  }

void _download(String url) async {
    final status = await Permission.storage.request();

    if(status.isGranted) {
      final externalDir = await getExternalStorageDirectory();

      final id = await FlutterDownloader.enqueue(
          url: url,
          savedDir: externalDir!.path,
        showNotification: true,
        openFileFromNotification: true,
      );
    } else {
      print('Permission Denied');
    }
  }

Call _download(url) function in your button and you are ready to go.
N.B: I am using sound null safety in my app and for this reason I am using null aware operator in this line of code:
final SendPort send = IsolateNameServer.lookupPortByName('downloader_send_port')!;


text:
Q: How to ask when a product will go bad idiomatically? How to ask when a product will go bad?
Maybe:

*

*What is its expiry/exparation date?

*How long until its expiry/exparation date?

*How long until its shelf life elapses?

*How long until the milk expires?

*How long until the milk is past/passes/reaches its expiry date?

A: Often, an expiration date, "best by" date, or "sell by" date is printed on the packaging, so one need not ask. But if one is going to ask, this can be phrased in quie a few ways that will be natural.
In my experience, in the US, the term "expiration date" is much more common than "expiry date".
For food in particular, a "best by" date is also common. This means a date after which some undesirable changes may occur. The food will usually be safe past this f=date, but not in top quality much past it.
A "sell by" date is also common for food. This means that the store is not allowed to sell the product after that date, but it is calculates to that the food will still be good for several days on that date, allowing for a possible delay by the buyer in using the food. So a "sell-by" date would be earlier than the "best by" date, which in turn would be earlier than an "expiration date" Products other than food mostly use only an "expiration date" or in soem cases a "good thru" date.
Now lets consider some alternate phrasings of such a question:

*

*"What is its expiration date?"
This is a very common way of asking about how long the product is good for.

*"How long until its expiration date?"
This is a bit less common, and in my view a bit less natural, but would be clearly understood.

*"How long until its shelf life elapses?"
This is unusual, and might seem a bit odd to a native US speaker, although it would be understood.

*"What is its shelf life?" or "How long is its shelf life?"
This is more common than the previous version. It is not likely to be asked of comparatively short duration foods such as milk or meat, but might be used of staples such as flour or shelf-stable broth, and more likely yet of non-food items like cleaners and medication.

*How long until the milk expires?
This is also a bit unusual, but would be easily understood. Such questions are mo often phrase using "when" than "how long" in my experience, and "expires" is more often used when speaking about medication or perhaps cleaning supplies than food. In those cases usually a year and month are given, not a day.

*"How long until the milk is past/passes/reaches its expiry date?"
Here again a "when" quetion is more likely than a "how long" question, and "expiry date" is significantly less common than "expiration date", in my experience.

*"How long is that good for?"
This is more casual than any of the options above, but reasonably common.

*"When does this medicine expire?"
A very common phrasing when medicine si involved.


text:
Q: How to set default value in @Html.DropDownListFor using Asp.net mvc razor? I Have MVC Razor view with DropdownListFor. I wanna set a default value to that DropdownListFor. I have bind dropdown for using viewbag. and in the viewbag come list and in the list store one Flag property. now i want Flag is 1 then this value I wanna set in the dropdown list. always in the list Flage = 1 is only one object come and other object flag = 0.
This is my view =>
@{ var CategoryList = ViewBag.Category as IEnumerable<ABCBAL.CategoryBAL>; }
                @Html.DropDownListFor(model => model.CatId, new SelectList(CategoryList , "CatId", "Category"), new { @class = "form-control", @id = "ddlCat"})

This my controller method =>
public ActionResult EditCat(int UserId)
{
    Users Userobj = new Users();
    ViewBag.Category = Userobj.GetAllcategoryById(UserId).Data;
    return PartialView(Cat);
}

This is my User.cs class Method =>
public Status GetAllcategoryById(int UserId)
    {
            Status Status = new Status();
            DataSet ds = DataAccess.ExecuteDataset(Settings.ConnectionString(), "GetAllcategoryById", UserId);

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                List<CategoryBAL> CatList = new List<CategoryBAL>();

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    CategoryBAL objCat = new CategoryBAL();

                    objCat.CatId = Convert.ToInt32(ds.Tables[0].Rows[i]["CatId"]);
                    objCat.Category = ds.Tables[0].Rows[i]["Category"].ToString();
                    objCat.Falge = Convert.ToInt32(ds.Tables[0].Rows[i]["Falge"]);

                    CatList.Add(objCat);
                }

                Status.Result = true;
                Status.Data = CatList;
            }
            else
            {
                Status.Result = false;
            }
        return Status;
    }

This is my code and here one flage is come 1 then i want to flage is 1 then default selected in the drop down.

A: You can set the value from your model like this:
 @Html.DropDownListFor(model => model.CatId, new SelectList(CategoryList , "CatId", "Category"), new { @class = "form-control", @id = "ddlCat",**@value = Model.CatId**})


text:
Q: Is it possible to complete Moonlit Grotto without using the teleporter in the midboss room? I have played Oracle of Ages several times, and each time this has bothered me.
In all of the dungeons in Oracle of Seasons, and I believe all of them in Oracle of Ages with the exception of Moonlit Grotto, I was able to finish the dungeon without using the red teleporter that appears in the midboss room after beating the midboss.  However, it seemed to be necessary in order to complete Moonlit Grotto.  Is possible to complete this dungeon without teleporting to the midboss room to the entrance of the dungeon?
The problem I run into is that I need to get to the room east of the bumper on the second floor, as pictured here (star indicates where I want to go):

To do so, I need the bumper to be pointing clockwise when I reach the midboss room.  However, going to the midboss room from the west, the bumper sends me counterclockwise, so I can't get to the room with the boss key without using the teleporter to get to the room with the midboss and going south.
Is possible to complete this dungeon without teleporting to the midboss room to the entrance of the dungeon?

A: Yes, it's possible to beat the dungeon without making use of the mini-boss teleport. It's actually faster to not make use of the teleport. The way you're supposed to get around it is to just take the same route you would use to get to the boss room, and then push the block directly across from the room. This will take you back to the mini-boss room, and allow you to get to the blocker from the North with the arrows taking you to the east.
The route to get you through is:

*

*Start in the mini-boss room

*Walk south to the bumper, which will move to the left and take you to the room west of the bumper room.

*Enter the room to the North, and continue proceeding North until you hit the room with the boss door (you'll need to make use of your seed shooter along the way)

*Push the block directly across from the boss room door, and go through the new opening. Proceed down the southern path on this side of the room.

*Proceed to the the East, which will return you to the mini-boss room. Once here simply proceed South to the bumper room again and it will take you to the Eastern room.

I've edited a map of the dungeon from Neoseeker showing you the route. I had to switch to a white zig-zaggy line part-way through in order to differentiate the from the initial path you take upon leaving the mini-boss room.


text:
Q: Laravel scope custom field value for model I have a model as follows
class WorkingTime extends Model
{
    protected $table = 'working_times';
    protected $fillable = ['day', 'start_time', 'finish_time', 'user_id'];
    public function scopeAfterStart($query, $start)
    {
        return $query->where('start_time', '<=', $start);
    }

    public function scopeBeforeFinish($query, $finish)
    {
        return $query->where('finish_time', '>=', $finish);
    }
}

and I can use the following query
WorkingTime::afterStart(1200)->beforeFinish(1800)->get();

what I need to do is, in working_times table when the start_time > finish_time value, I have to check if finish_time + 2400 >= $finish. To be more specific, something like the following query has to be happened
with new_working_times as (
    select
        start_time,
        case when start_time > finish_time then
            finish_time + 2400
        else
            finish_time
        end as finish_time
)
select * from new_working_times
where finish_time > {finishTime} and start_time < {start_time}

How can I do this via eloquent and scope?


text:
Q: Extract data from webpage with Python For training purposes ,i'am trying to extract the line :
2017/01/15

from the following webpage (inspect element preview) :

                        Date
                        Notifier
                        H
                        M
                        R
                        L

                        Domain
                        OS
                        View

                        2017/02/10
                        <a href="/testarchive/

I'am confused how will i get the td parts and which parts are correct (class/id) in order to fetch the correct information with BeatifulSoup.
Thanks in advance

A: For your example you should use next thing.
from bs4 import BeautifulSoup

soup = BeautifulSoup('yor_html_source', 'html.parser')
for table in soup.find_all('table'):
     tr = table.findAll('tr')[1]
     td = tr.findAll('td')[0].text
print(td) # return 2017/02/10

If you want get just 2017/02/10	 remove text property from td variable.
BeautifulSoup4 have also cool Soup documentation

A: Gather The Data:
To get the data to process you can use urllib2
import urllib2
resource = urllib2.urlopen("http://www.somewebsite.com/somepage")
html = resource.read()
# assuming html is the example with a few more rows in the table

Process the Data:
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, "lxml")
for table in soup.findAll("table"):
    if table.attrs['id'] == 'ldeface':
        rows = table.findAll("tr")
        header = rows[0]
        date_col = [ i for i, col in enumerate(header.findAll("td")) if col.text == "Date"][0]
        for row in rows[1:]:
            print row.findAll("td")[date_col].text

Result:
2017/02/10
2017/02/11
2017/03/10
...

You can extract other columns based on the text in the cell, the id attribute like I did for the table, or the class attribute in a similar way to the table

A: from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
tags=[str(tag) for tag in soup.find_all()]
for elem in tags:
   if '' in elem and len(elem.split('/')==4):
       print(elem.text)

Go through all the tags, if the tag is a td and has the right amount of slashes, print it.

A: You can install urllib3 and bs4 via pip:
python3 -m pip install urllib3
python3 -m pip install beautifulsoup4

After that the python code should look something like this:
#!/usr/bin/python3
# -*- coding: UTF-8
import urllib3
from bs4 import BeautifulSoup
http = urllib3.PoolManager()
page = http.request("GET","http://HOST.TLD/CONTENT")
if page.status == 200:
  html = page.data
  soup = BeautifulSoup(html, "html.parser")
  h1 = soup.find('h1') # we are interested only in the 1st
  print("H1: %s" % (h1))


text:
Q: (Display pyramid) Write a program that prompts the user to enter an integer from 1 to 15 and displays a pyramid I want to create a program that creates a pyramid. Its size (number of lines) is determined by the user input.
This is what I have tried so far. It is only showing one half of the pyramid.
#include <iostream>

using namespace std;

int main()
{
    //delcare all the variables
    int n, m, i, j;

    cout << "Enter the number of lines: ";
    cin >> n;

    for (i = 1; i <= n; i++)
    {
        //prints the spaces in between row and column using loop
        for(j = 1; j <= n - i; j++)
        {
            cout <<" ";
        }

        //prints the element of using loop
        for (j = i; j >= 1; j--)
        {
            cout <<" ";
        }

        //prints first and last elements using loop
        for (j = 2; j <= i; j++)
        {
            cout << " " << j << " ";
        }

        //elements in new line printed
        cout << "\n";
    }

    return 0;
}

I was expecting a whole pyramid when I entered the number 7 but the current output is only half of the pyramid, namely from 2 up to 7.

A: Declare variable as close to where they're used. Give them meaningful names:
#include <iostream>
#include <iomanip>

int main()
{
    std::cout << "Enter the number of lines: ";
    int num_lines;
    if (!(std::cin >> num_lines) || num_lines < 1 || 15 < num_lines) {
        std::cerr << "Input error. Bye :(\n\n";
        return EXIT_FAILURE;
    }

    for (int current_line{ 1 }; current_line <= num_lines; ++current_line) {
        for(int spaces = 0; spaces < num_lines - current_line; ++spaces)
            std::cout << "   ";

        for(int number = current_line; number; --number)
            std::cout << std::setw(2) << std::right << number << ' ';

        for (int number = 2; number <= current_line; ++number)
            std::cout << std::setw(2) << std::right << number << ' ';

        std::cout.put('\n');
    }
}

Sample Output:
Enter the number of lines: 15

                                           1
                                        2  1  2
                                     3  2  1  2  3
                                  4  3  2  1  2  3  4
                               5  4  3  2  1  2  3  4  5
                            6  5  4  3  2  1  2  3  4  5  6
                         7  6  5  4  3  2  1  2  3  4  5  6  7
                      8  7  6  5  4  3  2  1  2  3  4  5  6  7  8
                   9  8  7  6  5  4  3  2  1  2  3  4  5  6  7  8  9
               10  9  8  7  6  5  4  3  2  1  2  3  4  5  6  7  8  9 10
            11 10  9  8  7  6  5  4  3  2  1  2  3  4  5  6  7  8  9 10 11
         12 11 10  9  8  7  6  5  4  3  2  1  2  3  4  5  6  7  8  9 10 11 12
      13 12 11 10  9  8  7  6  5  4  3  2  1  2  3  4  5  6  7  8  9 10 11 12 13
   14 13 12 11 10  9  8  7  6  5  4  3  2  1  2  3  4  5  6  7  8  9 10 11 12 13 14
15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15

Explanation for a Sample Input of 15:
I am using std::wetw() to pad the output of the numbers to two digits. std::rightright-justifies the output inside those two characters: 1 ~> " 1" but 11 ~> "11". I do that so i don't have to write more complicated code when I am printing the spaces at the beginning of each line. One printed number is alsways three characters wide - two for the number and a following space to seperate the numbers.
Talking of space caracters to begin each line: At the base of the pyramid all numbers from 15 to 1 and up to 15 again get printed. So the number of spaces preceeding the numbers must be 14 times three for the first line, 13 times three for the second line, 12 times three for the third and so on until it are zero times three spaces in the last, the 15th line. So as you can see the number of spaces is num_lines - current_line times three. That's what the first inner for()-loop does.
The other two inner for()-loops should be self-eplanatory. One counts down from current_line to 1 and the other back up again to current_line. The loop counting upwards starts at 2 to not print two times the number 1.


text: Q: Find the degree of B-Tree to store number of keys? Suppose you are storing 32 bits keys in a B-tree and each block in the hard disk contains 1024 bits. What is the best value for the degree d of the B-tree?


text:
Q: How many $5$-digit numbers are there, so that $0,1$ and $2$ are NOT included, $3,4$ and $5$ have to be included I have the following question.
How many $5$-digit numbers are there, so that the following conditions are satisfied:

*

*$0,1$ and $2$ are NOT included

*$3,4$ and $5$ have to be included

The list of possible numbers to choose from is $(3,4,5,6,7,8,9)$. As we know, $3,4$ and $5$ have to be included in every number, for example $33475$, $54339$ etc.
I tried to do this as follows:
For the $1.$ digit, I can choose $3,4$ or $5$. So, I basically have ${3 \choose 1}$ choices. For the $2.$ digit, I have $2$ numbers to choose from, for example $4$ or $5$ if $3$ is the 1. digit, $3$ or $5$ if $4$ is the 1. digit etc. So, that's ${2 \choose 1}$. For the $3.$ digit there is $1$ number to choose as per reasoning for choosing the $2.$ number. That's basically ${1 \choose 1}$. For the $4.$ and $5.$ digit, there are ${7 \choose 1}$ possibilities respectively, because any number from the list can be chosen.
At the end I get ${3 \choose 1} \cdot {2 \choose 1} \cdot {1 \choose 1} \cdot {7 \choose 1} \cdot {7 \choose 1} = 3 \cdot 2 \cdot 1 \cdot 7 \cdot 7 = 294$ possible numbers. Now, you can permute those choices between the digit places. There are $5$ digits, so it would be $5! = 120$ possible permutations. In the end I got $294 \cdot 120 = 35280$ numbers. However, the problem is that there are not 120 such permutations, because for some cases one number is counted multiple times.
I know from my class that the answer is $1830$. And I also got the hint from my professor to use the inclusion-exclusion principle. But with that I have problems to start.
So, could somebody help me either how to calculate this with the inclusion-exclusion principle OR with the way I tried to do this, i.e. how to NOT multiple count those numbers.

A: The easiest is to apply Principle of Inclusion Exclusion:
Count of five digit numbers with digits $3$ - $9$ where at least one of $3, 4, 5$ are missing is
$3 \cdot 6^5 - 3 \cdot 5^5 + 4^5$
Now subtracting it from $7^5$ should give us the count of numbers where all three digits $(3, 4, 5)$ appear at least once. So the answer is,
$7^5 - (3 \cdot 6^5 - 3 \cdot 5^5 + 4^5) = 1830$

If you are working cases by case, there are $3$ cases.
$(i)$ three of five spaces are taken by $3, 4, 5$
$(ii)$ four of five spaces are taken by $3, 4, 5$
$(iii)$ all five spaces are taken by $3, 4, 5$
$(i)$ We choose three spaces and place $3, 4, 5$. Rest two spaces are taken by $6, 7, 8, 9$
So count of numbers $ ~ = \displaystyle {5 \choose 3} \cdot 3! \cdot 4^2$
$(ii)$ We choose four spaces and choose one from $3, 4, 5$ that appears twice. Remaining space is taken by $6, 7, 8, 9$
So count of numbers $ ~ = \displaystyle {5 \choose 4} \cdot 3 \cdot \frac{4!}{2!} \cdot 4$
$(iii)$ consists of one of $3, 4, 5$ appearing three times or two of them appearing two times.
So that leads to,
$ \displaystyle 3 \cdot \left[\frac{5!}{3!} + \frac{5!}{2! \cdot 2!}\right]$
Adding $(i), (ii), (iii)$ should give the same answer as we got using Principle of Inclusion Exclusion.


text:
Q: Weak pull down for SPI I am using Arduino(does not matter) and 8 x 12 bit-ADCs to read some values. I created a prototype which consists of a Shift Register(SR) and all outputs of SR are connected to individual ADC's chip-select pin. During boot, I set all output of SR as HIGH.
I select the ADC by pulling the specific output of the SR as LOW and then talk to the ADC. As soon as my communication is finished, I again set all output of SR as HIGH. This is all working.
During some testing, I found that if all SPI (ADCs) are pulled HIGH (none should be talking) and if I read MISO, I was getting some random data. I realized that MISO was floating and added a 100K pull-down (weak pulldown!) which sorted this out. After this, if I listened the MISO while all ADCs were HIGH, all I get is 0s (Yey!).
My question is that does it make sense to pull down MOSI and CLOCK as well? Will it create any problem?

A: You shouldn't need to pull down the MOSI or Clk lines.
Master Out Slave In is an output from your controller, as is the Clk line.  Unless you do something that turns those pins to inputs, they should be just fine without either pull-down or pull-up resistors.
On the other hand, Master In Slave Out is an input to the controller.  When none of your ADC chips are selected, that line does float.  It needs the resistor that you added.

A: All CMOS inputs without built-in pull-ups or pull-downs must be driven to a valid logic level. So your question isn't related to SPI or even your application: it is basic circuit design aspect of working with CMOS digital inputs.
For each CMOS digital ("logic") input you must be able to show a circuit path that leads either to positive supply or GND, at all times, in all system configurations. Pull-up/pull-down resistors are just one possible way of providing such circuit path. Another would be weak MOS drivers - typically only available if you're laying out a chip design, but sometimes MCUs and other chips have those built-in, in such a way that the driver activates immediately on power-up, fulfilling the design requirement.


text:
Q: Bottomnavigationbar item icon in flutter app I want to change the icon of an active bottomnavigationbar item, ie if the item is selected the icon is filled and if it's unselected it shows the outline.

A: Check the code below with explanations:
import 'package:flutter/material.dart';

class MainScreen extends StatefulWidget {

  @override
  _MainScreenState createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen>
    with SingleTickerProviderStateMixin {
  // we need this to switch between tabs
  TabController _tabController;
  // here we remember the current tab, by default is the first one (index 0)
  int _currentTabIndex = 0;

  @override
  void initState() {
    super.initState();
    // init the TabController
    _tabController = TabController(vsync: this, length: _Tab.values.length);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0.0,
        backgroundColor: Colors.white,
        title: Text(_getTitleForCurrentTab(_Tab.values[_currentTabIndex])), // set the title in the AppBar
      ),
      body: TabBarView(
        controller: _tabController, // we set our instantiated TabController as the controller
        children: <Widget>[
          // here we put the screen widgets corresponding to each tab
          // the order must correspond to the order given below in bottomNavigationBar
          Tab1Widget(), // these are your custom widgets for each tab you have
          Tab2Widget(),
          Tab3Widget(),
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        onTap: (int index) {
          // when a tab icon was tapped we just change the current index of the tab with the new one
          // this set state call will re-render the screen and will set new the tab as active
          setState(() {
            _currentTabIndex = index;
          });

          // also we want to change the screen content not just the active tab icon
          // so we use the TabController to go to another tab giving it the index of the tab which was just clicked
          _tabController.animateTo(index);
        },
        // here we render all the icons we want in the BottomNavigationBar
        // we get all the values of the _Tab enum and for each one we render a BottomNavigationBarItem
        items: _Tab.values
            .map((_Tab tab) => BottomNavigationBarItem(
                title: Text(_getTitleForCurrentTab(tab)), // set the title of the tab icon
                icon: Image.asset(
                  _getAssetForTab(tab),
                  width: 24.0,
                  height: 24.0,
                ))) // set the icon of the tab
            .toList(),
      ),
    );
  }

  /// Get the asset icon for the given tab
  String _getAssetForTab(_Tab tab) {
    // check if the given tab parameter is the current active tab
    final active = tab == _Tab.values[_currentTabIndex];

    // now given the tab param get its icon considering the fact that if it is active or not
    if (tab == _Tab.TAB1) {
      return active ? 'assets/tab1_active.png' : 'assets/tab1.png';
    } else if (tab == _Tab.TAB2) {
      return active ? 'assets/tab2_active.png' : 'assets/tab2.png';
    }
    return active ? 'assets/tab3_active.png' : 'assets/tab3.png';
  }

  /// Get the title for the current selected tab
  String _getTitleForCurrentTab(_Tab tab) {
    if (tab == _Tab.TAB1) {
      return 'tab1_title';
    } else if (tab == _Tab.TAB2) {
      return 'tab2_title';
    }
    return 'tab3_title';
  }
}

// Just an enum with all the tabs we want to have
enum _Tab {
  TAB1,
  TAB2,
  TAB3,
}


text:
Q: CSS Shape-Outside pushes text out of border-box only in Chrome I am using shape-outside (boundary) and clip-path (content) to have a "triangle" with text on top of a photo.
Safari and Firefox both work almost the same, but Chrome behaves strange (or perhaps right?). The text is shifted outside the box and always is pushed till the edge of the viewport. I can't define any margin or padding to them.
Screenshot shows Safari on the top/left window with correct margin and text within the orange box (H1 and P). Chrome however lets the text break out of their boxes and only stops at the very end.

Here is the code, simplified and trimmed to the bare minimum:
https://codepen.io/suntrop/pen/RwVMvzo

Chrome: Headline reaches the viewport edge on the right, but should fit/break inside the orange box. Safari and Firefox behave expected and text stays inside the ornage box

This text breaks out of the orange box (only in Chrome). Lorem ipsum, dolor sit amet consectetur adipisicing elit. Nisi inventore ut dolor voluptatem reprehenderit sapiente et molestiae officiis nesciunt repudiandae vel quia itaque, error fugiat dolores distinctio pariatur optio! Tempore!

If you strip down the headline, you see there is enough space, but still it sits at the far right.

A: Try this solution, i don't have safari, but in firefox and chrome works. For .boundary added width: 70% that fix body overflow.
RESET CSS
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

CLASS WITH CHANGES
.boundary {
  width: 70%; /* changed */
  height: 100vh;
  float: left;
  shape-outside: polygon(0 0, 100% 0, 30% 100%, 0 100%); /* changed */
  /*background: blue;*/
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
    Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
section {
  border: 2px dotted blue;
  height: 100vh;
  background: url(https://picsum.photos/1500/1000) no-repeat 0 0;
  background-size: cover;
}
.boundary {
  width: 70%; /* changed */
  height: 100vh;
  float: left;
  shape-outside: polygon(0 0, 100% 0, 30% 100%, 0 100%); /* chenged */
  /*background: blue;*/
}
.content {
  height: 100vh;
  background-color: rgba(255, 255, 255, 0.9);
  clip-path: polygon(70% 0, 100% 0, 100% 100%, 20% 100%);
  border: 1px solid red;
}

h1,
p {
  margin-top: 100px;
  margin-right: 100px;
  border: 1px solid orange;
}
h1 {
  text-align: right;
}

Chrome: Headline reaches the viewport edge on the right, but should fit/break inside the orange box. Safari and Firefox behave expected and text stays inside the ornage box

This text breaks out of the orange box (only in Chrome). Lorem ipsum, dolor sit amet consectetur adipisicing elit. Nisi inventore ut dolor voluptatem reprehenderit sapiente et molestiae officiis nesciunt repudiandae vel quia itaque, error fugiat dolores
      distinctio pariatur optio! Tempore!


text:
Q: Transact-SQL DEFAULT keyword deprecated? Why? In MSDN article
Deprecated Database Engine Features in SQL Server 2016
there is a statement on deprecation of DEFAULT keyword (among the others).
Quoted from the table:

Category: Transact-SQL
Deprecated feature: Use of DEFAULT keyword as default value.
Replacement: Do not use the word DEFAULT as a default value.
Feature name: DEFAULT keyword as a default value.
Feature ID: 187.

What is the logic behind this change? I find nothing wrong with
CREATE FUNCTION dbo.GetFirstIdByCode(@Code nvarchar(20), @ExcludeThisId int)

and in most cases, where I don't use 2nd parameter, call it like
IF dbo.GetFirstIdByCode(@Id, DEFAULT) = 0 --- etc...

Of course, I can replace DEFAULT with NULL at every call of the function. To me, this looks like anything but a progress. Why is this planned?
How should I adjust my coding style preparing for this?

A: The wording was incorrect:Erland raised a connect item for this..please see this connect for more details..
Pasting relevant items from connect item:
Depreceated feature is ..

using the word DEFAULT as the DEFAULT value.

Example:
CREATE TABLE T1
(Col1 int PRIMARY KEY,
Status varchar(10) DEFAULT 'DEFAULT' )
or
CREATE DEFAULT phonedflt AS 'DEFAULT'


text:
Q: Dojo File Caching in Worklight When using Dojo file caching with Worklight receiving a 404 Error when running in Simulator.  It appears the file being loaded is not being copied from the common area to the device.  Is there something else I need to define in my project to make that happen?  There must be a convention and I wanted to follow it going forward as I expect to have more template files in the project.
My define statement in a .js file:
define(["dojo/_base/lang", "dijit/layout/ContentPane", "dojo/dom", "dojo/text!./templates/Order.html"], function(lang, ContentPane, dom, template){
...
var cp1 = new ContentPane({
            title:"Order",
            content: lang.replace(template, someJson)
         }).placeAt("temp");

My folder structure:
In the common/js directory I have the above code in a .js file and I have a templates folder to keep the Order.html and I would expect to have other template files stored there in the future.
Error on the console:
GET http://localhost:10080/DojoProject/apps/services/preview/DojoApp/windowsphone8/1.0/default/layers/templates/Order.html 404 (Not Found)

A: It seems that the way you are specifying the path, browser tries to find the file in the "layers" folder which is sibling to "templates".
Have you tried to modify the "dojo/text!./templates/Order.html" to something like: "dojo/text!./../templates/Order.html" to navigate one level up, then go into the templates folder?
I'm not sure this will work, but I think it worths a try.


text:
Q: Connection string not getting detected in ADO.NET Entities I for the first time tried the ADO.Net Data entity model and would like to work wiht linq on it.  I did my entity connection and following code to test connection:
Public Function SaveContact(ByVal ContactValue As Contact, ByVal IsNew As Boolean) As String Implements IContactService.SaveContact
    Dim db As New salessolEntities
    db.Database.Connection.Open()
    db.Database.Connection.Close()
    Return Nothing
End Function

However, I am getting the following error:

No connection string named 'salessolEntities' could be found in the
  application config file.

The connection string is correctly set in app.config:
Default version(auto generated):
  <connectionStrings>
    <add name="SalesSolWcfLib.My.MySettings.DBConnection" connectionString="server=localhost;User Id=root;password=surpavan;database=salessol;Persist Security Info=True;Old Guids=True" providerName="MySql.Data.MySqlClient" />
    <add name="salessolEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=MySql.Data.MySqlClient;provider connection string="server=localhost;user id=root;password=surpavan;database=salessol;persist security info=True;old guids=True"" providerName="System.Data.EntityClient" />
  </connectionStrings>

A small modifiction:
  <connectionStrings>
    <add name="SalesSolWcfLib.My.MySettings.DBConnection" connectionString="server=localhost;User Id=root;password=surpavan;database=salessol;Persist Security Info=True;Old Guids=True" providerName="MySql.Data.MySqlClient" />
    <add name="salessolEntities" connectionString="server=localhost;User Id=root;password=surpavan;database=salessol;Persist Security Info=True;Old Guids=True" providerName="MySql.Data.MySqlClient" />
  </connectionStrings>

Another modification:
<connectionStrings>

        <add name="SalesSolWcfLib.My.MySettings.DBConnection" connectionString="server=localhost;User Id=root;password=surpavan;database=salessol;Persist Security Info=True;Old Guids=True" providerName="MySql.Data.MySqlClient" />
        <add name="SalesSolWcfLib.My.MySettings.salessolEntities" connectionString="server=localhost;User Id=root;password=surpavan;database=salessol;Persist Security Info=True;Old Guids=True" providerName="MySql.Data.MySqlClient" />
      </connectionStrings>

Entire App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="SalesSolWcfLib.My.MySettings.DBConnection" connectionString="server=localhost;User Id=root;password=surpavan;database=salessol;Persist Security Info=True;Old Guids=True" providerName="MySql.Data.MySqlClient" />
    <add name="SalesSolWcfLib.My.MySettings.salessolEntities" connectionString="server=localhost;User Id=root;password=surpavan;database=salessol;Persist Security Info=True;Old Guids=True" providerName="MySql.Data.MySqlClient" />
      </connectionStrings>
      <appSettings>
        <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
        <add key="ClientSettingsProvider.ServiceUri" value="" />
      </appSettings>
      <system.web>
        <compilation debug="true" />
        <membership defaultProvider="ClientAuthenticationMembershipProvider">
          <providers>
            <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
          </providers>
        </membership>
        <roleManager defaultProvider="ClientRoleProvider" enabled="true">
          <providers>
            <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
          </providers>
        </roleManager>
      </system.web>
      <!-- When deploying the service library project, the content of the config file must be added to the host's
      app.config file. System.Configuration does not support config files for libraries. -->
      <system.serviceModel>
        <services>
          <service name="SalesSolWcfLib.Service1">
            <endpoint address="" binding="basicHttpBinding" contract="SalesSolWcfLib.IService1">
              <identity>
                <dns value="localhost" />
              </identity>
            </endpoint>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
            <host>
              <baseAddresses>
                <add baseAddress="http://localhost:8733/Design_Time_Addresses/SalesSolWcfLib/Service1/" />
              </baseAddresses>
            </host>
          </service>
          <service name="SalesSolWcfLib.ContactService">
            <endpoint address="" binding="basicHttpBinding" contract="SalesSolWcfLib.IContactService">
              <identity>
                <dns value="localhost" />
              </identity>
            </endpoint>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
            <host>
              <baseAddresses>
                <add baseAddress="http://localhost:8733/Design_Time_Addresses/SalesSolWcfLib/ContactService/" />
              </baseAddresses>
            </host>
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior>
              <!-- To avoid disclosing metadata information,
              set the values below to false before deployment -->
              <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True" />
              <!-- To receive exception details in faults for debugging purposes,
              set the value below to true.  Set to false before deployment
              to avoid disclosing exception information -->
              <serviceDebug includeExceptionDetailInFaults="False" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
      </system.serviceModel>
      <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
          <parameters>
            <parameter value="v11.0" />
          </parameters>
        </defaultConnectionFactory>
      </entityFramework>
    </configuration>

Please advise on which part I went wrong, this is a WCF project with Mysql.  My manual connection with "SalesSolWcfLib.My.MySettings.DBConnection" works well, but with ado.net I am facing this issue.  Please correct me where I went wrong.


text:
Q: rdist.earth() with pairs of coordinates So I've converted my pairs of coords into 2 matrices which look like this:
    long1      lat1
1 -1.290672 0.7124777
2 -1.290643 0.7125160
3 -1.290692 0.7125405
4 -1.290724 0.7124929
5 -1.290748 0.7124579
6 -1.290766 0.7124353

    long2      lat2
1 -1.290643 0.7125160
2 -1.290692 0.7125405
3 -1.290724 0.7124929
4 -1.290748 0.7124579
5 -1.290766 0.7124353
6 -1.290771 0.7124249

Attempting to run a seemingly-simple command, but it's hanging my machine. Not sure why, because each matrix is only 507550 elements and 17.4 Mb.
foo <- rdist.earth(coords, coords2, miles=FALSE, R=6371)

Is there an easier way to do this???

A: dist <- rdist.earth.vec(coords, coords2, miles=FALSE, R=6371)

A: There are better ways to do it. But if your R skills are minimal: you can subset the first matrix matrix into submatrices (where each is, say, 1/10th of the size of the total, run each sub-matrix against the second matrix, and then combine the results at the end. I had the same issue, and this is what I came up with.
getwd()
setwd("C:/_R")
library(maptools)
require(rgdal)
# Read SHAPEFILE.shp from the current working directory (".")
points2010 <- readOGR(dsn = "C:/_R", layer = "points_2010")
metro <- readOGR(dsn = "C:/_R", layer = "selection")
plot(points2010)
plot(metro, axes=TRUE)
head(points2010)

library("rgeos")
ohio.metro <- spTransform(points2010, CRS("+proj=longlat +datum=WGS84"))
plot(ohio.metro, axes=TRUE)

ohio.metro$COUNTYFP10<-substr(ohio.metro$id,3,5)
countylist<-unique(ohio.metro$COUNTYFP10)
# "035" "055" "085" "093" "103"
ohio.county035 <- subset( ohio.metro, COUNTYFP10 == "035"  )
ohio.county055 <- subset( ohio.metro, COUNTYFP10 == "055"  )
ohio.county085 <- subset( ohio.metro, COUNTYFP10 == "085"  )
ohio.county093 <- subset( ohio.metro, COUNTYFP10 == "093"  )
ohio.county103 <- subset( ohio.metro, COUNTYFP10 == "103"  )

plot(ohio.metro$COUNTYFP10) #counties in the metro
plot(ohio.county035$COUNTYFP10) # counties inthe county

plot(ohio.metro) #counties in the metro
plot(ohio.county035) # counties inthe county

#get the coordinats for the Great circle command
ohio.metro.coords <- ohio.metro@coords
ohio.county035.coords <- ohio.county035@coords
ohio.county055.coords <- ohio.county055@coords
ohio.county085.coords <- ohio.county085@coords
ohio.county093.coords <- ohio.county093@coords
ohio.county103.coords <- ohio.county103@coords

library(fields)
great_circle<-rdist.earth(ohio.county035.coords,ohio.metro.coords,miles=TRUE, R=NULL) #works
great_circle<-rdist.earth(ohio.county055.coords,ohio.metro.coords,miles=TRUE, R=NULL) #works
great_circle<-rdist.earth(ohio.county085.coords,ohio.metro.coords,miles=TRUE, R=NULL) #works
great_circle<-rdist.earth(ohio.county093.coords,ohio.metro.coords,miles=TRUE, R=NULL) #works
great_circle<-rdist.earth(ohio.county103.coords,ohio.metro.coords,miles=TRUE, R=NULL) #works

library(matrixStats)
bm<-rowMedians(great_circle)
head(bm)


text:
Q: How to union records of two stored procedures without knowing columns I have 2 stored procedures which returns same but unknown columns. I need to write a proc to combine results from both stored procedures. I tried OPENROWSET but problem is to provide the connection string in OPENROWSET function, even if I specify the connection string one time, it will be different for different environments and I think that will be the worst thing to change connection string each time I deploy the application in different environments or if the user is changed on server. Can someone help me to get this done in the best way.
I cannot write them as function since the procs are using temp tables.
Declare @connection nvarchar(200)
Declare @sql nvarchar(max)
Set @connection= 'Server=servername;initial
catalog=dbname;user=abc,password=xyz';
Set @sql='SELECT * INTO #temp1
FROM OPENROWSET(
           ''SQLNCLI'',
           '''+ @connection + ''',
           ''EXEC sp_name '')'

Exec(@sql)

A: --- creating a temporary table
CREATE Table #Dynamic_Temp_Table (_field_only_for_create_ INT )

--- Addition of fields from the first recordset from the first procedure
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL=ISNULL(@SQL+',','ALTER TABLE #Dynamic_Temp_Table ADD ')+name+' '+system_type_name
    FROM sys.dm_exec_describe_first_result_set('exec sp_proc_first', NULL, NULL)
    order by column_ordinal
exec sp_executesql @SQL

--- Remove of the first unused column
ALTER TABLE #Dynamic_Temp_Table drop column _field_only_for_create_

--- Addition of the result from the first procedure
INSERT INTO #Dynamic_Temp_Table
exec sp_proc_first

--- Addition of the result from the second procedure
INSERT INTO #Dynamic_Temp_Table
exec sp_proc_second

--- result:  exec sp_proc_first UNION ALL exec sp_proc_second
select * from #Dynamic_Temp_Table
--- result: exec sp_proc_first UNION exec sp_proc_second
select DISTINCT * from #Dynamic_Temp_Table

A: It is possible but not easy at all....
You can change your stored procedures to just create and populate a global temp tables (no select), then you can select both with an union.
To use OPENROWSET as you are doing it in your current approach you will need global temp table too, But as you mention that your stored procedures are using Temp Tables, OPENROWSET, OPENQUERY or sys.dm_exec_describe_first_result_set will not be able to determine the metadata to create the temp table.
Another option is to change your stored procedures to use variable tables instead of temp tables, then the metadata could be redetermined. @chrszcpl's answer https://stackoverflow.com/a/55632401/10932521 is a very good solution if you are able to do that.
If this is not possible (I assume that this isn't, otherwise the columns would't be unknown) because you are using dynamic sql in your procedures, or you simply can't touch those procedures for any reason, I think that the cheapest solution is create a third stored procedure which returns the dynamic columns definition that the other procedures will return..


text:
Q: Does ag-grid support server-side filtering on .netcore I am trying to evaluate using grids for my angular 8 client that support server-side filtering on .Netcore. I am currently using DevExpress and want to move away from it since I feel there are better tools in the market.
I am seen too much of markup being generated with them. I was contemplating to use ag-grid but dont think they support server-side validation on .net core. Does anybody have idea about ag-grid. I tried searching the net
but couldnt find an appropriate example. Has anybody used any other grid , which is better that devexpress grid. The reason why i am looking for server-side filtering is it is indeed better and far more effecient than
doing it client side

A: Below row models of ag-grid supports server side filtering.

*

*Server side row model

*Infinite row model
TLDR;
After applying filter, getRows (which you are supposed to implement) method of dataSource gets called, along with the required parameters like startRow, filterModel, sortModel, etc. - which you can pass on and apply filter at server.

Now, your question: Does ag-grid support server-side filtering on .netcore
It doesn't matter which framework you are using at server. You can use .net, .net core, Java, Node, python, or any name add in the list.
The grid should receive JSON array. That's it.


text:
Q: Javascript throws undefined So i've been trying to learn to code and have been using codeAcademy as as resource. I'm currently doing a Rock, Paper, Scissors exercise and my code runs fine but my last console.log(determineWinner(userChoice, computerChoice));" throws an undefined into the console. Any help would be appreciated.

const getUserChoice = (userInput) => {
  userInput = userInput.toLowerCase();
  if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') {
    return userInput;
  } else {
    console.log('Error!');
  }
}

const getComputerChoice = () => {
  switch (Math.floor(Math.random() * 3)) {
    case 0:
      return 'rock';
    case 1:
      return 'paper';
    case 2:
      return 'scissors';
  }
}

const determineWinner = (userChoice, computerChoice) => {
  if (getUserChoice === getComputerChoice) {
    return 'the game was a tie';
  }
}
if (getUserChoice === 'rock') {
  if (getComputerChoice === 'paper') {
    return 'computer won!';
  } else {
    return 'you won!';
  }
}
if (getUserChoice === 'paper') {
  if (getComputerChoice === 'scissors') {
    return 'computer won!';
  } else {
    return 'you won!';
  }
}
if (getUserChoice === 'scissors') {
  if (getComputerChoice === 'rock') {
    return 'computer won!';
  } else {
    return 'you won!';
  }
}
const playGame = () => {
  const userChoice = getUserChoice('rock');
  const computerChoice = getComputerChoice();
  console.log(`You threw: ${userChoice}`);
  console.log(`The computer threw: ${computerChoice}`);
  console.log(determineWinner(userChoice, computerChoice));
};
playGame();

A: Ignoring a small syntax mistake in the code you posted here, the problem with the non-working code is that in the function determineWinner, you've two variables named userChoice and computerChoice. But, wrongly, you are using getUserChoice and getComputerChoice.

const getUserChoice = (userInput) => {
  userInput = userInput.toLowerCase();
  if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') {
    return userInput;
  } else {
    console.log('Error!');
  }
}

const getComputerChoice = () => {
  switch (Math.floor(Math.random() * 3)) {
    case 0:
      return 'rock';
    case 1:
      return 'paper';
    case 2:
      return 'scissors';
  }
}

const determineWinner = (userChoice, computerChoice) => {
  if (userChoice === computerChoice) {
    return 'the game was a tie';
  }

  if (userChoice === 'rock') {
    if (computerChoice === 'paper') {
      return 'computer won!';
    } else {
      return 'you won!';
    }
  }
  if (userChoice === 'paper') {
    if (computerChoice === 'scissors') {
      return 'computer won!';
    } else {
      return 'you won!';
    }
  }
  if (userChoice === 'scissors') {
    if (computerChoice === 'rock') {
      return 'computer won!';
    } else {
      return 'you won!';
    }
  }
}
const playGame = () => {
  const userChoice = getUserChoice('rock');
  const computerChoice = getComputerChoice();
  console.log(`You threw: ${userChoice}`);
  console.log(`The computer threw: ${computerChoice}`);
  console.log(determineWinner(userChoice, computerChoice));
};

playGame();


text:
Q: Pinch Zoom on picture in Ionic project I developed a project on Ionic.
In a view, I searched the possibility to pinch zoom a picture.
I tried hammer.js (http://hammerjs.github.io/). The pinch zoom works but the zoom is on center screen of the picture and not where the pinch was performed. Also, the picture can disappear from the screen...
So, how i can pinch zoom on a picture (not on a gallery), with Android/Ios compatibility.
It's a basic function and it's not very popular...
Any idea or tutorial ?

A: That's true, the video posted by Aravind shows the solution.
Ionic provides zooming via the ion-scroll directive. This implicitly adds the possibility to scroll the picture when zoomed.
<ion-scroll
    direction="xy"
    zooming="true"
    min-zoom="1.0"
    max-zoom="2.5"
    overflow-scroll="false"
    has-bouncing="false"
    >
</ion-scroll>

Be sure to add
overflow-scroll="false"

on your ion-scroll, as zooming won't work with overflow-scroll, which is by now the default setting for scrolling in Ionic.
The has-bouncing attribute is optional, although in my opinion the feeling is cleaner when the native iOS bounce is deactivated for zoomable images.


text:
Q: How to debug a simple website string grabber Does anyone have any suggestions on how to better debug this? I know that it is returning null at line = in.readLine() even when it shouldn't. One tier up I have added a catch for all throwables but unfortunately, no errors are being printed. Anyone have any suggestion on what I can try next?
public static String pullString(int id) throws IOException {

    String price;
    logError("Checkpoint 1");
    URL url = new URL("http://www.example.com");
    URLConnection con = url.openConnection();
    logError("Checkpoint 2");
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    logError("Checkpoint 3");
    String line;

    while ((line = in.readLine()) != null) {
    //^ for some reason this becomes null, but on identical pages it works fine.

          //Removed unneeded info

                return ---;
            } catch (NumberFormatException e) {
                logError("NumberFormatException");

                return null;
            }
        }
    }
    logError("left out the back");
    return null;
}


text:
Q: Mock GetExternalLoginInfoAsync() method I have private property to access AuthenticationManager:
private IAuthenticationManager AuthenticationManager => HttpContext.GetOwinContext().Authentication;

I want to mock the method GetExternalLoginInfoAsync() in order to receive fake ExternalLoginInfo object:
ExternalLoginInfo loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

Both GetOwinContext() and GetExternalLoginInfoAsync() methods are extension methods. Is it possible to see source code of these methods to see how they works?

A:
Both GetOwinContext() and GetExternalLoginInfoAsync() methods are extension methods. Is it possible to see source code of these methods to see how they works?

Sure, one way is to use ILSpy.  For example:
/// <summary>
///     Extracts login info out of an external identity
/// </summary>
/// <param name="manager"></param>
/// <returns></returns>
public static async Task<ExternalLoginInfo> GetExternalLoginInfoAsync(this IAuthenticationManager manager)
{
    if (manager == null)
    {
        throw new ArgumentNullException("manager");
    }
    return AuthenticationManagerExtensions.GetExternalLoginInfo(await TaskExtensions.WithCurrentCulture<AuthenticateResult>(manager.AuthenticateAsync("ExternalCookie")));
}

However, in my opinion this is just a Rabbit hole.  Instead, you should be using Dependency Injection to inject a IAuthenticationManager into your controller.  Then you can simply Mock it and the methods you need instead of testing internal microsoft code.


text:
Q: Extracting data from multiple variable sized arrays in bash onto one line I am writing a small bash script that will find the MX records of any given domain, then print out the hostname, IP address, and reverse address for the IP address. I was able to successfully store each hostname, ip, and reverse address into 3 arrays:
$MXHOSTS[@]
$MXIPS[@]
$MXRHOST[@]

Each contains the same number of values, and depend on how many MX records a domain has. What I want to then do, is print out a line with data from all three arrays, for the number of values in the arrays.
How would I be able to either a. create a new array that condenses 3 arrays into 1 with this data or b. print out the data from all three arrays using echo?
Examples:
$MXHOSTS[0] = aspmx.l.google.com.
$MXIPS[0] = 74.125.129.27
$MXRHOST[0] = ia-in-f27.1e100.net.

From that, I'd like to then print out this:
aspmx.l.google.com. :: 74.125.129.27 :: ia-in-f27.1e100.net.
for each MX record, so it would run like this:
[~/scripts]# ./whomails google.com
aspmx.l.google.com. :: 74.125.129.27 :: ia-in-f27.1e100.net.
alt1.aspmx.l.google.com. :: 74.125.129.27 :: qe-in-f27.1e100.net.

etc..
So far I've tried a few different methods, mostly using for loops, but if the domain has multiple MX records it will print out all possible combinations. With only one MX, it works fine.
Currently I am using the following, but this is what gives me all possible combinations:
for hosts in "${MXHOSTS[@]}"; do
    for ips in "${MXIPS[@]}"; do
        for rhosts in "${MXRHOSTS[@]}"; do
            echo "$hosts :: $ips :: $rhosts"
        done
    done
done

How do I get it to print just the corresponding array value, like [1-n] instead of [@]*[@]*[@]?

A: I'm not sure if I got what you want, but if all the arrays have the same size, you may simply index them with an integer:
for (( i = 0; i < ${#array1[@]}; ++i )); do
    ${array1[$i]}
    ${array2[$i]}
    ...
    ${arrayn[$i]}
done


text:
Q: Apply a web.config transform within a Teamcity Build Step I am trying to run a MSBuild task on team city that also transforms a web.casper.config file.
I have tried various switches but can;t get this right. Which most likely means there is a different way to achieve my desired result (like publish).
I have tried:-
/t:TransformWebConfig
/p:TransformWebConfig=true
Basically I want to
 - BUILD website.csproj into a custom dir
 - THEN apply a web.config transform on web.casper.config
Can anyone help?

A: One thing that seems to work (not sure if its the best way) is to add a before/after build event on the csproj file for the website e.g.
  <Target Name="BeforeBuild">
    <Copy SourceFiles="Web.config" DestinationFiles="Web.temp.config"
         OverwriteReadOnlyFiles="True" />
    <TransformXml Source="Web.temp.config" Transform="Web.$(Configuration).config"
         Destination="Web.config" />
  </Target>
  <Target Name="AfterBuild">
    <Copy SourceFiles="Web.temp.config" DestinationFiles="Web.config"
       OverwriteReadOnlyFiles="True" />
    <Delete Files="Web.temp.config" />
  </Target>

This basically copies web.config to web.temp.config then uses the casper config to transform.
Source from SO


text:
Q: Check if Word Document is Read Only from PowerShell I'm trying to detect if a "Microsoft Word Document" has been configured "Read-Only" by MSOffice.
Everything I have read relates to checking using Get-ItemProperty "C:\tmp\readonly.docx" | Select-Object IsReadOnly, but that is checking if the File is "read only" from the filesystem level.
The Problem is Microsoft doesn't mark it on the outside, you'd need to open/check with the Microsoft COM object I figure to query if document is read only.
PS C:\Users\Admin> Get-ItemProperty "C:\tmp\readonly.docx" | Select-Object IsReadOnly

IsReadOnly
----------
     False

Update: If file is configured RO without a Password then you can simple open as RW without a prompt (via powershell), but if it is with a Password then you get the prompt to acknowledge RO status which is what I want to avoid because it's hanging my script.

A: Continuing from my comment and note, not using anything dealing with the Word DOM via COM.
$File = 'd:\Temp\HSGCopy.docx'

# File not in use
Set-ItemProperty -Path $File  -Name IsReadOnly -Value $false
(Get-ItemProperty 'd:\Temp\HSGCopy.docx').IsReadOnly
$File |
ForEach{
    try
    {
        $TargetFile = (New-Object System.IO.FileInfo $PSitem).Open(
                                            [System.IO.FileMode]::Open,
                                            [System.IO.FileAccess]::ReadWrite,
                                            [System.IO.FileShare]::None
                      )
        $TargetFile.Close()
        Remove-Item -Path $PSItem -WhatIf
    }
    catch [System.Management.Automation.ItemNotFoundException]{$PSItem.Exception.Message}
    catch {$PSItem.Exception.Message}
}
# Results
<#
False
What if: Performing the operation "Remove File" on target "D:\Temp\HSGCopy.docx".
#>

# File in use
Set-ItemProperty -Path $File  -Name IsReadOnly -Value $false
(Get-ItemProperty 'd:\Temp\HSGCopy.docx').IsReadOnly
$File |
ForEach{
    try
    {
        $TargetFile = (New-Object System.IO.FileInfo $PSitem).Open(
                                            [System.IO.FileMode]::Open,
                                            [System.IO.FileAccess]::ReadWrite,
                                            [System.IO.FileShare]::None
                      )
        $TargetFile.Close()
        Remove-Item -Path $PSItem -WhatIf
    }
    catch [System.Management.Automation.ItemNotFoundException]{$PSItem.Exception.Message}
    catch {$PSItem.Exception.Message}
}
# Results
<#
False
Exception calling "Open" with "3" argument(s): "The process cannot access the file 'd:\Temp\HSGCopy.docx' because it is being used by another process."
#>

# Change the file attribute
# File not in use
Set-ItemProperty -Path $File  -Name IsReadOnly -Value $true
(Get-ItemProperty 'd:\Temp\HSGCopy.docx').IsReadOnly
$File |
ForEach{
    try
    {
        $TargetFile = (New-Object System.IO.FileInfo $PSitem).Open(
                                            [System.IO.FileMode]::Open,
                                            [System.IO.FileAccess]::ReadWrite,
                                            [System.IO.FileShare]::None
                      )
        $TargetFile.Close()
        Remove-Item -Path $PSItem -WhatIf
    }
    catch [System.Management.Automation.ItemNotFoundException]{$PSItem.Exception.Message}
    catch {$PSItem.Exception.Message}
}
# Results
<#
True
Exception calling "Open" with "3" argument(s): "Access to the path 'd:\Temp\HSGCopy.docx' is denied."
#>

# File in use
Set-ItemProperty -Path $File  -Name IsReadOnly -Value $true
(Get-ItemProperty 'd:\Temp\HSGCopy.docx').IsReadOnly
$File |
ForEach{
    try
    {
        $TargetFile = (New-Object System.IO.FileInfo $PSitem).Open(
                                            [System.IO.FileMode]::Open,
                                            [System.IO.FileAccess]::ReadWrite,
                                            [System.IO.FileShare]::None
                      )
        $TargetFile.Close()
        Remove-Item -Path $PSItem -WhatIf
    }
    catch [System.Management.Automation.ItemNotFoundException]{$PSItem.Exception.Message}
    catch {$PSItem.Exception.Message}
}
# Results
<#
True
Exception calling "Open" with "3" argument(s): "Access to the path 'd:\Temp\HSGCopy.docx' is denied."
#>

When using Word document protection
# with Word doc protection off
#>
$Word = New-Object –comobject Word.Application
Try
{
    ($Word.documents.open($File,$false,$false)).ReadOnly
    Write-Warning -Message "$File is protected ReadOnly"
}
Catch {Write-Verbose -Message "$File is not protected" -Verbose}

# then don't forget to close
$Word.Quit()
# Results
<#
VERBOSE: d:\Temp\HSGCopy.docx is not protected
#>

# With Word doc protection on
$Word = New-Object –comobject Word.Application
Try
{
    ($Word.documents.open($File,$false,$false)).ReadOnly
    Write-Warning -Message "$File is protected ReadOnly"
}
Catch {Write-Verbose -Message "$File is not protected ReadOnly" -Verbose}

# then don't forget to close
$Word.Quit()
# Results
<#
True
WARNING: d:\Temp\HSGCopy.docx is protected ReadOnly
#>

By accident or on purpose, you could have both set in an environment. I've had this happen to me in auto-classification scenarios. Meaning when FSRM/RMS/AIP has been deployed/implemented and enforced.
Update
Here a sample of what I have in my workflow to catch this sort of stuff, as per our exchange.
Clear-Host
$Files |
ForEach{
    $File = $PSItem
    "Processing $PSItem"
    try
    {
        Write-Verbose -Message 'Word properties:
        DocID, FullName, HasPassword,
        Permission, ReadOnly, Saved,
        Creator, CurrentRsid, CompatibilityMode' -Verbose

        'DocID', 'FullName', 'HasPassword',
        'Permission', 'ReadOnly', 'Saved',
        'Creator', 'CurrentRsid', 'CompatibilityMode' |
        ForEach {($Word.documents.open($File,$false,$false)).$PSitem}

        Write-Verbose -Message 'File system ReadOnly attribute:' -Verbose
        (Get-ItemProperty $File).IsReadOnly

        Write-Verbose -Message 'Document state' -Verbose
        $TargetFile = (New-Object System.IO.FileInfo $PSitem).Open(
                                            [System.IO.FileMode]::Open,
                                            [System.IO.FileAccess]::ReadWrite,
                                            [System.IO.FileShare]::None
                        )
        $TargetFile.Close()
        Remove-Item -Path $PSItem -WhatIf
    }
    catch [System.Management.Automation.ItemNotFoundException]{$PSItem.Exception.Message}
    catch {$PSItem.Exception.Message}
}
# Results
<#
Processing d:\Temp\HSGCopy.docx
VERBOSE: Word properties:
        DocID, FullName, HasPassword,
        Permission, ReadOnly, Saved,
        Creator, CurrentRsid, CompatibilityMode
938207550
D:\Temp\HSGCopy.docx
False
True
True
1297307460
12414886
15
VERBOSE: File system ReadOnly attribute:
False
VERBOSE: Document state
What if: Performing the operation "Remove File" on target "D:\Temp\HSGCopy.docx".
#>

A: Ok, so to test this, I had 3 files as follows:

*

*A) One regular test.docx with no restrictions

*B) One readonly.docx w/ a password. This is the file that hung me up w/ a prompt

*C) One nopass.docx w/ a read-only setting, but no PWD configured.

A and C would open regardless of the ReadOnly setting, but B would hang on a prompt even with DisplayAlerts set to 0. You also couldn't check the ReadOnly property unless the prompt was surpassed, or if you set it to TRUE it was always true obviosuly.
There is no way I found to check the ReadOnly or HasPassword property without first openeing document. You can likely inspect the XML file for HEX but I'd say that is less reliable. My way just took some testing/trickery to get working. The important part was I had to pass a password and catch if it failed. Doc's A/C would open fine even when you pass a password argument, so no harm there. In the catch I set ReadOnly = TRUE and Visible = TRUE. You may not need to set the visible part true, but if ReadOnly = TRUE then you can't make certain adjustments via VB (like ORIENTATION) and I'll be using SENDKEYS so I'll need the UI if ReadOnly = TRUE. As well, hiding the UI is just a "bonus" but not needed. I may just set it always visible if I continue wasting time on coding IF/THEN for the OPENUI statments.
Anyway... Here is a final code snippet to test on the three files which should result in each file opening w/o a prompt.
 #Constants
 Clear-Variable ReadOnly
 $missing = [System.Type]::Missing
 $str = ''
 $PASSWD = 'IsPWDProtected?'
 $wdAlertsNone = 0
 $FILENAME = "C:\tmp\readonly.docx"
 $OPENUI = "TRUE"

 #Start Word
 $ObjWord = New-Object -comobject Word.Application
 IF ($OPENUI -eq "FALSE"){$ObjWord.Visible  = $FALSE}ELSE{$ObjWord.Visible  = $TRUE}
 $ObjWord.Application.DisplayAlerts = $wdAlertsNone

 #.Open
 IF (!$ConfirmConversions){$ConfirmConversions = $missing}
 IF (!$ReadOnly){$ReadOnly = $FALSE}
 IF (!$AddToRecentFiles){$AddToRecentFiles = $missing}
 IF (!$PasswordDocument){$PasswordDocument = $PASSWD}
 IF (!$PasswordTemplate){$PasswordTemplate = $PASSWD}
 IF (!$Revert){$Revert = $False}
 IF (!$WritePasswordDocument){$WritePasswordDocument =  $PASSWD}
 IF (!$WritePasswordTemplate){$WritePasswordTemplate =  $PASSWD}
 IF (!$Format){$Format = 'wdOpenFormatAuto'}
 IF (!$Encoding){$Encoding = $missing}
 IF (!$Visible){$Visible = $False}
 try{$ObjDoc=$ObjWord.documents.open($FILENAME,$ConfirmConversions,$ReadOnly,$AddToRecentFiles,$PasswordDocument,$PasswordTemplate,$Revert,$WritePasswordDocument,$WritePasswordTemplate,$Format,$Encoding,$Visible)}
  catch {
     Write-Error  $_
     Write-Host "Opening Read_Only"
     $ReadOnly = $TRUE
     $Visible = $TRUE
     $ObjDoc=$ObjWord.documents.open($FILENAME,$ConfirmConversions,$ReadOnly,$AddToRecentFiles,$PasswordDocument,$PasswordTemplate,$Revert,$WritePasswordDocument,$WritePasswordTemplate,$Format,$Encoding,$Visible)
 }

#AllDone?
PAUSE
$ObjWord.ActiveDocument.Close(0)
$ObjWord.Quit()
[gc]::collect()
[gc]::WaitForPendingFinalizers()
[gc]::collect()
[gc]::WaitForPendingFinalizers()
sleep 2

Result:
PS C:\Users\Admin> C:\tmp\test.ps1
C:\tmp\test.ps1 : The password is incorrect. Word cannot open the document. (C:\tmp\readonly.doc)
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,test.ps1

Opening Read_Only
Press Enter to continue...:

Note: I hardcoded OPENUI = TRUE during testing because if it got hung on a prompt with the UI closed, I had to use tskill winword.exe and start over.


text: Q: How do I close Chrome when entering standby or hibernate? If I leave Chrome open, it keeps me logged into my sites even during standby, so the only defence I have is my Linux password. I would like to have Chrome shut down on standby or hibernate, and then automatically re-open on resume so that I have to enter my LastPass password when I next use my PC. Does anyone know how to do this?


text:
Q: Inline Babel script: Unexpected token I have this JS fiddle with some React. Most of the code in the fiddle is not relevant, except for this part:
class TodoApp extends Component {
    render() {
    return {

        <button onClick={() => {
            store.dispatch({
            type: 'ADD_TODO',
            text: 'Test',
            id: nextTodoId++
          })
        }}>
            Add Todo
        </button>

            {this.props.todos.map(todo =>

                {todo.text}

          )}

    }
  }
}

When this is interpreted, I get this error in the browser:
Uncaught SyntaxError: Inline Babel script: Unexpected token (130:5)
  128 |     render() {
  129 |     return {
> 130 |

      |         ^

I don't understand why the JSX is not recognised.
I have added this to the HTML part:

Since I am getting the React and React DOM scripts(I added some spaces to the URLs, otherwise I would not have been able to post the question), the JSX code should be properly interpreted, right?

A: You shouldn't be using { and } around your JSX, you should be using ( and ):
return (

        ...

       );

Fixed Fiddle (it has other issues that are revealed when you click Add Todo, but the syntax error is fixed)
That's if you want to use anything around it at all; it isn't necessary, but is common. This is also valid:
return

    ...

;

The reason you see (...) so much is that this is NOT correct but sadly results in a silent failure:
// NOT CORRECT
return

    ...

;

It's because of (the horror that is) Automatic Semicolon Insertion, which will insert a ; after the return, making it:
// NOT CORRECT
return;

    ...

;

E.g., return; followed by a React.createElement call that never gets executed.


text:
Q: Google Drive API - Example code is not working I want to use Google API to transfer SharePoint Documents to Google Drive using dot net. For that to happen I want to use this link Google Quick Start.
I have followed every little piece of information. It states in beginning "Complete the steps described in the rest of this page, and in about five minutes you'll have a simple Drive app that uploads a file to Google Drive" but it is not true.
I am trying to run this sample example since yesterday but failed.
// Register the authenticator and create the service
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET);
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);

So it seems that this code example is outdated and Google APIs have been upgraded.
Here comes the warning

[Obsolete("GoogleAuthenticationServer is not supported any more and it's going to be removed in 1.7.0-beta. Consider using the new Google.Apis.Auth NuGet package which supports .NET 4, .NET for Windows Store apps, Windows Phone 7.5 and 8 and Portable Class Libraries as well")]

Another code
var service = new DriveService(new BaseClientService.Initializer()
{
Authenticator = auth
});

And the error

Cannot implicitly convert type 'Google.Apis.Authentication.OAuth2.DotNetOpenAuth.NativeApplicationClient' to 'Google.Apis.Http.IConfigurableHttpClientInitializer'. An explicit conversion exists (are you missing a cast?)

Then I was looking for [latest release samples] there I found the source files.
I was not able able to run the sample also.
Here I was successfully authenticated but then had error for redirect Uri
My Client_Secrets.JSON looks like, as you can see I have set default redirect Uri to http://localhost/.
{"web":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret":"secret","token_uri":"https://accounts.google.com/o/oauth2/token","client_email":email","redirect_uris":["http://localhost/"],"client_x509_cert_url":"aa@developer.gserviceaccount.com","client_id":"id","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","javascript_origins":["http://localhost:53404/"]}}

Now I can run this application but as mentioned getting error

Error: redirect_uri_mismatch
  The redirect URI in the request: [[http://localhost:2430/authorize/]] did not match a registered redirect URI

I really don't know from where this port number comes and from where this authorize comes. As you can see in my JSON, I have not set anything similar.
I am using VS 2010 SP1 Ultimate and Windows 7 home Basic.
I have tried to give complete information and my end goal is upload document in Google drive.

A: The tutorial you are following uses an older version of google.apis thats why you are seeing the not supported.  Here are a couple of tutorials on how it works with the new version of the api.

*

*http://daimto.com/google-oauth2-csharp/

*http://daimto.com/google-drive-api-c/

A: Take a look in https://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.ASP.NET.SimpleOAuth2/Default.aspx.cs?repo=samples. It's a Task API ASP.NET sample. As you can see you need to add several lines of code, but it works.

A: I downloaded the samples Eyal mentions and got that compiling before integrating with my own app.  .Net needs to be 4 although it states it supports higher.

A: You have to set the redirect URI in the google developer console, not in your JSON. In your case, you would want to set it to http://localhost:2430/authorize/.


text:
Q: Is it a good practice to make concrete classes final? Open-Closed principle is one of the five SOLID principles of object-oriented design. It states that  "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification".
But recently most programming languages are providing a way to finalize classes such that it won't be inherited in future by providing keywords such as final. Some languages like Kotlin have their classes by default final (aka opt-in open).
I have also read some articles which states that interface inheritance must be preferred over implementation inheritance with valid reasoning like fragile base class problem. But OCP tells that classes should be open for extension. So should I consider declaring my classes open? or final? Which is a good practice in general?

A: I think no!
The main reason behind this is stated below.
The open-closed principle attacks this in a very straightforward way. It says that you should design modules that never change. When requirements change, you extend the behavior of such modules by adding new code, not by changing old code that already works."
So we can say it's the structural format for any code!

A: Inheritance is just one of the techniques used to fulfil OCP. Strategy pattern, decorator pattern, ordinary composition, parametric polymorphism and other techniques can be used to achieve those goals too. Inheritance will always be an option but should be avoided if possible, as appropriate.


text:
Q: Load a DLL From a Resource Directly From Memory in Delphi 7 I put a dll file into a resources file (*.res)
ProjectTestLibrary.dll
library ProjectTestLibrary;

uses SysUtils, Classes, Dialogs;

{$R *.res}

procedure DllMessage; export;
begin
  ShowMessage('Hello world from a Delphi DLL');
end;

exports DllMessage;

begin
end.

MyTestDLL.rc
TestDLL RCDATA ProjectTestLibrary.dll

Produce MyTestDLL.res by this command line
BRCC32 ProjectTestLibrary.rc

In main form
implementation
{$R *.dfm}
{$R MyTestDLL.RES}

procedure DllMessage;  stdcall; external 'ProjectTestLibrary.dll';

procedure TForm1.Button1Click(Sender: TObject);
begin
    DllMessage;
end;

Then error comes out
This application has failed to start because ProjectTestLibrary.dll was not found.
I understand that the problem because the dll file doesn't exist yet.
So I delete the 'DLLMessage;' code in onButton1Click.
Then onFormCreate, I added :
procedure TForm1.FormCreate(Sender: TObject);
var ms : TMemoryStream;
    rs : TResourceStream;
begin
  if 0 <> FindResource(hInstance, 'TestDLL', RT_RCDATA) then
  begin
    rs := TResourceStream.Create(hInstance, 'TestDLL', RT_RCDATA);
    ms := TMemoryStream.Create;
    ShowMessage('Found');
  end else
  begin
    ShowMessage('Not Found');
  end;
end;

I run it again then pop-up message said 'Found'
My question then :
1. How to save it in memory (not in PC hard drive), and finally
2. use its procedures/functions (procedure DLLMessage)

A: There is no official way to do it, although there exist techniques which emulate the Windows PE loader, and let you load DLL directly from a memory buffer, without having to store it on disk.
Here is a Delphi implementation, for example, of a DLL memory loader: https://github.com/DSPlayer/memorymodule


text:
Q: Magnitude of spin Why can't the magnitude of spin change for an elementary particle? All the places i have looked at so far just state that spin magnitude cannot be changed. Why is this the case?

A: Spin is an intrinsic property of a particle. We can rotate the spin so that we change the probability of measuring it as spin-up or spin-down along a given axis, but the spin itself is a naturally-occurring intrinsic property of the particle, much like mass or charge.

A: Because it is an intrinsic property of the particle. Just like mass, charge etc.
All elementary Standard Model fermions have 1/2 spin. It is not like a rotation so that you can rotate the particle faster. It is a property that particles just have.

A: I can think of two answers depending on what you mean by magnitude.
First, as others have already answered, spin, mass, charge, lepton number are the mathematical labels that uniquely name electrons.  If the spin was a different number, the particle would no longer be an electron.  In particular, spin $\frac{1}{2}$ tells you that an electron transforms under space rotations like a 2-vector that you use a 2 x 2 matrix to rotate.  In fact, spin S is just short hand for telling you the particle transforms like a (2S+1) component vector that you need a (2S+1) x (2S+1) matrix to rotate.
Second, you may already understand that particles transform like (2S+1) dimension vectors, but you are asking if the magnitude of the vector is always $\hbar S$ of angular momentum?  Experimentally, I think this has been verified for photons by absorbing N circularly polarized photons on a disk and seeing that $I\omega=N\hbar$ where $I$ and $\omega$ are the observed macroscopic moment of inertia and angular velocity of the disk.  The magnitude of $\hbar$ per unit of spin has also been verified experimentally for electrons using the Einstein-de Hass effect.  The magnitude of angular momentum per unit of spin has not been measured for any other particle, but it is hard to conceive how it could be different for other particles.


text:
Q: Testing if a user just logged in with Devise I want to include a user's authentication_token in my JSON response if they just logged in so that a consumer of my API can keep track of it and authenticate future requests. But I do not want to include the token otherwise. I am using Active Model Serializers to customize my JSON output:
class UserSerializer < ActiveModel::Serializer
  attributes :id, :email, :authentication_token

  def include_authentication_token?
    # what to put here?
  end
end

The Devise session controller uses respond_with resource where resource is the logged-in user, so by default it will use the UserSerializer. I could customize the Devise controller, but I would rather use include_authentication_token?. Is there some method in Devise that will return true when a User just logged in (i.e., the response is coming from Devise::SessionsController)?

A: While the current Request is not automatically available within your subclass of ActiveModel::Serializer, you can easily pass it into the serializer's options hash by including it in your call to UserSerializer.new.
If you explicitly create your serializer like:
UserSerializer.new(@user, scope: current_user)

That means you can simply pass a second option called request:
UserSerializer.new(@user, scope: current_user, request: request)

From then on, you can access the current Request in your serializer by calling options[:request]. For example, to inspect the current controller inside UserSerializer, simply check the value of
options[:request].params[:controller]

If it comes up as "devise/sessions", you're OK to include the token. Otherwise, if you're using the standard Devise controllers to handle sign-ins, you'll probably have to subclass Devise::SessionsController and reroute sign-ins to your new controller:
# app/controllers/sessions_controller.rb
class SessionsController < Devise::SessionsController
  def create
    self.resource = warden.authenticate!(auth_options)
    set_flash_message(:notice, :signed_in) if is_navigational_format?
    sign_in(resource_name, resource)
    respond_with resource, location: after_sign_in_path_for(resource), request: request
  end
end

# config/routes.rb
devise_scope :user do
  post "sign_in" => "sessions#create", as: :user_session
end

Please note I haven't tested this yet. In reading the source for ActionController::MimeResponds#respond_with, it appears that any options given to #respond_with will be passed downward to the responder, which is hijacked by ActionController::Serialization and it looks like the options are passed all the way into the resource's Serializer.
Good luck!

A: Maybe this will help you.
- (Boolean) signed_in?(scope = nil)
And on stackoverflow  Devise how to add signed in check in custom session controller


text:
Q: HashMap JSON object sent to browser through AJAX prints as [object Object] I am getting this strange issue here. I am sending a HashMap as a JSON to client side through AJAX to populate a dropdown. Everything looks good on server side but on the client side browser, the dropdown is being populated as [object Object]. What am I missing? My code is as follows.
 HashMap<Integer, Cars> cars = new HashMap();
 cars.put(1,car1);
 cars.put(2,car2);
 json = new Gson().toJson(cars);
 System.out.println(json); // PRINTS WELL
 try {
            ServletOutputStream os = res.getOutputStream();
            os.write(json.toString().getBytes());
            flushCloseOutputStream(os);
            res.setStatus(HttpServletResponse.SC_OK);
        } catch (Exception e) {
            System.out.println("from catch");
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Cannot create response");
        }
        setDestination(req, RESPONSE_NO_REDIRECT);

On the client side
function populatedd(dropdown){
.....
.....
if (this.readyState == 4 && this.status == 200) {
   var jsonResponse = JSON.parse(this.responseText);
   dropdown.options.length = 0;
   for (var key in jsonResponse) {
                createOption(dropdown, jsonResponse[key], key);
            }

.....
.....}

  function createOption(dropdown, text, value) {
    var x = document.createElement('option');
    x.value = value;
    x.text = text;
    dropdown.options.add(x);
}

P.S. no jQuery


text:
Q: How do I use the TarFile dereference flag in Python 2.4? I wrote a script that collects all our log files to one tar file. The problem is that it doesn't contain soft link's data. I tried to use the dereference flag but it is not recognized for python 2.4.3.
I can't use the command line since there's a length limit and I want to support many log files.
user ~/Desktop]$python
Python 2.4.3 (#1, Jun 11 2009, 14:09:37)

[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2

>>> import tarfile
>>> tarfile.TarFile('test.tar.gz', mode='w', dereference=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: __init__() got an unexpected keyword argument 'dereference'
>>>

A: According to the Python 2.4 docs dereference = True is supported. It appears to have been supported since tarfile was added in Python 2.3.
Unless you're on a non-Posix system (Windows) you must be doing it wrong. Post your code and the error you get with dereference = True so we can tell you what that is.
Also, by soft links I assume you mean symbolic links? Because that's what dereference = True allows to work.
Edit: I just looked at the code for tarfile on Python 2.4. It does not support the dereference parameter to the constructor, but it does seem to have the needed code to actually dereference (Checked against the source for Python 2.6). So,
import tarfile
tf = tarfile.TarFile('test.tar.gz', mode='w')
tf.dereference = True

should work. Please, update with your results.

A: Couldn't you just use the -T or --files-from option on tar?