text:
Q: Flutter Web Display Microsoft Documents Firebase I am trying to embed MS Documents in a Flutter Web App.
Documents are stored on Firebase Storage. I am using MS Web Viewer to display them in browser.
This works without any problem:
https://view.officeapps.live.com/op/embed.aspx?src=https://file-examples.com/wp-content/uploads/2017/08/file_example_PPT_250kB.ppt
The following two versions where the documents are hosted on Firebase are not working:
https://view.officeapps.live.com/op/embed.aspx?src=https://firebasestorage.googleapis.com/v0/b/tutor-and-learn.appspot.com/o/public%2Ffile_example_PPT_250kB.ppt?alt=media&token=6e293eb9-9f3b-41ab-9969-f936b3c54384
https://view.officeapps.live.com/op/embed.aspx?src=https://storage.googleapis.com/tutor-and-learn.appspot.com/public/file_example_PPT_250kB.ppt?GoogleAccessId=firebase-adminsdk-t47jn%40tutor-and-learn.iam.gserviceaccount.com&Expires=1597309385&Signature=VHbm8U8xlf%2BYybwalAveZtl8FsmEmr6Uml%2BwX%2FR7TOFNqlj%2B8QW1FFSJUNB4qcAzVpEcntLzipT15Zj73B%2FLlSZlQwEU10s5RkJdR5CZeZ6MuF2DUptUbqfnNobdLkizEmwlQ6Bkk4DkDWCd9nRL%2BQ0GLYypBr%2Bxs39bpd8JSuxxACWCjq0Of8qLTBMZQmD%2BgbE8JkMdqvBVOV75A7EQyy1IWqHrRBD7RgVc46IEq4TaO2ZT9h56joJgawqZOt81%2Fkq95YmNWZNOeU9kVRuLpSFsqZru8Ku7aapiFcUXjrjuMWZeC1XCrTK7fwU6A8shNIyHq3bE8RB9a%2BCQnS0llA%3D%3D
Either via Firebase directly nor Google Cloud Storage I get it to work.
The individual links in the above example work without any problems and you can download the file.
https://firebasestorage.googleapis.com/v0/b/tutor-and-learn.appspot.com/o/public%2Ffile_example_PPT_250kB.ppt?alt=media&token=6e293eb9-9f3b-41ab-9969-f936b3c54384
https://storage.googleapis.com/tutor-and-learn.appspot.com/public/file_example_PPT_250kB.ppt?GoogleAccessId=firebase-adminsdk-t47jn%40tutor-and-learn.iam.gserviceaccount.com&Expires=1597309385&Signature=VHbm8U8xlf%2BYybwalAveZtl8FsmEmr6Uml%2BwX%2FR7TOFNqlj%2B8QW1FFSJUNB4qcAzVpEcntLzipT15Zj73B%2FLlSZlQwEU10s5RkJdR5CZeZ6MuF2DUptUbqfnNobdLkizEmwlQ6Bkk4DkDWCd9nRL%2BQ0GLYypBr%2Bxs39bpd8JSuxxACWCjq0Of8qLTBMZQmD%2BgbE8JkMdqvBVOV75A7EQyy1IWqHrRBD7RgVc46IEq4TaO2ZT9h56joJgawqZOt81%2Fkq95YmNWZNOeU9kVRuLpSFsqZru8Ku7aapiFcUXjrjuMWZeC1XCrTK7fwU6A8shNIyHq3bE8RB9a%2BCQnS0llA%3D%3D
I presume the MS Web Viewer can not cope with the URLs. Is there any way I can adapt or change anything in Firebase to get it to work?
Looking in Firebase Storage Console the files are listed with the correct type as application/vnd.ms-powerpoint.

A: Encode the signed URL before adding it to https://view.officeapps.live.com/op/embed.aspx?src=. You can use online tools to encode URLs like https://www.urlencoder.org/


text:
Q: Docker node container cannot start but works locally without docker Update 3/23: I used author's package.json, npm install on my Mac, upgrade react-scripts to 3.4.0 and Dockerfile to fix a few issues and now this version works: https://github.com/harrywang/my-flask-react-auth/tree/6e65a7deaf89244a41a7c91843f07f4756956f95 however, this does not explain why the previous version did not work.
Update 3/23: if I only replace package.json and package-lock.json at https://github.com/harrywang/my-flask-react-auth/tree/master/services/client with the authors' versions at https://gitlab.com/testdriven/flask-react-auth/-/tree/master/services%2Fclient, it will work. Don't know why.
Following the tutorial at https://testdriven.io/courses/auth-flask-react/
Docker 2.2.0.4 Desktop on Mac
My code repo is at https://github.com/harrywang/my-flask-react-auth, where you can see the Dockerfile and docker-compose.yml, you can clone and run docker-compose up -d --build to reproduce my problem.
When I run docker-compose up -d --build, the flask and database containers work well but the node container exits with error code 0 when "Starting the development server..."
One thing I noticed is that I don't see [wds] webpack related info locally on my Mac. I don't know what they are.

but when I go to /services/client and run npm start, the node server starts and works well locally.
There is no error message during the docker building process. I have spent a few hours on this and cannot figure it out. Please help!! Thanks a lot!!
However, the author's repo at https://gitlab.com/testdriven/flask-react-auth with older versions does not have this issue:

A: I had the same problem. I am currently working through the same course. I have done every exactly like written in the guide. I was able two start 2 containers, the third one (flask-react-auth_client_1) stoped with 0.
I first tried to get into the container and execute docker run -it --entrypoint sh <image> and then npm start
No problem was detected. So I did a little research.
Apparently with react-scripts@3.4.0 or react-scripts@3.4.1+ it is impossible to run in the background now without the CI flag enabled.
My fix was, to add CI=true to the docker-compose.yml under client > environment.
I go the idea from https://github.com/facebook/create-react-app/issues/8688

A: It seems that the following part is missing from the client app Dockerfile:
COPY src /usr/src/app/src
COPY public /usr/src/app/public

This will copy the source folders into the Docker image. These two lines can be set above the following line in your Dockerfile.
The way you can troubleshoot such issues is by doing a docker run -it --entrypoint sh <image> to spin up a new container and get a shell to it. Then you can run the command that the server intended to run (npm start in our case). From there, you can spot errors that may not have been propagated to docker-compose. In our case, the error was the following:
react-scripts start Could not find a required file.
Name: index.html Searched in: /usr/src/app/public

A: In my case, just simply add CI=true into npm start scrpts, in package.json:
"start": "CI=true react-scripts start",

Thank to p1umyi 's answer above

A: You must include command line on docker-compose.yml :
version: '3'
services:
  redis-server:
    image: 'redis'
  node-app:
    command: npm start #this line
    build: .
    ports:
      - "4001:8081"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Insert php sql row record into hidden form input value field I'm trying to insert sql ID record inside php echo form input value. Values that are inserted manualy via input field (by typing) are being displayed fine. Value inside input (named: potnik) is not being displayed. Is it ignored because is inside echo or is inserted wrong?
$sql3 = "
SELECT id, potnik_id, ura, naslov
FROM prevoznik
ORDER BY HOUR(ura), MINUTE(ura) ASC;
";
$result = $conn->query($sql3);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {

        //Spremenjena oblika datuma
        $date = date_create($row["ura"]);
        $ura_pobiranja = date_format($date,"H:i");
        echo "

" . $row["id"] . "

" . $row["naslov"] . "

$ura_pobiranja

            ";

        if ($row["naslov"] !== null) {
            echo "
Nastavi uro<form action='update.php?id=" . $row["id"] . "\"' method='POST'><input name=\"potnik\"  value='".$row["id"]."' type='hidden' /> <input class=\"form-control fancy-border\" type=\"text\" name=\"posodobljeni_cas\"/><input type='submit' value='Posodobi'>  </form>
";
            echo "
";
        }
        else {
            echo "
";
        }

    }
} else {
    echo "
Nimaš še nobenih opravil

";
}

Code that isn't working (hidden input field value):

echo " <form action='update.php?id=" . $row["id"] . "\"' method='POST'><input name=\"potnik\"  value='".$row["id"]."' type='hidden' /> <input class=\"form-control fancy-border\" type=\"text\" name=\"posodobljeni_cas\"/><input type='submit' value='Posodobi'>  </form>
";

A: I had post parameters instead of get parameters set for update.php form action
update.php?id=
echo"Error on update ID:{$_GET['id']} POSODOBLJENI CAS:{$_POST['posodobljeni_cas']}";


text:
Q: Highest Quality Possible in SimpleScreenRecorder I have installed SimpleScreenRecorder On My Linux Machine but I recorded and Edited Some Videos With it Like This Example But the Recorded Quality is Not Good Enough, Please Tell me Some Settings Which I Can use For Recording Quality
My PC Details:
2 GB Ram, 2.2GHz Intel Dual Core Processor & 500GB HDD & Linux Mint XFCE4

A: This is hardly a question for unix stackexchange, but here's what I'm using to get good results off this application:

The key is specifying a low enough constant rate factor. 6 is close to lossless and you can specify 0 for lossless encoding but the resulting file might be huge.

A: It depends mostly on the system because when you have a slow machine you get better results when you get up with the speed and leave the constant rate factor on 23 because 23 is actually a near lossless default. In my case to stream a  full hd movie I get the best results with speed on medium and rate factor on 23 by a setting of 30 frames per second what is enough for hd movies, and I get a file size of about 2 GB. When i stream and record older series for example i scale on 720p 30 frames per second mp4 h264 codec with speed on slow and 28 rate factor what is near lossless to older series and movies the result is median-good quality by a filesize of about 300 MB 60 minutes


text:
Q: Oracle DB read next unlocked row I have following query running at three different instance of my application all trying to read row from a table one by one as a queue.
SELECT * FROM order_request_status ors WHERE ors.status = 'new' and ROWNUM <= 1 order by ors.id asc for update skip locked

now the issue is if the row is locked by one application instance i want my second application instance to read the next unlocked row by the query. but it is not working by this - for update skip locked.
Please suggest how i can implement a queue like feature using oracle db.

A: The SKIP LOCKED processing happens after rows are returned by the query. Your predicate stops after reading just one record due to ROWNUM<=1, so if the record it finds has already been locked by another session, your query skips it and stops finding more records.
If you only want to process one record at a time, just fetch one record from the cursor instead of using ROWNUM to limit it.


text:
Q: ImportError when using Python C API I have a binary which can load .so shared objects to extend functionality. These extensions are coded in C++ but I want to use some pre-coded python functions so I make use of Python C API. So far so good.
Calls to Python functions work nicely, but if, in Python, I import spidev module I get the following error:
import spidev
ImportError: /usr/local/lib/python2.7/dist-packages/spidev.so: undefined symbol: _Py_ZeroStruct
Segmentation fault

If I import standard python modules (sys, os, argparse...) there's no problem.
What could be the problem?
N.B.: I know that I could use spidev directly from C++ but I wanted to reuse existing python code as much as possible.
UPDATE:
As @BrianCain and @qarma pointed out, it can be a problem related with dependencies to libpython so I include ldd outputs:
$ ldd myextension.so
    /usr/lib/arm-linux-gnueabihf/libcofi_rpi.so (0xb6f89000)
    libpthread.so.0 => /lib/arm-linux-gnueabihf/libpthread.so.0 (0xb6f5f000)
    libdl.so.2 => /lib/arm-linux-gnueabihf/libdl.so.2 (0xb6f54000)
    libutil.so.1 => /lib/arm-linux-gnueabihf/libutil.so.1 (0xb6f49000)
    libm.so.6 => /lib/arm-linux-gnueabihf/libm.so.6 (0xb6ed8000)
    libpython2.7.so.1.0 => /usr/lib/libpython2.7.so.1.0 (0xb6c47000)
    libgcc_s.so.1 => /lib/arm-linux-gnueabihf/libgcc_s.so.1 (0xb6c1f000)
    libc.so.6 => /lib/arm-linux-gnueabihf/libc.so.6 (0xb6af0000)
    /lib/ld-linux-armhf.so.3 (0xb6fa2000)
    libz.so.1 => /lib/arm-linux-gnueabihf/libz.so.1 (0xb6ad2000)

$ ldd /usr/local/lib/python2.7/dist-packages/spidev.so
    /usr/lib/arm-linux-gnueabihf/libcofi_rpi.so (0xb6ed3000)
    libpthread.so.0 => /lib/arm-linux-gnueabihf/libpthread.so.0 (0xb6ea9000)
    libc.so.6 => /lib/arm-linux-gnueabihf/libc.so.6 (0xb6d7a000)
    /lib/ld-linux-armhf.so.3 (0xb6eed000)

UPDATE2:
Output of spidev installation.
$ sudo pip install spidev
Downloading/unpacking spidev
  Downloading spidev-2.0.tar.gz
  Running setup.py egg_info for package spidev

Installing collected packages: spidev
  Running setup.py install for spidev
    building 'spidev' extension
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/src/linux/include -I/usr/include/python2.7 -c spidev_module.c -o build/temp.linux-armv6l-2.7/spidev_module.o
    gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-z,relro build/temp.linux-armv6l-2.7/spidev_module.o -o build/lib.linux-armv6l-2.7/spidev.so

Successfully installed spidev
Cleaning up...

$ ldd /usr/local/lib/python2.7/dist-packages/spidev.so
    /usr/lib/arm-linux-gnueabihf/libcofi_rpi.so (0xb6f97000)
    libpthread.so.0 => /lib/arm-linux-gnueabihf/libpthread.so.0 (0xb6f6d000)
    libc.so.6 => /lib/arm-linux-gnueabihf/libc.so.6 (0xb6e3e000)
    /lib/ld-linux-armhf.so.3 (0xb6fb1000)

Still not depending on libpython...

A: I suspect your spidev.so is built against wrong version of Python or built badly.
Please run ldd on both your Python and this lib. If there's a mismatch, tough luck! If not, dig deeper.
Here's how it should work:
(test)[dima@bmg py-spidev]$ python setup.py build
(test)[dima@bmg py-spidev]$ ldd build/lib.linux-x86_64-2.7/spidev.so
        linux-vdso.so.1 (0x00007fffbadfe000)
        libpython2.7.so.1.0 => /usr/lib/libpython2.7.so.1.0 (0x00007f42c9659000)
        libpthread.so.0 => /usr/lib/libpthread.so.0 (0x00007f42c943c000)
        libc.so.6 => /usr/lib/libc.so.6 (0x00007f42c9094000)
        libdl.so.2 => /usr/lib/libdl.so.2 (0x00007f42c8e8f000)
        libutil.so.1 => /usr/lib/libutil.so.1 (0x00007f42c8c8c000)
        libm.so.6 => /usr/lib/libm.so.6 (0x00007f42c898b000)
        /usr/lib64/ld-linux-x86-64.so.2 (0x00007f42c9c50000)
(test)[dima@bmg py-spidev]$ python setup.py install
(test)[dima@bmg py-spidev]$ python
>>> import spidev
>>> dir(spidev)
['SpiDev', '__doc__', '__file__', '__name__', '__package__']

Note that it should linked against some libpython2.x.so.y.z
Perhaps your target python (if cross-compiling) is missing python-config?


text:
Q: Access to files in MongoDB GridFS with NestJS and GraphQL I'm working with NestJS with GraphQL and MongoDB.
I'm trying store image files using GridFS using mongo-gridfs package.
Uploading images to database works fine, but how can I access to this files?
I mean for example I want to get source path of this files and use it in my frontend
Here is my resolver and service:
// photo.resolver.ts

import { Resolver, Mutation, Query, Args } from '@nestjs/graphql';
import { GraphQLUpload, FileUpload } from 'graphql-upload';
import { Photo } from './dto/photo.dto';
import { PhotoService } from './services/photo.service';

@Resolver()
export class PhotoResolver {
  constructor(
    private readonly photoService: PhotoService
  ) {}

  @Query(() => ???, { nullable: true })
  async photo(@Args('id', { nullable: true }) id: string) {
    const photo = await this.photoService.findOne(id);
    return ???;
  }

  @Mutation(() => Photo)
  async uploadPhoto(@Args({name: 'file', type: () => GraphQLUpload}) file: FileUpload) {
    return await this.photoService.save(file);
  }
}

// photo.service.ts

import { Connection } from 'mongoose';
import { Injectable } from '@nestjs/common';
import { InjectConnection } from '@nestjs/mongoose';
import { FileUpload } from 'graphql-upload';
import { MongoGridFS } from 'mongo-gridfs';
import { Photo } from '../photo.interface';

@Injectable()
export class PhotoService {
  private fileModel: MongoGridFS;

  constructor(
    @InjectConnection() private readonly connection: Connection
  ) {
    this.fileModel = new MongoGridFS(this.connection.db as any, 'photo');
  }

  async findOne(id: string) {
    return await this.fileModel.findById(id);
  }

  async save(file: FileUpload): Promise<Photo> {
    return await this.fileModel.writeFileStream(file.createReadStream(), {
      filename: file.filename,
      contentType: file.mimetype
    });
  }
}

I've tried two approached:

*

*I used downloadFile method from my photoModel, but it returns path to this file in my Temp directory in local disk.

// photo.service.ts
async findOne(id: string): Promise<string> {
  return await this.fileModel.downloadFile(id); // C:\...\AppData\Local\Temp\189450ef
}

// photo.resolver.ts
@Query(() => String, { nullable: true })
async photo(@Args('id', { nullable: true }) id: string) {
  return id && await this.photoService.findOne(id);
}

It works per se but it doesn't look to me as a proper solution. I'd prefer that source path should "lead" to my server.

*I used readFileStream method from my photoModel, which return filestream and added @Res() res to arguments in resolver.

// photo.service.ts
async findOne(id: string): Promise<GridFSBucketReadStream> {
  return await this.fileModel.readFileStream(id);
}

// photo.resolver.ts
@Query(() => Boolean)
async photo(@Args('id', { nullable: true }) id: string, @Res() res) {
  const photoStream = await this.photoService.findOne(id);
  photoStream.pipe(res);
  return true;
}

And now I've got such an error in terminal:
[Nest] 12408   - 10.07.2021, 13:02:25   [ExceptionsHandler] dest.on is not a function +27555ms
TypeError: dest.on is not a function


text:
Q: Extract data from JSON file in R I have a .json file that contains corresponding pairs of IDs and category names. How can I extract them?
I converted the file:
categories <- fromJSON("CA_category_id.json")

and got a nested list as a result.
I need:
categories[["items"]]["id"]

and
categories[["items"]][["snippet"]][["title"]]

combined in one table. Like this:

id
title

1
Film & Animation

2
Autos & Vehicles

10
Music

15
Pets & Animals

...
...

You can find the initial .json file here. It is called CA_category_id.json.
Thank you for your help.

A: One easy way is to go item by item. Working code below:
library(rjson)
library(data.table)
categories <- fromJSON(file="CA_category_id.json")
table <- NULL
for (index in seq_along(categories$items) ) {
  table <- rbind(table,data.table(id=categories[["items"]][[index]][["id"]],title=categories[["items"]][[index]][["snippet"]][["title"]]))
}
table


text:
Q: How to enable active learning with multiple intent and Qnamaker KBs? I have a chatbot that routes to the appropriate KB in QnAMaker based on intent. E.g. if the question is related to Project management, then it will route to the Project management KB.
My dilemma now is how to run active learning based on the intent and routing the suggestions back to the appropriate KB.
Appreciate anyone's advice on this.
I have taken the Active learning example from Microsoft to initialize the dialog in the constructor but am unable to detect the input query.
public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Handle Message activity type, which is the main activity type for shown within a conversational interface
            // Message activities may contain text, speech, interactive cards, and binary or unknown attachments.
            // see https://aka.ms/about-bot-activity-message to learn more about the message and other activity types
            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                DialogContext dialogContext = await _dialogs.CreateContextAsync(turnContext, cancellationToken);
                DialogTurnResult results = await dialogContext.ContinueDialogAsync(cancellationToken);
                switch (results.Status)
                {
                    case DialogTurnStatus.Cancelled:
                    case DialogTurnStatus.Empty:
                        await dialogContext.BeginDialogAsync(_dialogHelper.ActiveLearningDialogName, _qnaMakerOptions, cancellationToken);
                        break;
                    case DialogTurnStatus.Complete:
                        break;
                    case DialogTurnStatus.Waiting:
                        // If there is an active dialog, we don't need to do anything here.
                        break;
                }

                await _accessors.ConversationState.SaveChangesAsync(turnContext);
            }
            else if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate)
            {
                if (turnContext.Activity.MembersAdded != null)
                {
                    // Send a welcome message to the user and tell them what actions they may perform to use this bot
                    await SendWelcomeMessageAsync(turnContext, cancellationToken);
                }
            }
            else
            {
                await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected", cancellationToken: cancellationToken);
            }
        }

I expect the active learning result to be displayed based on the intent and routing to the correct QnA KB.

A: As Matt Stannett suggested, you should probably clarify what type of Active Learning you're using, as there's active learning for both QnA & LUIS.
You should consider looking into using Dispatch, which would route to the appropriate QnA KB, LUIS app, or other miscellaneous services it supports.
See NLP with Dispatch sample for how to link together LUIS intents and QnA Maker.
Snippet:
private async Task DispatchToTopIntentAsync(ITurnContext<IMessageActivity> turnContext, string intent, RecognizerResult recognizerResult, CancellationToken cancellationToken)
{
    switch (intent)
    {
        case "l_HomeAutomation":
            await ProcessHomeAutomationAsync(turnContext, recognizerResult.Properties["luisResult"] as LuisResult, cancellationToken);
            break;
        case "l_Weather":
            await ProcessWeatherAsync(turnContext, recognizerResult.Properties["luisResult"] as LuisResult, cancellationToken);
            break;
        case "q_sample-qna":
            await ProcessSampleQnAAsync(turnContext, cancellationToken);
            break;
        default:
            _logger.LogInformation($"Dispatch unrecognized intent: {intent}.");
            await turnContext.SendActivityAsync(MessageFactory.Text($"Dispatch unrecognized intent: {intent}."), cancellationToken);
            break;
    }
}

And then for the logic of each intent, you can process the QnA as you have already done using the active learning sample.
You can also look at the CoreBot sample to help give you ideas of how to tie in dialogs with services like LUIS (which is what Dispatch is--it's essentially a parent LUIS model that routes to children services like QnA Maker or other LUIS models connected to it)

Also, recently as of 4.5 release, the SDKs now natively support Active Learning and are no longer just in experimental:
https://github.com/Microsoft/botbuilder-dotnet/blob/master/libraries/Microsoft.Bot.Builder.AI.QnA/QnAMaker.cs#L200
You can take a look at the unit tests to see how to call the Train API directly from your process qna intent.


text:
Q: Python to obtain hard drive information Can someone shed some light on what commands i can use to obtain the following from hard drives. It would be best if there was an internal Python module for this, but probably not. I do have root access to obtain any information, but i would like to stay away from having to download extra packages, so:
procinfo, swapon, hdparm, hardinfo are out of the picture, not default on Fedora 17, not sure about other distros.
Index (Device 0, could be more)
Description (Full Name, Western Digital Black Edition.....)
InterfaceType (IDE, SCSI)
Manufacturer (Western Digital, Seagate, Maxtor)
Model (WDxxx)
Size (in KB, MB or GB)
Partitions (if Any)

A: Check out sysfs.  For example, for the first disk on my Ubuntu 12.04 system most of that information can be read from or inferred by the presence of the following files and directories:

*

*/sys/block/sda/dev

*/sys/block/sda/device/scsi_device

*/sys/block/sda/device/vendor (actually "ATA," implying SATA, not "Western Digital" as might be expected)

*/sys/block/sda/device/model

*/sys/block/sda/size

*/sys/block/sda/sda1

*/sys/block/sda/sda2

*/sys/block/sda/sda5

A: I think i found a good terminal command that seems to provide a lot of the information i requested, plus much  more.
fdisk -l

Now the question remains on how to parse this amount of data!
Output from fdisk-l
Disk /dev/sda: 750.2 GB, 750156374016 bytes
255 heads, 63 sectors/track, 91201 cylinders, total 1465149168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xf4375e1b

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048      206847      102400    7  HPFS/NTFS/exFAT
/dev/sda2          206848   895822804   447807978+   7  HPFS/NTFS/exFAT
/dev/sda3      1151823870  1465147391   156661761    5  Extended
/dev/sda4       895823872  1100623871   102400000   83  Linux
/dev/sda5      1151823872  1435025407   141600768   83  Linux
/dev/sda6      1435027456  1465147391    15059968   82  Linux swap / Solaris

Partition table entries are not in disk order

Disk /dev/sdb: 1000.2 GB, 1000204886016 bytes
255 heads, 63 sectors/track, 121601 cylinders, total 1953525168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x3ac08bdc

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1            2048  1953521663   976759808    7  HPFS/NTFS/exFAT

Disk /dev/sdc: 16.0 GB, 16008609792 bytes
255 heads, 63 sectors/track, 1946 cylinders, total 31266816 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

   Device Boot      Start         End      Blocks   Id  System
/dev/sdc1              32    31266815    15633392    7  HPFS/NTFS/exFAT

A: This might be a little late, but:
If the OP just wanted a list hard disk drives attached to the system use parted (in bash): Output on my system:
[root@Bugs]#parted -m /dev/sda print devices
/dev/sda (80.0GB)
/dev/sdb (128GB)
/dev/sdc (6001GB)
/dev/sdd (4001GB)
/dev/sde (8002GB)
/dev/sdf (1500GB)
/dev/sdi (4001GB)
/dev/sdg (4001GB)
/dev/sdh (8002GB)
[root@Bugs]#

Note that parted requires a device to be specified, but it is not really needed. Also, for some drives, the actual size given was +xGB. These seemed for drives => 4TB.
Since this is a bash command, python has various utils to run these.
This is the simplest answer/result for me, and I guess for the OP. Hope this helps someone in the future.


text:
Q: How to connect Home Folder using PowerShell I tried to create user using New-QADUser cmdlet. I know this cmdlet has -HomeDrive switch. But the problem is that cmdlet is just applying path string to user's account and not creating user's home directory on the fileserver like it happens when you use ADUC console. How can I do it corerctly?

A: Does the script that is creating the user account have administrative access to the file server as well?
Why not let the script create the home drive? very simple example:
$user = read-host -prompt "Enter Username"
$server = "HOMEDRIVESERVER"
$share = "usershare$"
New-QADUser -name $user etc..
newitem -path \\$HOMEDRIVERSERVER.domain.com\$share -name $user -itemtype directory

The only gotcha here is then setting the ACLs on the folder, that could possibly be done with set-acl. A bit more info on ACLS here..
http://chrisfederico.wordpress.com/2008/02/01/setting-acl-on-a-file-or-directory-in-powershell/
The nice thing about scripting it in this way is being able to then output what it is doing to a log file for script auditing purposes. Of course, it doesn't necessarily give you the 1-step nicety the MMC console does.

A: Resulting code for creating and connecting home drive to user with $Sam sam account name:
$HomeDir = "<Path>"
$Sam = "<User's Sam Account Name>"
$User = Get-QADUser -SamAccountName "$Sam"
New-Item -Path $HomeDir -Name $Sam -ItemType Directory
$UserDir = "$HomeDir\$Sam"
$Rights = [System.Security.AccessControl.FileSystemRights]::FullControl
$Inherit=[System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit
$Propogation=[System.Security.AccessControl.PropagationFlags]::None
$Access=[System.Security.AccessControl.AccessControlType]::Allow
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("$Sam",$Rights,$Inherit,$Propogation,$Access)
$ACL = Get-Acl $UserDir
$ACL.AddAccessRule($AccessRule)
Set-Acl $UserDir $ACL
Set-QADUser -Identity $User -HomeDirectory "$UserDir" -HomeDrive "Z:"

A: powershell setfolderpermission.ps1
download from http://www.powershell.nu/wp-content/uploads/2009/02/setfolderpermission.ps1
Function CreateHomeFolder {
  Param($userinfo)
  $homeserver = '\\homeserver'
  $HomeFolderRoot = "\home\'
  Mkdir ($homeserver + $HomeFolderRoot + $userinfo['AccountName'])
}

Function UpdateHomeDirRights2 {
  Param($userinfo)
  $homeserver = '\\taz'
  $HomeDrive = "S"
  $HomeFolderRoot = "\home\'
  $HomeDirectory = $homeserver + $HomeFolderRoot + $userinfo[*'AccountName'*]
  ./SetFolderPermission.ps1 -path $HomeDirectory -Access  $userinfo[*'UserPrincipalName'*] -Permission FullControl
}


text:
Q: Suppose $y $ satisfies D.E. $dy/dx=y^2$ Describe the behaviour of the following initial conditions:
$y (0)=0$,
$y (0)=0.01$,
$y (0)=-0.01$
Ans: if I solve for $y $ first I get: $y=1/(c-x) $
$y (0)=0$ gives me a vertical asymptote.
2nd and 3rd conditions give my constant 100 and -100 values respectively. Am I correct? Is that all I'm supposed to describe?


text:
Q: Prove that $\sin(\tan 1)>\tan(\sin 1)$ Prove that $\sin(\tan 1)>\tan(\sin 1)$?
All given measurements are in radians. I have tried comparing the graphs of sin x and tan x but I wasn't able to proceed with it.

A: We may start from the fact that $\log\cos x$ is concave on $I=[0,1]$ and over there
$$ \tan(x)+2\sin(x) = \int_{0}^{x}\frac{dt}{\cos^2 t}+\int_{0}^{x}\cos(t)\,dt+\int_{0}^{x}\cos(t)\,dt\geq x $$
holds by Holder inequality. This leads to
$$ \cos^3(x) \geq \cos(\tan x)\cos^2(\sin x) $$
and by rearranging
$$ \frac{d}{dx}\tan(\sin x)=\frac{\cos(x)}{\cos^2(\sin x)}\geq\frac{\cos(\tan x)}{\cos^2(x)}=\frac{d}{dx}\sin(\tan x). $$
By integrating the middle terms on $[0,1]$ we get that $\tan(\sin 1)\color{red}{\geq} \sin(\tan 1)$.

A: As $\sin(\theta)\le1=\tan\dfrac\pi4$, it suffices to prove
$$\sin1>\frac\pi4.$$
By Taylor, as we have an alternating series,
$$\sin 1>1-\frac16.$$


text:
Q: Only two media query breakpoints in my css work..why doesn't the rest also work? My question is why will only the iphones min and max widths load in my css but
not my ipads min and max widths? I know that all my css does work individually but not all together. I also tried using multiple stylesheets instead but i had the same issue..where only the last 2 stylesheets would load.
<head>
<title></title>

<meta charset="UTF-8"/>

<meta name="viewport" content="width=device-width, initial-scale=1.0"/>

<link rel="stylesheet" type="text/css" href="css/stylesheet.css?v=1"/>

</head>

container, header, menu, home-info {
display: inline-block;
}

body {
background-color: pearl white;
}

#container {
width: 50%;
height: 800px;
background-color: white;

position: fixed;
transform: translateX(-50%);
left: 50%;
box-shadow:  0 0 75px 0px rgba(12, 3, 25, 0.8);
margin-bottom: 5px;
}

.header {
height: 200px;
width: 100%;
color: white;
transform: translateX(-50%);
left: 50%;
position: absolute;
text-align: center;
font-size: 220px;
background-color: grey;

}

.menu {
position: absolute;
top: 205px;
left: 50%;
transform: translateX(-50%);
padding: 5px;

}

.menu ul{
margin: 0;
padding: 0;
float:left;

}

.menu ul li{
float:left;
list-style:none;
position:relative;
}
.menu ul li a{

display:block;

    text-decoration:none;
    padding:10px 10px;
    text-align:center;
    width: 775px;
    height: 25px;
    background-color: silver;
    font-size: 25px;
    border-radius: 5px;
    color: white;
}
.menu ul li a:hover{

    background: yellow;
    color: #00357d;
    box-shadow: 5px 5px 25px 5px yellow;
}

.menu ul ul{

    visibility:hidden;
    position:absolute;
}
.menu ul li:hover ul{

visibility:visible;
}

.menu ul ul li a:hover {

background: yellow;
color: #00357d;

}
.menu ul ul ul  {

visibility: hidden;
position: absolute;

}
.menu ul ul li:hover ul {

visibility: visible;
}

.menu ul ul ul li a:hover {

background: yellow;
color: #00357d;

}
.menu ul ul ul ul  {

visibility: hidden;
position: absolute;

}
.menu ul ul ul li:hover ul {

visibility: visible;
}

.menu ul ul ul ul li a:hover {

background: yellow;
color: #00357d;

}
.menu ul ul ul ul ul  {

    visibility: hidden;
    position: absolute;

}
.menu ul ul ul ul li:hover ul {

    visibility: visible;
}

.home-info {
color: grey;
font-size: 20px;
top: 550px;

position: absolute;

margin-left: auto;
margin-right: auto;

}

/*max-ipads*/

@media only screen and (max-width: 1024px){

    #container {
    width: 50%;
    height: 800px;
    background-color: white;

    position: fixed;

    transform: translateX(-50%);
    left: 50%;
    box-shadow:  0 0 75px 0px rgba(12, 3, 25, 0.8);
    margin-bottom: 5px;
}
}
@media only screen and (max-width: 1024px){
.header {

position: absolute;
    height: 100px;
    width: 100%;
    color: white;
    transform: translateX(-50%);
    left: 50%;

    text-align: center;
    font-size: 105px;
    background-color: grey;
}
}
@media only screen and (max-width: 1024px){
.menu {

position: absolute;

    top: 75px;
    left: 50%;
    transform: translateX(-50%);
    padding: 5px;

}
}
@media only screen and (max-width: 1024px){
.menu ul li a{

display:block;

    text-decoration:none;
    padding:10px 10px;
    text-align:center;
    width: 350px;
    height: 15px;
    background-color: silver;
    font-size: 25px;
    border-radius: 5px;
    color: white;
}
}
@media only screen and (max-width: 1024px){
.home-info {
color: grey;
font-size: 15px;
top: 420px;

position: absolute;

margin-left: auto;
margin-right: auto;
}
}

/*---min-width---*/

@media only screen and (min-width: 768px){
#container {
width: 50%;
height: 1024px;
background-color: white;

position: fixed;

transform: translateX(-50%);
left: 50%;
box-shadow:  0 0 75px 0px rgba(12, 3, 25, 0.8);
margin-bottom: 5px;
}
}
@media only screen and (min-width: 768px){
.header {

height: 80px;
width: 100%;
background-color: grey;
color: white;
transform: translateX(-50%);
left: 50%;

position: absolute;

text-align: center;
font-size: 80px;
}
}
@media only screen and (min-width: 768px){
.menu {

position: absolute;

top: 55px;
left: 50%;
padding: 5px;
transform: translateX(-50%);
}
}
@media only screen and (min-width: 768px){
.menu ul li a{

display:block;

    text-decoration:none;
    padding:10px 10px;
    text-align:center;
    width: 480px;
    height: 25px;
    background-color: silver;
    font-size: 15px;
    border-radius: 5px;
    color: white;
}
}
@media only screen and (min-width: 768px){
.home-info {

color: grey;
font-size: 21px;
top: 430px;

position: absolute;

margin-left: auto;
margin-right: auto;
}
}

/*iphones-max*/

@media only screen and (max-width: 480px){
#container {

width: 50%;
height: 350px;
background-color: white;

position: fixed;

transform: translateX(-50%);
left: 50%;
box-shadow:  0 0 75px 0px rgba(12, 3, 25, 0.8);
margin-bottom: 5px;
}
}
@media only screen and (max-width: 480px){
.header {

height: 50px;
width: 100%;
color: white;
transform: translateX(-50%);
left: 50%;

position: absolute;

text-align: center;
font-size: 50px;
background-color: grey;
}
}
@media only screen and (max-width: 480px){
.menu {

position: absolute;

top: 55px;
left: 50%;
transform: translateX(-50%);
padding: 5px;

}
}
@media only screen and (max-width: 480px){
.menu ul li a{

display:block;

    text-decoration:none;
    padding:10px 10px;
    text-align:center;
    width: 125px;
    height: 15px;
    background-color: silver;
    font-size: 10px;
    border-radius: 5px;
    color: white;
}
}
@media only screen and (max-width: 480px){
.home-info {

color: grey;
font-size: 10px;
top: 270px;

position: absolute;

margin-left: auto;
margin-right: auto;
}
}

/*smartphone-min*/

@media only screen and (min-width: 320px){
#container {

width: 50%;
height: 420px;
background-color: white;

position: fixed;

transform: translateX(-50%);
left: 50%;
box-shadow:  0 0 75px 0px rgba(12, 3, 25, 0.8);
margin-bottom: 5px;
}
}
@media only screen and (min-width: 320px){
.header {

height: 80px;
width: 100%;
background-color: grey;
color: white;
transform: translateX(-50%);
left: 50%;

position: absolute;

text-align: center;
font-size: 80px;
}
}
@media only screen and (min-width: 320px){
.menu {

position: absolute;

left: 50%;
padding: 5px;
transform: translateX(-50%);
margin-top: 30px;
}
}
@media only screen and (min-width: 320px){
.menu ul li a{

display:block;

    text-decoration:none;
    padding:10px 10px;
    text-align:center;
    width: 200px;
    height: 25px;
    background-color: silver;
    font-size: 10px;
    border-radius: 5px;
    color: white;
}
}
@media only screen and (min-width: 320px){
.home-info {

color: grey;
font-size: 10px;
top: 320px;

position: absolute;

margin-left: auto;
margin-right: auto;
}
}

A: If this is exactly how your styles are laid in your stylesheet (tough to tell without seeing an actual source), then I believe your problem is NOT that the iPad styles aren't loading - it's that they are loading in the wrong order.
You should lay out your styles from smallest (top) to largest (bottom) (i.e. 320 then 480 then 768 etc.). Otherwise your smaller screen styles are likely overriding your larger screen styles.
For example, if I do:
@media (max-width: 1024px) {
    .box { background: red; }
}

@media (min-width: 420px) {
    .box { background: yellow; }
}

The background color will be yellow on any screen from 420px to 1024px.
Therefore, you need to either switch the order from smaller to larger OR you can get more specific with your media queries. Example:
@media (min-width: 768px) and (max-width: 1024px) {
    .box { background: red }
}


text:
Q: Parallel Read and Dbcontext threading ssues We have to read 2 select statements need to run parallelly, means should be awaited together.
var t1 = GetSomeData1(somParams);
var tWrite = await WriteData(someParams);
var t2 = GetSomeData2(somParams);
await Task.WhenAll(t1, t2);

Note 1 write is between but in errors we see this error sometimes,

System.InvalidOperationException: A second operation was started on
this context before a previous operation completed. This is usually
caused by different threads concurrently using the same instance of
DbContext. For more information on how to avoid threading issues with
DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.    at
Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
at
Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()

As per this. https://learn.microsoft.com/en-us/ef/ef6/saving/transactions default transaction isolation level is READ COMMITED.
I know read and write in READ COMMITED causes blocks but does we get the same error when we mix read and write.
What is the recommendation to avoid this error and use parallel reads.

A: As it reads on the link from your exception:

Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance. This includes both parallel execution of async queries and any explicit concurrent use from multiple threads. Therefore, always await async calls immediately, or use separate DbContext instances for operations that execute in parallel.
When EF Core detects an attempt to use a DbContext instance concurrently, you'll see an InvalidOperationException with a message like this:
A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext, however instance members are not guaranteed to be thread safe.
When concurrent access goes undetected, it can result in undefined behavior, application crashes and data corruption.

https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/#avoiding-dbcontext-threading-issues


text:
Q: Email value not showing using POST method I have this form in which there is only one field i.e. "Email id", so what I have to do is that when I entered the email id the email id must be split into two parts like user name and domain name and must be displayed in next form.
So my problem is that my 2nd form doesn't display the result, however when I used $_SESSION method in place of $_POST(to take value of email field) it takes the value and also split it but takes only one value as I want to take multiple email ids.
For better understanding please check my code.
<?php
    session_start();
?>
<!Doctype html>

        <title>PHP3</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css">

                <form class="form-horizontal" method="post" action="screen3_controller.php">

                        Email:

                            <input type="email" class="form-control"  name="email_text" id="email_text">

                            <input type="submit" name="submit" id="submit_button" class="btn btn-default" value="Submit">

                </form>

                    Email Id

                <?php
                    if(isset($_SESSION['all_post']) && !empty($_SESSION['all_post']))
                    {
                       foreach($_SESSION['all_post'] as $key=>$value)
                       {
                        ?>

                                <?php echo $value['email_text']; ?>

                    <?php
                        }
                    }
                ?>

                        User Name
                        Domain Name

                    <?php
                        $str = $_POST['email_text'];
                        $hello = explode("@", $str);
                        $_SESSION ['emails'] = $hello;
                        echo "
";
                        foreach ($_SESSION ['emails'] as $value)
                        {
                            echo "$value	";
                        }
                        echo "
";
                    ?>

Controller:
<?php
    session_start();
    $data = $_POST;
    if (isset($data['submit'])) {
        $_SESSION['all_post'][] =  $data;
    }
    header('Location:screen3_2.php'); exit();
?>

A: As I can see,
In your code you are posting your form data to controller, not the second page.
Though you are storing your data to $_SESSION in your controller page, That's how you're able to access data from second page.
Solution :
either access data on second page using $_SESSION, or
POST your first page to directly second page, and access data using $_POST.

A: When the following code executes, it does NOT send the POST vars with it.
They are lost at that point.  However, you have stored the data in the session.
header('Location:screen3_2.php'); exit();

Also note that the following code:
$str = $_POST['email_text'];
$hello = explode("@", $str);
$_SESSION ['emails'] = $hello;

Will store the two parts of exactly one email. You mentioned that you want to store multiple emails and this code will not accomplish that.
It seems to me that what you want to do is to keep going back to the same page and reusing the form while collecting email addresses.  Please confirm.
Try this:
Do not use a separate controller file. Take that code and remove the redirect. Put that code at the top of the file. This way you collect
all the email addresses from $_POST.
<?php
    // Taken from 'controller'
    session_start();
    // Only process post if it exists
    if ( ! empty($_POST) ) {
        $data = $_POST;
        if ( isset($data['submit']) ) {
            $_SESSION['all_post'][] =  $data;
        }
    }
    // No redirect
 ?>
<?php // put the form here ?>
<form class="form-horizontal" method="post" >
<input type="email" class="form-control"  name="email_text" id="email_text">
<input type="submit" name="submit" id="submit_button" class="btn btn-default" value="Submit">
</form>

<?php
    // output all the email addresses collected
    if(isset($_SESSION['all_post']) && !empty($_SESSION['all_post'])) {
        foreach($_SESSION['all_post'] as $key=>$value) {
            $parts = explode('@', $value['email_text']);
                    ?>

            <?= $parts[0] ?>	 <?php // before @ ?>
            <?= $parts[1] ?>	 <?php // after @ ?>

<?php
        }
    }
?>
</form>


text:
Q: Azure Website doesn't recognize my Database's Table after changing the Schema I have a Microsoft Azure Website running and working with an Azure SQL Database for the sole purpose of storing and retrieving user accounts. However I needed a mobile client as well there fore according to numerous tutorials online such as THIS, I had to change the 'schema' of the database's table from 'dbo' to my mobile service's name which is 'usermobileservice'.
This was done using the SQL query:
CREATE SCHEMA usermobileservice;
ALTER SCHEMA usermobileserviceTRANSFER dbo.usertable;

This did the trick and I was able to connect to the Database using my mobile applications BUT now I can't access the database using my Azure Website! Gives me this error:
Server Error in '/' Application.

Invalid object name 'UserTable'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'UserTable'.

I believe the ASP.NET Web Application cannot find the Database Table anymore since I changed the schema? What is the right way of sharing the data between a Website and a Mobile Service?

A: For those of you having the same issue, Just replace your SQL queries that call the table (where the schema was changed) with this:

your_mobile_service_name.Your_Table_Name

In my case:
usermobileservice.UserTable
Example:
SELECT * FROM usermobileservice.UserTable

Thank you @Brendan Green for the directions!


text:
Q: How to avoid implicit conversion for an Integer column   SELECT [BusinessEntityID],[NationalIDNumber],[LoginID],[OrganizationNode]
  FROM [AdventureWorks2014].[HumanResources].[Employee]
  where BusinessEntityID = 5

I get convert_implicit() function called by SQL Server after executing the query in Actual Execution Plan.
  SELECT [BusinessEntityID],[NationalIDNumber],[LoginID],[OrganizationNode]
  FROM [AdventureWorks2014].[HumanResources].[Employee]
  where BusinessEntityID = convert(int,5)

Obviously when I explicitly convert the Scalar value to Integer type, convert_implicit() function is not called. Is there any way we can avoid implicit conversion for a scalar int value without using the explicit conversion. Also I would like to know the performance difference between implicit conversion ,explicit conversion and no conversion happened at all.

A:
How to avoid implicit conversion for an Integer column

It is the parameter that has been implicitly converted, not the column.
The query has been subject to Simple Parameterization by SQL Server. You have no control over the datatypes used in this process. It uses the smallest datatype that can hold the literal value (5 can fit into a tinyint). The implicit cast of a tinyint parameter to an int won't cause any problems.
However to avoid having multiple plans in cache for int, smallint, tinyint and get rid of the implicit cast you could explicitly parameterize the query yourself - with a parameter of datatype int rather than having it be parameterized automatically.
EXEC sys.sp_executesql
  N'SELECT [BusinessEntityID],[NationalIDNumber],[LoginID],[OrganizationNode]
  FROM [AdventureWorks2014].[HumanResources].[Employee]
  where BusinessEntityID = @BusinessEntityID',
  N'@BusinessEntityID INT',
  @BusinessEntityID = 5;

One other alternative would be to block simple parameterisation by adding a redundant AND 1=1 as below. But I don't recommend this as then you will get plans compiled and cached for every different literal value that you pass.
SELECT [BusinessEntityID],
       [NationalIDNumber],
       [LoginID],
       [OrganizationNode]
FROM [AdventureWorks2014].[HumanResources].[Employee]
where BusinessEntityID = 5
      AND 1=1

A: Community wiki answer:
Use a variable, you will also get the benefits of query reuse
Declare @ BeID int = 5
select xxx where BuisnessEntityID = @BeID

If you want to be certain you need to strongly type the query, either by using a variable or by using cast/convert:
select xxx where BuisnessEntityID = CAST (5 as int)

I think the performance overhead of the implicit conversion there is negligible - but there I might be wrong. But by using a variable you will definitely get the benefits of query cache reuse.


text:
Q: Empty Angular2 project increases memory in IE 11 My company is currently building a very large SPA written in Angular 2 and we have some issues regarding memory consumption.
During my tests, I have commented out all code from the app, leaving just the main module and two components that are completely empty.
We use Webpack for transpilation purposes.
While profiling in Chrome, the memory consumption seemed quite consistent, but when I did the same in IE11 (the client will mainly use this browser), the memory seems to constantly increase even if I refresh the browser window.
Following are two screenshots of the IE profiler as well as the task manager. Each spike indicates a browser refresh.
Also note, that taking a heap snapshot is showing a constant value of 3.16Mb for my website, so nothing wrong there.
This issue is made worse on the full version, where after some hours of work, the browser can reach over 1Gb.

The Task Manager :

Is this constant memory increase in IE11 a known issue?
If you would like some more info on my implementation please ask.


text:
Q: How can i set a default value to AspxGridView TimeEdit control I want to set default value current time for AspxGridView TimeEdit control. Is it possible?
KR,
Çağın

A: This can be done by using the ASPxGridView's CellEditorInitialize event.  Check the value of the e.Column.FieldName property and then set the e.Editor.Value as needed.


text:
Q: MKCircleRenderer not updating radius changes correctly first of all I'm using Xamarin.iOS and I'm trying to draw a circle on an MKMapView. This works fine with the following code
in my controller I have
private MKCircleRenderer _circleRenderer;

private MKOverlayRenderer CircleOverlayRenderer(MKMapView mapView, IMKOverlay overlay)
{
    return _circleRenderer ?? (_circleRenderer = new MKCircleRenderer(overlay as MKCircle)
    {
        FillColor = UIColor.Blue,
        Alpha = 0.5f
    });
}

Now I added a Slider so the user can change the radius of the circle
private void _radiusRadius_Changed(object sender, EventArgs e)
{
    if (_circleOverlay != null)
    {
        _mapView.RemoveOverlay(_circleOverlay);
    }

    _circleOverlay = MKCircle.Circle(_mapView.CenterCoordinate, _radiusRadius.Value);
    Console.WriteLine("Lat: {0}, Long: {1}, Radius: {2}", _mapView.CenterCoordinate.Latitude, _mapView.CenterCoordinate.Longitude, _radiusRadius.Value);
    _mapView.OverlayRenderer = CircleOverlayRenderer;
    _mapView.AddOverlay(_circleOverlay);
}

but instead of the circle getting bigger or smaller it is moving in the direction of the upper left corner from the map
(and another small problem is that the center of the drawn radius is not in the center of the map although i use the center coordinate of the map...)
I did my researches and found this entry on stackoverflow
MKCircle is not updating radius but it's translating
which is exactly my problem but this guy was using the ios6 version with an override of the GetViewForOverlay function in the MKMapViewDelegate (I tried implementing that way but failed miserably) and to be honest I'd rather not use deprecated stuff...
Thanks in advance
update:
The Solution (thanks to Anna!)
    private MKOverlayRenderer CircleOverlayRenderer(MKMapView mapView, IMKOverlay overlay)
    {
        return new MKCircleRenderer(overlay as MKCircle)
        {
            FillColor = UIColor.Blue,
            Alpha = 0.5f
        };
    }


text:
Q: Call to a member function setTemplate() on a non-object in home page My home.phtml file
echo $this->getLayout()->createBlock('banner/Monblock')
->setTemplate('banner/afficher.phtml')->toHtml();

my layout file.
<?xml version="1.0" ?>
<layout version="0.1.0">
  <test_adminhtml_index_index>
     <reference name="content">
             <block type="banner/Myblock"  name="afficher_monbloc"
                  template="banner/afficher.phtml"/>
                   <block type="banner/adminhtml_grid" name="banner" />
      </reference>

   </test_adminhtml_index_index>

   <reference name="content">
             <block type="banner/Monblock"  name="afficher_monbloc"
                  template="banner/afficher.phtml"/>
                   <block type="banner/adminhtml_grid" name="banner" />
      </reference>

       <default>
          <reference name="content">
          </reference>
      </default>
      <banner_index>
           <reference name="content">
               <block type="banner/Monblock"  name="afficher_monbloc"
                  template="banner/afficher.phtml"/>
                  <block type="test/test"  name="test"
                          template="test/tes2.phtml" />
           </reference>
      </banner_index>
</layout>

My block file
class Banner_Banner_Block_Monblock extends Mage_Core_Block_Template
{
     public function methodblock()
     {
         return 'informations about my block !!' ;
     }
}

config.xml
<?xml version="1.0"?>
  <config>
     <modules>
        <Banner_Banner>
          <version>1.0.0</version>
        </Banner_Banner>
     </modules>
     <frontend>
       <routers>
          <banner>
              <use>standard</use>
              <args>
                 <module>Banner_Banner</module>
                 <frontName>banner</frontName>
              </args>
           </banner>
       </routers>
       <layout>
            <updates>
                <Banner_Banner>
                    <file>Banner.xml</file>
                </Banner_Banner>
            </updates>
        </layout>
    </frontend>
    <admin>
     <routers>
         <banner>
            <use>admin</use>
            <args>
               <module>Banner_Banner</module>
               <frontName>admintest</frontName>
            </args>
         </banner>
      </routers>
 </admin>
 <adminhtml>
   <layout>
      <updates>
          <banner>
              <file>banner.xml</file>
           </banner>
      </updates>
   </layout>
   <menu>
      <banner translate="title" module="adminhtml">
         <title>My Banner</title>
         <sort_order>100</sort_order>
         <children>
             <set_time>
                   <title>Add Banner</title>
                   <action>admintest/adminhtml_index</action>
              </set_time>
          </children>
       </banner>
    </menu>
</adminhtml>
     <global>
      <models>
<banner>
     <class>Banner_Banner_Model</class>
     <resourceModel>Banner_mysql4</resourceModel>
 </banner>
<banner_mysql4>
     <class>Banner_Banner_Model_Mysql4</class>
     <entities>
         <banner>

banner

         </banner>
      </entities>
</banner_mysql4>
</models>

<resources>

        <test_write>
            <connection>
                <use>core_write</use>
            </connection>
        </test_write>

       <test_read>
          <connection>
             <use>core_read</use>
          </connection>
       </test_read>
</resources>

            <blocks>
              <Banner>

              <class>Banner_Banner_Block</class>
             </Banner>

            </blocks>

     </global>
</config>

A: You need to change this part of your config.xml:
<blocks>
     <Banner>
         <class>Banner_Banner_Block</class>
     </Banner>
</blocks>

to
<blocks>
     <banner>
         <class>Banner_Banner_Block</class>
     </banner>
</blocks>

then call the block like this:
echo $this->getLayout()->createBlock('banner/monblock')->setTemplate('banner/afficher.phtml')->toHtml();

A: In your config.xml file, you should have a code like this
FILE: app\code\local\Banner\Banner\etc\configx.xml
<global>
    <blocks>
        <banner>
             <class>Banner_Banner_Block</class>
        </banner>
    </blocks>
</global>

This defines your custom module block section. Without this, Magento will not understand where should it look for your custom blocks. So make sure, this code exist.
Kindly note the block alias name. It should be banner in this case. Then you can now refer your custom block like this.
 banner/monblock

Note all letters should be in small letter.
But I recommend you to change block alias name to banner_banner. That is the best practice. In general, it should be namespace_modulename. Now you can refer you block with
 banner_banner/monblock

In either way, you need to change this in everywhere. Means in layout file as well as in home.phtml file.

A: There issue with block type banner/Monblock .it should be in banner/monblock.Block class  type should be small letter.
Also Suggest used Mage_Adminhtml_Block_Template class instead Mage_Core_Block_Template  because Mage_Adminhtml_Block_Template is add more functions which will suitable with backend
The contend after  </test_adminhtml_index_index> should with in handler
<reference name="content">
             <block type="banner/Monblock"  name="afficher_monbloc"
                  template="banner/afficher.phtml"/>
                   <block type="banner/adminhtml_grid" name="banner" />
      </reference>

class Banner_Banner_Block_Monblock extends Mage_Core_Block_Template change to
class Banner_Banner_Block_Monblock extends Mage_Adminhtml_Block_Template.


text:
Q: change row colour in a loop based on value I wish to change tr background colour based on value in a loop so if the value is X for next a few records then colour should be blue, if the value is changed to something else then colour should also be changed to yellow.
My code below is faulty which makes all the rows yellow after painting first one as blue.
foreach ($arr as $key => $value)
{
  if ($old_value == $value)
  {
    $colour = 'blue';
  }
  else
  {
    $colour = 'yellow';
    $old_value = $value;
  }

}

I need output like this:

A: You need to change the color according to the last color used, something like
$arr = array(1,1,1,4,4,7,3);
$old_value = 0;
$colour = 'blue';
echo '
';
foreach ($arr as $key => $value)
{
    if ($old_value == $value)
    {
        //colour stays the same
    }
    else
    {
        if($colour == 'blue')
        {
            $colour = 'yellow';
        }
        else
        {
            $colour = 'blue';
        }
        $old_value = $value;
    }
    echo '
' . $value . '
';
}
echo '
';

Now every group of equal values will have the same colour, and the next group has the other colour.

A: Make sure you are using your cycle right:
foreach ($arr as $key => $value)
{
  if ($old_value == $value)
  {
    $colour = 'blue';
  }
  else
  {
    $colour = 'yellow';
    $old_value = $value;
  }

  //now $color has the desired value
  //so now you should echo your tr

}

//now $color contains just the last row

A: $arr = ['something', 'something else', 'another something'];
$old_value = "";
foreach ($arr as $key => $value){
    if ($old_value == $value){
        $colour = 'blue';
    }
    else{
    $colour = 'yellow';
    $old_value = $value;
    }
    echo '
' . $value . '
';
    }

Outputs:

A: you may do like
$i=0;
$old_value = "";

foreach ($arr as $key => $value)
{
  if ($old_value != $value)
  {
    $old_value = $value;
    $i++;
  }

  if($i % 2 == 1)
  {
    $colour = 'yellow';
  } else {
    $colour = 'blue';
  }

}

A:  $i=0;
 foreach($resultex as $rowex)
      {
 if ($old_value != $rowex)
      {
        $old_value = $rowex;
        $i++;
      }

    if($i%2 == 1)
               {

       }
            else
               {

       }
     }


text:
Q: KDE Disable when selecting and pressing CTRL + Backspace, to not delete everything When I select something in the Menu, Login or probably anything KWin related in KDE with CTRL + A and I then accidentally press CTRL + Backspace, since I am still holding down CTRL, it doesn't delete everything, but instead leaves something behind afterwards.
How can I disable this or is this a bug?


text:
Q: handle different config file versions in the same repo We have a git repo that is set up in a git-flow(ish) type way -- we have 3 "mainline" branches, dev, release, and production. Our workflow is something is that a new piece of code goes into dev, which has a cycle of two weeks. Once those two weeks is up, dev becomes "release", at which point it is tested and things are fixed on it, but no new features are applied. 2 weeks after that, release gets deployed, and becomes the production branch, which doesn't really get touched (except in the case of emergency out of band fixes)
Because of that, we have 3 versions of the database locally to track the 3 different branches. We tend to have a lot of schema churn, so it is very common that changes that happen to it in the dev branch could break what is on release or production.
The problem is, how do you manage 3 different sets of config files in the same git repository? Currently, what we are doing is .gitignoring them, and keeping 3 local versions of the codebase on everyones machine. However, this isn't really ideal for several reasons, and it would be great if we could have a single version of the repo and just switch between the branches.
I guess I am looking for a way to check a file in to a branch, and have it stay there, but not get picked up between merges of the mainline branches. So that way there could be a version on dev, one on release, and a third on master, but each would be isolated from the others. Sort of like a .gitignore for merging.
Is that even possible? Has anyone run into this before? (can't believe we are the only ones) How did you solve it?

A: If you are talking of environment configs, you can have a config for each environment like dev.config, test.config, production.config etc. Changes can be done to dev.config on the dev branch. Once it gets tested and the time for release comes, the test / production config in release can be updated and tested appropriately. It doesn't makes sense to have one config for all environments.

A: Manojlds is right: separate config files are best (no merge issue that way).
It is best to combine those "value config files" with a content filter driver in order to generate automatically on checkout (with a 'smudge' script the right and final (but non-versioned) config file.
See the question "Something like gitignore, but not gitignore" for more.


text:
Q: Android - Copy an user selected image to own folder? I'm working on a feature that lets users select their own background image in an app.
Should that image be copied into an app associated folder after they selected it or what's convention for this?

A: In this case the user has freedom to select a picture from the other folder hierarchies and that picture can be deleted by the user. So you should save a copy of that image in your application folder and decode that picture to use as the background.
But the user can repeat this operation several times and saving a copy of each picture will consume a lot of space so, you should just create a single file that will be overwritten each time the user selects a picture to change the background.
And you need not to have a very high resolution image. You should down sample the image and then save it.
Follow this link for effective bitmap decoding.


text:
Q: useCallback does not inherit parent props I'm detecting keypresses in a component that is aware of what dialog component is currently open elsewhere in the app via a prop, currentDialog. Normally I'd be able to access this prop in a nested function but it seems this isn't possible when using useCallback:
export const AllAreaNav = (props) => {

    console.log('AllAreaNav / props.currentDialog: ', props.currentDialog); // displays correct dialog

    const handleKeyPress = useCallback((event) => {

        console.log('AllAreaNav / handleKeyPress / props.currentDialog: ', props.currentDialog); // displays undefined

        if(event.keyCode === 70) {
            //Do whatever when F is pressed
            console.log("F key pressed");
            if (props.currentDialog == "DialogSearchBar") {
                // Take action based on DialogSearchBar being active
            } else {
                // Take action based on DialogSearchBar NOT being active
            }

        }

    }, []);

    useEffect(() => {
        // Listener for keypresses
        document.addEventListener("keydown", handleKeyPress, false);
        return () => {
            document.removeEventListener("keydown", handleKeyPress, false);
        };
    }, []);

    return (
        {jsxElements}
    )
};

So now I'm a little unsure of a straightforward way of passing this as a parameter - assuming this would be the next step. From researching I believe it's fine to add another parameter alongside event? That this should work as I intend:
const handleKeyPress = useCallback((event, currentDialog) => {

However, I'm not entirely sure of how to initially pass this to the function. If I modify the listener to be:
document.addEventListener("keydown", handleKeyPress(event, props.currentDialog, false);

I'm unsure if this is correct, or where exactly to define event in this context, in the manner handleKeyPress defaults its as a parameter.

A: It seems that you were trying to resolve the problem by parametrizing the callback but you did not have an event in your context. In order to parametrize AND have the event in context, you must create a closure on the currentDialog parameter.
You can try this solution:
/**
 * move callback definition outside the component
 * and create a closure on currentDialog (function returning a function)
 */
const handleKeyPress = (currentDialog) => (event) => {
  if (event.keyCode === 70) {
    //Do whatever when F is pressed
    console.log("F key pressed");
    if (currentDialog == "DialogSearchBar") {
      // Take action based on DialogSearchBar being active
    } else {
      // Take action based on DialogSearchBar NOT being active
    }
  }
};

export const AllAreaNav = (props) => {
  console.log("AllAreaNav / props.currentDialog: ", props.currentDialog); // displays correct dialog

  useEffect(() => {
    // Listener for keypresses
    const listener = handleKeyPress(props.currentDialog); // use closure to create a callback closured on currentDialog value
    document.addEventListener(
      "keydown",
      listener,
      false
    );
    return () => {
      document.removeEventListener(
        "keydown",
        listener,
        false
      );
    };
  }, [handleKeyPress, props.currentDialog]); // pass callback and currentDialog value to dependency array

  return { jsxElements };
};


text:
Q: Auto-scale persistent storage My application runs on an embedded database that writes to file system storage instead of a standard database. I want to know how to set my OpenShift app to be able to have persistent storage that automatically grows.
Currently, my application database writes into a mount path in the file system (in standard Linux environment), e.g. /mnt/db If I moved it to Openshift how can I be able to have such persistent storage that scales as the data grows?
From the Openshift pricing page: https://www.openshift.com/products/online/
It shows storage from 2GB to 150GB, does it mean that this is the hard limit? How about my application data hits 1TB above? It would not work with current Red-hat hosted version of Openshift?


text:
Q: What do class_type='Main' and self.main = parent mean? class x_Plugin(SpyderPluginWidget):

    """Spyder plugin for unit testing."""
    # focus_changed = Signal()

    def __init__(self, parent, class_type='Main'):
        """

        """
        SpyderPluginWidget.__init__(self, parent)

        self.class_type = class_type

        self.main = parent #

What do class_type='Main' and self.main = parent mean?

A: self.main = parent # principal is a main function of the program that is the same as the parent (parent with all its properties).


text:
Q: How to catch events about start and finish of task in Camunda? I need to get messages about task started and finished. I'd like to create one common callback and don't modify each task.
Any ideas?

A: The camunda-bpm-reactor extension and the camunda-spring-boot-starter (version 3.3 and up) both support registering global listeners for every task "hook" without explicitly adding a listener in the model.
The reactor extension is based on a a meanwhile no longer supported early projectreactor eventbus, so if you are free to choose, I would go for the spring eventing solution.
You can subscribe to all task create events happening in your engine via:
@Component
class MyTaskListener {

    @EventListener(condition="#taskDelegate.eventName=='create'")
    public void onTaskEvent(DelegateTask taskDelegate) {
      // do stuff on every task create
    }
}


text:
Q: use of regular expressions with python I'm trying to write a script that takes a list of words from one file and try to search for those specific words in another file and if the specific word is found then the entire line is printed.
The problem is that i want in the search file only the words that i'm looking for will be matched
exemple : if i have to search for the word "word123", i don't need to have
the hit "word12345" to be found just the first one corresponding to the exact word i wrote
This is the code :
for line in searchfile:
    for word in keywords:
        if re.search ("^word$" , line):
            print(line.strip(), file = new_file)
            break

The result is always an empty file

A: if re.search (r"\b"+word+r"\b" , line):

You need to use \b or word boundary here .

A: Instead of the regex
"^" + word + "$"

try:
r"^.*\b" + word + r"\b.*$"


text:
Q: How to change the icon of Datetimepicker of WPF toolkit? I want to change the default drop down icon of the DateTimePicker control to a calender icon. How Can i do it?

A: Just modify style of dateTimePicker by right click on it on designer => modify style => create a local copy.
Then you can modify style to insert your own button (name of element is PART_Button)


text:
Q: How to show a continuous function on $[0,1]$ interval is a vector space? Trying out some problems and the title says it all,

Show that a set of continuous functions on $[0,1]$ interval belongs to a vector space

We were told that since the vector addition and multiplication is defined to be continuous in calculus it does not need to be defined, but stuck. Could someone help me out? Thanks!

A: Hint: $V$ with addition and scalar multiplication defined is a vector space over $\mathbb R$ if:

*

*$(V, +)$ is a commutative group

*For all $\alpha, \beta\in\mathbb R$ and all $v\in V$, $$\alpha(\beta v) = (\alpha\beta)v$$

*For all $v\in V$, $1v = v$

*For all $\alpha, \beta\in\mathbb R$ and all $v\in V$, $$(\alpha + \beta)v = \alpha v+\beta v$$

*For all $\alpha\in\mathbb R$ and all $v,w\in V$, $$\alpha(v+w)=\alpha v + \alpha w.$$

Go step by step. Prove each point individually, none of them is particularly hard.

A: Your question is confused.  What set?  What vector space?  The set of all continuous functions on $[0,1]$ is a vector space: just verify the properties
in the definition of vector space.  For some subset $S$ of these to form a
vector space, you just have to verify that for any $f$ and $g$ in $S$ and any
real number $c$, $f+g$ and $cf$ are in $S$.


text:
Q: C++ Linked List Display All I'm new to C++ and currently experimenting about linked lists and I'm having trouble with displaying the multiple values in my program. The problem is in the DisplayAll function.
    struct node
    {
        string firstname;
        string lastname;
        string phonenumber;
        string dayofbirth;
        string monthofbirth;
        string yearofbirth;
        string age;
        string streetname;
        string city;
        string state;
        string zipcode;
        char ch;
        static int count;
        int count2;
        node* next;
    };

    class InfoBook
    {
    private:
        node* head;
        node* current;
        node* temp;

    public:
        InfoBook();

        void userPromptStatement();
        node* AddNode(node*);
        void DisplayAll();
        //node* SearchNode();
        //void sort(node*, int);
        void UpdateNode();
        //node* DeleteNode(node*);
    };

node* InfoBook::AddNode(nodePtr temp)
{
    string firstname;
    string lastname;
    string phonenumber;
    string dayofbirth;
    string monthofbirth;
    string yearofbirth;
    string age;
    string streetname;
    string city;
    string state;
    string zipcode;
    InfoBook ad;

       if(head != NULL)
        {
            current = head;
            while(current -> next != NULL)
            {
                current = current -> next;
            }
            current -> next = new node;
            current -> firstname = temp -> firstname;
            current -> lastname = temp -> lastname;
                     ////code here to add the other values////
            current -> zipcode = temp -> zipcode;
            current -> next -> next = nullptr;
            return current;
            ad.userPromptStatement();
        }
       else
        {
            head = new node;
            head -> firstname = temp -> firstname;
            head -> lastname = temp -> lastname;
                    ////code here to add the other values////
            head -> zipcode = temp -> zipcode;
            head -> next = nullptr;
            return current;
        }
}

    ////////////////////////////////DisplayAll/////////////////////////////////

    void InfoBook::DisplayAll()
    {
        current = head;
        int count = 1;
        string firstname;
        string lastname;
        string phonenumber;
        string dayofbirth;
        string monthofbirth;
        string yearofbirth;
        string age;
        string streetname;
        string city;
        string state;
        string zipcode;

            if(current == nullptr)
            {
                cout << "\n\n\No Record exists.";
            }
                while(current != NULL)
                {      ////////The problem is somewhere between here////////
                    cout << "Record # " << count << " : ";
                    cout << current -> firstname << endl;
                    cout << current -> lastname << endl;
                    cout << current -> phonenumber << endl;
                    cout << current -> dayofbirth << endl;
                    cout << current -> monthofbirth << endl;
                    cout << current -> yearofbirth << endl;
                    cout << current -> age << endl;
                    cout << current -> streetname << endl;
                    cout << current -> city << endl;
                    cout << current -> state << endl;
                    cout << current -> zipcode << endl;
                    cout <<"\n\n\n";
                    current = current -> next;
                    count++;
                }
    }
                            ///////////////////////////////////////////////

The program displays only 'Record # : ' but not the values. Any ideas?
//////////////////added//////////////////////
 node* temp = new node;
 node* current;
 char ch;
 int count2 = 0;
 ad.userPromptStatement();

 while(1)
 {
    cin >> ch;
    switch(ch)
    {
        case '1':
            system("cls");
            cout << "\n\nINSERT RECORD";
                        cout << "\n\nInput FIRST NAME: ";
                        cin.ignore();
                        getline(cin,firstname,'\n');

                        cout << "\nRecord inserted!";
                    current = ad.AddNode(temp);
                ad.userPromptStatement();
        break;

        case '2':
            system("cls");
            cout << "\n\nDISPLAY ALL\n\n";
            ad.DisplayAll();
            _getch();
            ad.userPromptStatement();
        break;

A: A possible problem is here:
current -> next = new node;
current -> firstname = temp -> firstname;
current -> lastname = temp -> lastname;
        ////code here to add the other values////
current -> zipcode = temp -> zipcode;

In the above code you allocate a new node at current->next, but assign to the fields of current.

Another problem is that you don't actually initialize the fields in the node structure you use in the AddNode call.

A: If you desire to use a linked list, I recommend you not reinvent the wheel and instead use
std::list.  You can still salvage most of your node class when using std::list.
#include <list>
#include <string>

using namespace std;

struct node
{
    string firstname;
    string lastname;
    string phonenumber;
    string dayofbirth;
    string monthofbirth;
    string yearofbirth;
    string age;
    string streetname;
    string city;
    string state;
    string zipcode;
    char ch;
};

typedef std::list<node> NodeList;

class InfoBook
{
    NodeList nList;

    public:
        InfoBook();

        void userPromptStatement();
        void AddNode(node& theNode) { nList.push_back(theNode); }
        void DisplayAll();
};

void InfoBook::DisplayAll()
{
    NodeList::iterator it = nList.begin();
    while (it != nList.end())
    {
        node& curNode = *it;
        // now print out curNode in whatever way you see fit
        // ...
        ++it;  // go to nest node in the list
    }
}

Note how much shorter the code is, especially the AddNode() function.  The node class no longer needs to keep count of things, as the nList.size() will give you the number of nodes.
The sample above introduces you to the standard library containers (std::list) and iterators (the "it" in the DisplayAll function).  I didn't fill in the other InfoBook functions, as I'll leave it to you to do that, but hopefully you get the idea on how to finish up.


text:
Q: Implementing sequential callback execution I am trying to execute following array (avoid callbackHell) of functions(sync/async), in a sequential order, implementing function runCallbacksInSequence (I need to implement my own function to understand how callbacks work and avoid using Async.js).
I do not quite understand how callbacks work that is why I am doing this exercise. Here is what I have so far. The function runCallbacksInSequence works well but I am having hard time to implement callback (null, result) signature. At the moment it follows callback (result) signature.
If you have any ideas let me know what I am doing wrong and how I can fix it.
- no promises and async/await

function first(cb) {
  setTimeout(function() {
    console.log('first()');
    cb('one');
    // cb(null, 'one');
  }, 0);
}

function second(cb) {
  setTimeout(function() {
    console.log('second()');
    cb('two');
    // cb(null, 'two');
  }, 100);
}

function third(cb) {
  setTimeout(function() {
    console.log('third()');
    cb('three');
    // cb(null, 'three');
  }, 0);
}

function last(cb) {
  console.log('last()');
  cb('lastCall');
  // cb(null, 'lastCall');
}

function runCallbacksInSequence(fns, cb) {
  fns.reduce((r, f) => k => r(acc => f(x => k([...acc, x]))), k => k([]))(cb);
}

const fns = [first, second, third, last];

runCallbacksInSequence(fns, results => {
  console.log('-- DONE --');
  console.log(...results);
});

A: In your runCallbacksInSequence you first of all have to move the x to the second position, also for consistency the final callback should be called with its first argument being null:
 function runCallbacksInSequence(fns, cb) {
   //                                    v  v                                  vvvvvvvv
   fns.reduce((r, f) => k => r(acc => f((e, x) => k([...acc, x]))), k => k([]))(r => cb(null, r));
 }

If you want the first callback with an error (having the first argument set) to directly terminate the chain, you can extend your chain a bit:
 //                                              vvvvvv
 fns.reduce((r, f) => k => r(acc => f((e, x) => e ? cb(e) : k([...acc, x]))), k => k([]))(r => cb(null, r));

A: To answer I do not quite understand how callbacks work
A callback is a function that is to be executed after another function has finished executing. For example.
function run(cb){
  console.log("run")
  cb("okay it is running");
}

A simple function that logs stuff. How do you run it?
run()

But you want to receive the callback. To know that above cb() everything was done. You do this.
run((arg) => {
  console.log(arg) //logs "okay it is running"
});

What you actually got is a "call", "back" from the function you ran, while running it.


text:
Q: Excel file Import to Sql Server, Sql Server Table have indexes and Excel file have Names I want to import Excel File to SQL Server, but my problem is the Table which I created in SQL for excel file save indexes and Foreign Keys.
Like SQLTable have ID, StudentName, ClassID, SectionID, etc...but my Excel file have not Class ID it has Class name in it. Similarly Section Name instead of SectionID.
How I will import the file to database.
Thank you

A: You obviously need to map the names to IDs before you can load the Excel data into the table. I can think of three ways to do it:
a) Import the Excel data into a new table, and then write some SQL to join to the relevant tables to get the IDs, and then do the insert into the target table.
b) Query your database directly from Excel to get the IDs that you need, and then use the SQL import wizard to import the data into the target table.
c) Write an SSIS package to read the Excel data, query the database for the additional IDs, and insert into your target table.


text:
Q: Succesfully installed "psycopg2-binary" but got ImportError: No module named psycopg2 I was abled to install the psycopg2-binary using pip3 . So that I case use psycopg2 .
pip3 install psycopg2-binary
Output:
Defaulting to user installation because normal site-packages is not writeable
Collecting psycopg2-binary
  Downloading psycopg2_binary-2.9.3-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (3.0 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.0/3.0 MB 38.2 MB/s eta 0:00:00
Installing collected packages: psycopg2-binary
Successfully installed psycopg2-binary-2.9.3

But When I try to run python -c "import psycopg2; print(psycopg2.__version__)" to check if its successfully installed or not. I got this error.
  File "<string>", line 1, in <module>
ImportError: No module named psycopg2```

Any help ?
Thanks!


text:
Q: Why does sshfs cause these Emacs artifacts? After opening a file in emacs (over an ssh tunneled, sshfs mounted file system) I get symbolic links like this:
.#jobid.php -> ddh@localhost.localdomain.31678:1260471633

We have determined that these are emacs LOCK files.
The sshfs filessystem is mounted with follow_symlinks and transform_symlinks, but it appears to be refusing to return the link 'text' via readlink so emacs is not removing them.

A: In case you're looking for documentation, Emacs refers to these files as file locks.
Instead of using sshfs/FUSE, you can access remote files directly from Emacs:
C-x C-f /ssh:host.name:/path/to/file RET

Emacs doesn't create file locks when editing remote files in this manner-- search for "TRAMP" for more info about editing remote files. (Unfortunately, I guess Emacs can't tell that your FUSE mountpoint is backed by a remote filesystem or that creating file locks on it is problematic.)

A: Those symlinks are used by emacs to prevent multiple emacs instances from modifying the same file.  The symlink normally goes away when you save the file, but it sounds like fuse-sshfs is interfering with this process since the target of the symlink isn't a real file (it isn't meant to be, but sshfs expects it).
Unfortunately, I don't know of a way to disable this feature or force emacs to store these symlinks in a different directory (I use emacs infrequently and I didn't find anything in the manual), so you may have to just periodically delete them manually I'm afraid.

A: The follow_symlinks option forces symlinks on the remote system to appear as actual files. This is useful when the symlink refers to a target on the remote host outside the directory that is mounted via sshfs, but it breaks Emacs's assumptions because when Emacs creates a symlink, it expects that same path to look like a symlink later.
However, you should be able to make all symlinks on the remote host work correctly while still appearing as symlinks by using the transform_symlinks option (and not follow_symlinks) and always mounting the root of the remote system (instead of just your home directory or something). This should allow emacs to abuse symlinks as lockfiles while still making remote symlink targets accessible.

A: These symlinks are created by Emacs when a buffer is visiting a file, and they prevent two Emacs instances from editing the same file (as mentioned in other answers).  Emacs refers to this as "clash detection".
Unfortunately, the only way to prevent this behavior in GNU emacs is at compile time.  The source docs describe how to do this by changing a header.
This is because the lock-buffer and unlock-buffer functions are primitives, and are called by other primitives to create these symlinks.  In older versions of Emacs, they can be redefined or defaliased in elisp, but a primitive will not notice this change.


text:
Q: run serve -s build from .bat file I want to execute serve -s build from .bat file as admin, this is my .bat file:
@ECHO OFF
cd "C:\Users\user\Desktop\Brabender\build-20220517T114506Z-001"
serve -s build

It works if I manually run it as admin, but I need it to run from Windows Startup Folder everytime the system starts, any ideas how to do it as admin automatically?

A: Some minor changes to your batch file, adding /d to the cd command
@echo off
cd /d "C:\Users\user\Desktop\Brabender\build-20220517T114506Z-001"
serve -s build

Assuming we call the file something like serve-build-script.bat, run from cmd.exe
schtasks /create /tn "Serve-Build" /tr "c:\<Path-to-Batch-file>\batchfile-name.bat" /sc onstart /ru "user" /rp "password" /np /f

The correct version updated as per confirmation from the chat.


text:
Q: Execute the multiple SQL Select, Update commands from SQL file using invoke-DbaQuery I am exploring powershell to run the following SQL script stored in my machine with name "TestSQLScript.sql"
USE TestDB
GO
SELECT TOP (1000) [DocId]
      ,[DocumentInfo]
  FROM [TestDB].[dbo].[Docs]

INSERT INTO WorkDocs
(       [DocId]
      ,[DocumentInfo])
SELECT [DocId]
      ,[DocumentInfo]
  FROM [TestDB].[dbo].[Docs]

SELECT TOP (1000) [DocId]
      ,[DocumentInfo]
  FROM [TestDB].[dbo].[WorkDocs]

When I use the following command it executed well.
invoke-sqlcmd -inputfile "D:\TestSQLScript.sql" -serverinstance "MYPC\MSSQLSERVER2019" -Username "sa" -Password "***" -database "master"

When I am running the following it through error while accessing table WorkDocs.
invoke-DbaQuery -SQLInstance "MYPC\MSSQLSERVER2019" -sqlcredential $Cred -File "D:\TestSQLScript.sql" -database "master"

In the initial finding it is noticed that tables referenced as [TestDB].[dbo].[WorkDocs] are accessible, and table referenced without [TestDB].[dbo] is not accessible at Insert statement, while I have already used the database reference on top in the SQL file "TestSQLScript.sql"
USE TestDB
GO

I can not reference all the tables with [TestDB].[dbo] as I have hundreds of script and there are multiple database references in each SQL script. Can you suggest how can I resolve this?
In addition to this How can I get the result count for each SQL query in the file. I have Multiple Select, Insert, Update and truncate SQL command in one SQL file and I want to log each execution result. Please refer to below for more.

*

*For Select Statements - 1000 Records fetched

*For Insert Statements - 100 rows inserted into 'Table Name'

*For Update Statements - 50 rows affected in 'Table Name'

*For Truncate Statements - 'Table Name' has been truncated.


text:
Q: how to return rejected/failure promise to through jasmine spy to an angular controller in a unit test I am using jasmine for testing my angular controllers.
I am catching errors and success in the .then(successCallback, errorCallback)
Although it is working fine on the bases of live functionality but am confused how to write a spy for returning an error as it is always caught in the successCallback()
Following is the controller :-
angular.module('myApp')
.controller('LoginCtrl', function ($scope, $location, loginService, SessionService) {
    $scope.errorMessage = '';

    $scope.login = function () {

      var credentials = {
          email: this.email,
          password: this.password
      };

     SessionService.resetSession();
     var request = loginService.login(credentials);

     request.then(function(promise){ //successfull callback
        if (promise['status'] === 200){
             //console.log('login');
            $location.path('/afterloginpath');
        }
      },
     function(errors){  //fail call back
      //  console.log(errors);
        $location.path('/login');
     });
    };
});

My test case :-
'use strict';

describe('Controller: LoginCtrl', function () {

  // load the controller's module
  beforeEach(module('myApp'));

  var LoginCtrl, scope, location, login, loginReturn, session;
  var credentials = {'email': 'email@email.com', 'password': 'admin123'};

  // Initialize the controller and a mock scope
 beforeEach(inject(function ($controller, $rootScope, $location, _loginService_, _SessionService_) {

    scope = $rootScope.$new();
    LoginCtrl = $controller('LoginCtrl', {
      $scope: scope
    });

    location = $location;
    login = _loginService_;
    session = _SessionService_;
    scope.errorMessage = '';
    spyOn(login, "login").andCallFake(
      function(){
        return {
          then: function(response){
            response(loginReturn);
          }
        }
      }
    );

    spyOn(session, "setName").andCallFake(function(){
      return true;
    });
  }));

  it('should go to login when login fail', function () {
    loginReturn = function(){
      return{
        successfullyCallback: {throwError:true},
        failCallback: {status: 400, 'data' : {'errors' : [{"type":"invalid_data","target":"email,password"}]}}
      }
    };

    var wrong_creds = {email: 'wrong@email.com', password: 'wrong_password'};
    scope.email = wrong_creds.email;
    scope.password = wrong_creds.password;

scope.login();

    expect(location.path()).toBe("/login");
    expect(scope.errorMessage).toBe('username or password combination is invalid');
  });

});

A: I find it easier to use actual promises for mocked services as it removes a lot of nested functions and is a lot easier to read.
Relevant snippets ($q needs to be injected in beforeEach):
deferred = $q.defer();
spyOn(login, 'login').andReturn(deferred.promise);

...

deferred.reject({ ... });

After resolving or rejecting the promise you need to call scope.$digest() so angular can process it.


text:
Q: Delegate method of push notification is not hitting after few hours I am sending silent push notification for my ipad for every hour. But after few hours the delegate method is not hitting(I have put a local notification inside delegate method).I am using this
application:handleActionWithIdentifier:forLocalNotification:completionHandler: delegate method to handle silent push notification. When i reset ipad under settings and try to send push notification, the delegate method will hit and work as i expected. I am not understanding this behaviour. I have also put sound to my notification,which plays when notification reaches device.But delegate inside my app is not hitting.My delegate code is as below.
    - (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    //some database operations

    completionHandler(UIBackgroundFetchResultNewData);
}

A: 1.APNS is based on Apple Servers, and Apple doesn't give any guarantee on successful message delivery.
2.If the app is open (i.e. the user is using the app) while the notification arrives, iOS doesnt show a notification message, you need to handle it.
3.Notification shows up only when the app is backgrounded or killed.
4.Also implement feedback service on your server side; will help you get rid of old unwanted tokens(users who deleted the app or disabled notifications thru settings).
5..Dont send too many notifications to a device within a short span of time, coz APNS caches only 1 message/device (if the device is offline). So it can deliver the message when the device comes online. Am not sure how long the message is cached though.

Some Notifications Received, but Not All
If you are sending multiple notifications to the same device or computer within a short period of time, the push service will send only the last one.
Here's why. The device or computer acknowledges receipt of each notification. Until the push service receives that acknowledgment, it can only assume that the device or computer has gone off-line for some reason and stores the notification in the quality of service (QoS) queue for future redelivery. The round-trip network latency here is of course a major factor.
As described in the Local and Push Notification Programming Guide, the QoS queue holds a single notification per app per device or computer. If the service receives another notification before the one in the queue is sent, the new notification overwrites the previous one.
All of this points out that the intent is that a notification indicates to an app that something of interest has changed on the provider, and the app should check in with the provider to get the details. Notifications should not contain data which isn't also available elsewhere, and they should also not be stateful.
Any push notification that isn't delivered immediately was queued for future redelivery because your device was not connected to the service. "Immediately" of course needs to take latency for your connection into account. Outlying cases would be beyond 60 seconds as APNs will time out at that point.
APNS Technical Note TN2265