text:
Q: PowerShell Hide-WUUpdate to Hide specific KB update Trying to hide a specific KB update with Hide-WUUpdate Here is what I am trying
Hide-WUUpdate –KBArticleID "KB4034664" -ComputerName PCNAME –Confirm:$false

I get the following output
WARNING: You haven't privileges to make this. Try start an eleated Windows PowerShell console

I have tried with an "Elevated Powershell" Any ideas?
After running this as suggested
Hide-WUUpdate –KBArticleID "KB4034664" -ComputerName PCNAME –Confirm:$false -Debuger
I got the following output.
DEBUG: STAGE 0: Prepare environment
DEBUG: Check if ComputerName in set
DEBUG: STAGE 1: Get updates list
DEBUG: Create Microsoft.Update.Session object for PCNAME
DEBUG: Create Microsoft.Update.Session.Searcher object for PCNAME
DEBUG: Set source of updates to default (for PCNAME) Windows Update
DEBUG: Set pre search criteria: IsInstalled = 0
DEBUG: Search criteria is: IsInstalled = 0
DEBUG: Set post search criteria: Dell Inc. - Bus Controllers and Ports, Display - Dell 1907FP(Analog)
DEBUG: Set post search criteria: KBArticleIDs = 'KB4034664'
DEBUG: UpdateAccess: false
DEBUG: Set post search criteria: LSI - Storage - Dell SAS 6/iR Integrated Workstation Controller
DEBUG: Set post search criteria: KBArticleIDs = 'KB4034664'
DEBUG: UpdateAccess: false
DEBUG: Set post search criteria: Update for Windows 7 for x64-based Systems (KB2574819)
DEBUG: Set post search criteria: KBArticleIDs = 'KB4034664'
DEBUG: UpdateAccess: false
DEBUG: Set post search criteria: Update for Windows 7 for x64-based Systems (KB2592687)
DEBUG: Set post search criteria: KBArticleIDs = 'KB4034664'
DEBUG: UpdateAccess: false
DEBUG: Set post search criteria: Update for Windows 7 for x64-based Systems (KB2830477)
DEBUG: Set post search criteria: KBArticleIDs = 'KB4034664'
DEBUG: UpdateAccess: false
DEBUG: Set post search criteria: Update for Windows 7 for x64-based Systems (KB3080079)
DEBUG: Set post search criteria: KBArticleIDs = 'KB4034664'
DEBUG: UpdateAccess: false
DEBUG: Set post search criteria: Update for Windows 7 for x64-based Systems (KB3102429)
DEBUG: Set post search criteria: KBArticleIDs = 'KB4034664'
DEBUG: UpdateAccess: false
DEBUG: Set post search criteria: 2017-08 Security Monthly Quality Rollup for Windows 7 for x64-based System
s (KB4034664)
DEBUG: Set post search criteria: KBArticleIDs = 'KB4034664'
DEBUG: Convert size
DEBUG: Convert KBArticleIDs
WARNING: You haven't privileges to make this. Try start an eleated Windows PowerShell console.
DEBUG: Set post search criteria: August, 2017 Preview of Quality Rollup for .NET Framework 3.5.1, 4.5.2, 4.
6, 4.6.1, 4.6.2, 4.7 on Windows 7 and Server 2008 R2 for x64 (KB4035036)
DEBUG: Set post search criteria: KBArticleIDs = 'KB4034664'
DEBUG: UpdateAccess: false
DEBUG: Set post search criteria: 2017-08 Preview of Monthly Quality Rollup for Windows 7 for x64-based Syst
ems (KB4034670)
DEBUG: Set post search criteria: KBArticleIDs = 'KB4034664'
DEBUG: UpdateAccess: false'

Powershell remote IS enabled on the remote computer.

A: Assuming this is the script you're using, it looks like the error message is from line 550.  That warning message is from an error trap that's concealing the actual error.  I'd recommend changing the code to something like this:
If ($pscmdlet.ShouldProcess($Computer, "$StatusName $($Update.Title)?")) {
    Try {
        $Update.IsHidden = $HideStatus
    }
    Catch {
        Write-Warning "You haven't privileges to make this. Try start an eleated Windows PowerShell console."
        throw ($_)
    }

} #$pscmdlet.ShouldProcess($Computer,"Hide $($Update.Title)?")

Now you should be able to see the actual error message instead of the friendly, non-informative warning the script author decided you should get.

A: After analyzing all the information, I believe you do not have the required permissions/access to perform this operation remotely.
Your script is a 3rd party script. The debug info is not specially informative. All that can be said is that the script fails on setting the hidden property on the update.
The best shot you have is to enable Powershell Remoting to make sure you have the remote access you need to run this. Nevertheless there is a chance that it still may not work due to some Microsoft security restrictions. In that case I'd advise you to install and configure Microsoft Windows Server Update Services which will enable you to perform this task.


text:
Q: How to set Google Drive access timeout on Android Let's list files from Google Drive:
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
    context, DriveScopes.DRIVE);
Drive service = new Drive.Builder(AndroidHttp.newCompatibleTransport(),
    new GsonFactory(), credential).build();
service.files().list().execute();

However, execute() takes almost forever to realize if for example there is no network connection available.
It turns out from the source of GoogleAccountCredential that it uses ExponentialBackOffPolicy, which has a 15 minutes maximum elapsed time limit by default.
Question 1: Is there a way to override this behavior and set the timeout limit to a lower value?
Question 2: service.files().list().execute() is running in an AsyncTask. What is the correct way to cancel it on user request, if she doesn't want to wait for that 15 mins timeout?

A: Thanks for the feedback!
Doesn't look like there is any way to customize the exponential backoff policy on GoogleAccountCredential.  I filed a feature request here:
https://code.google.com/p/google-api-java-client/issues/detail?id=734
It doesn't look like there's a good way to cancel either.  Feature request filed here:
https://code.google.com/p/google-api-java-client/issues/detail?id=735
NOTE: I'm an owner on the google-api-java-client project

redpajama_set_name: RedPajamaStackExchange


text:
Q: PySpark Aggregate and When Condition I have a question on PySpark.
df = (sc.parallelize([
    {"Day":1,"sensitive_id":"1234", "num":3},
    {"Day":1,"sensitive_id":"1234", "num":3},
    {"Day":2,"sensitive_id":"1234", "num":3},
    {"Day":3,"sensitive_id":"2345", "num":2},
    {"Day":3,"sensitive_id":"2345", "num":2},
    {"Day":3,"sensitive_id":"6789", "num":4},
    {"Day":4,"sensitive_id":"6789", "num":4},
    {"Day":4,"sensitive_id":"6789", "num":4},
    {"Day":4,"sensitive_id":"6789", "num":4}
 ]).toDF()
      )

I want to have a new column to have the corresponding "sensitive_id" as the max value of "num" column.
This is the result I have so far.
from pyspark.sql import functions as F
from pyspark.sql.window import Window
(
    df
    .withColumn(
        'top_sensitive_id',
        F.when
        (
            F.col('num') == F.max(F.col('num')).over(Window.partitionBy(F.col('Day'))),
            F.col('sensitive_id')
        )
    )
    .withColumn
    (
        'top',
        F.max(F.col('top_sensitive_id')).over(Window.partitionBy(F.col('Day')))
    )

    .show()
)

But I am sure there should be a more elegant and efficient way to do this.
Can someone provide a better way of doing this?

A: Your code is almost close to best approach, But I still tried to add few things -
1.Calculate 'top' once and use same for comparison.
2.Use separate column definition, it will help in better readability
   and maintainability
 from pyspark.sql.window import Window

windowSpec = Window.partitionBy('Day')
top = max('sensitive_id').over(windowSpec).alias('top')

df.select('Day','Num','sensitive_id',top).withColumn('top_sensitive_id', expr("CASE WHEN sensitive_id = top THEN top END")).show()


text:
Q: Automatically run a script on an uploaded FTP file Is there a way to run a script over a file that has been uploaded on an FTP server.
I am running ProFTP on the server and would like to process the uploaded files immediately after they are uploaded. The ways I have currently thought of are

*

*Cron Job to find new files in the FTP and process them every minute.

*Write a daemon to monitor the file upload log and use that information to process the file.

Is there a better way, or a directive I can set on the server to run a script on all file uploads?
Update: Linux OS

A: You don't state your OS, but if you're on a Linux box, you can hook 'inotify', which will is a kernel subsystem that fires when filesystem events happen.  This should give you much better response time than cron, which only runs on one minute granularity.
The following link will get you started, but there are Perl, Python, and a bunch of other bindings available.
http://inotify-tools.sourceforge.net

A: If changing your ftp daemon is not a problem then pure-ftpd has this functionnality.
Hope this helps.

A: The two general approaches to this would be:

*

*Use functionality built-in to ProFTP (if it exists) or another FTP server product

*Have some operating system process or cron job (as you mentioned in both your #s 1 and 2) watch for the file, or better than polling is to watch for file system events and respond accordingly.  See https://stackoverflow.com/questions/324258/is-there-an-equivalent-to-the-net-filesystemwatcher-in-the-linux-world.

The easiest approach is to use functionality built in to the FTP server if it exists.  If not, you can likely download file watcher code and or an already-written shell script which you can cron.


text:
Q: SharePoint Online - Using [Me] filter for Multi line text column doesn't work I am on SP Online environment. I have a list with multiple columns. One of the column multi line text column (Approvers) has multiple users of below format.
Approvers: User1; User2; User3; User4; User5..... using UserProfile Name.

I am trying to create Approver's view. If a user that belongs to Approver's column accesses this view, he should be able to see that item. I added filter to achieve this, Approver contains [Me], which doesn't seem to work.
After digging deep, i learnt that [Me] can only be applied to a User or group column(People Picker).
Any other ideas to achieve this?
Thanks

A:
One of the column multi line text

Change this to a People/Group column that allows multi-select ("Allow multiple selections") and then filter for [Me].  [Me] must be a real user, and multi-line text columns are just text, not users.
If you want a short list of users to select from (not all users), create a SharePoint group ("Choose from") with just those users and limit the People/Group column to that group.

You could also create People columns, one for each possible approver, and use a workflow to split the names across these columns. You can hide these columns in the view and still use them to filter. Create a series of "OR" filters, one for each column, that each filters on [Me].

A: [Me] only works for People column. The easiest way for your requirement is using Multi-people & group column to store the approvers instead of multi-line text column, then create a view and use [Me] to filter items.


text:
Q: Read rows in batches from mysql in constant time I am reading rows from a mysql table in batches of 100
select * from Foo limit 1000, 100

This works. but the time taken by the query increases drastically as the offset is increased. I think the reason is that the database still reads the entire result before returning the last 100.
Is there a way I can read rows in batches and in constant time between batches?


text:
Q: JOGL vertices limited between 0f and 1f I'm making a basic 3DS model viewer using JOGL, and I found that if I don't scale the vertices it won't display properly.  Say if the max vertex value was 40, I would scale all others by this to force the vertices to be between 0 and 1, then draw it.  Is there a way to set the perspective so I don't have to scale values? If it helps, the GLCanvas size I'm using is 600x600.

A:
Is there a way to set the perspective so I don't have to scale values? I

Of course. In old fixed function pipeline OpenGL you'd have the projection and modelview matrices to apply transformations on. Today, in modern shader based OpenGL you can implement whatever transformation you like in the vertex shader.
I suggest you read some OpenGL tutorials to get a firm grip on the subject, rather than wander in the foggy dark. I suggest http://arcsynthesis.org/gltut


text:
Q: I have a crazy virus I have a message pop up when I log in and try to open a folder with my go pro footage. It pops up a window with the title being "you are about to be logged off" and the window text "a virus was detected, your PC will be destroyed in a few seconds" then it restarts. I have tried logging into safe mode and running malewarebytes with no success. Any suggestions??

A: Your problem sounds very much like a joke by a friend(?). The simplest way to check if the Go Pro folder is a real folder is to right-click the icon and select "Properties" at the end of the context menu. This should tell you a lot.


text:
Q: Use the DGPS of iPhone and Android I'm working on a robot which need to know its exact position (with an error of +/- 5cm) in relation to a given point of coordinates (0, 0). So my question is :

Is it possible to get this kind of precision using differential GPS ?

The idea would be to place a GPS at the position (0, 0) and a GPS on the robot to compute the difference of coordinates of the 2 GPS and get the relative position of the robot.
Thanks for your answers

A: It is possible with DGPS, but bot in an mobile phone.
Precision Farming use GPS with cm accuracy.
With a consumer GPS if you would be able to read out the Satellite RAW data, you could do a GPS Post processing, that way you could reach <1m accuracy.
for cm accuracy you need 2 Phase Gps receiver (conusmer ois 1 -phase),
and additional RTK, Then you have cm accuracy.
Read more by searching for topic RTK, Rinex, GPS Post processing.
(But it is not possible for current mobile phones, using GPS)
And robotoers often want to work indoors, where GPS doesn not work, too.

A: No, GPS is way too inaccurate for that. Best guess would be that you can use the accelerometer to calculate a relative distance on movement.

A: Might be placing 3 wifi routers in the field and compute by using their relatively signal strength would give a better appoximation on the robot's current location?


text:
Q: Missing component in Angular when it has service mentioned in constructor, non used inside the component itself. JHipster app Here what we have in browser's debug:
const Mp = {
        pageTitle: "ученику"
    }
      , Ap = {
        path: "to-student",
        component: Fp,
        data: Mp,
        canActivate: [m.b]
    };
    class Dp {
        constructor() {}
        ngOnInit() {}
    }

It is interesting, that with npm start it is compiled well and fails in runtime only when it is built with npm plugin of maven on production side (heroku).
At the module we have:
import {
  BlogDocumentsComponent,
  BlogFaqComponent,
  BlogEntriesComponent,
  ShopComponent,
  ShopSuccessComponent,
  ShopFailureComponent,
  SyllablesComponent,
  RedirectComponent,
  //  UsefulStuffComponent actually not there
} from './';

import 'd3';
import 'nvd3';
import { NvD3Module } from 'ng2-nvd3';
import { UsefulStuffComponent } from './useful-stuff/useful-stuff.component';

so UsefulStuffComponent is not in common import, but its path is correct!
And it is not mentioned in the corresponding index.ts of the module (we don't need it ever, if the full path is set, right?)
So the problem can be fixed by explicitly making UsefulStuffComponent be exported in index.ts and being exported with other component the same way:
import {
  BlogDocumentsComponent,
  BlogFaqComponent,
  BlogEntriesComponent,
  ShopComponent,
  ShopSuccessComponent,
  ShopFailureComponent,
  SyllablesComponent,
  RedirectComponent,
  UsefulStuffComponent actually not there
} from './';

import 'd3';
import 'nvd3';
import { NvD3Module } from 'ng2-nvd3';
//  import { UsefulStuffComponent } from './useful-stuff/useful-stuff.component'; actually no import here

So, why I'm getting this kind of production runtime failure, but never get it on npm start locally?
UPD:
So, after the advice of @Gaël Marziou I have tried to localize the change that made the component to be lost at prod state. I have reveal that this component still causes the prod error:
import { Component, OnInit } from '@angular/core';
import { filter, map } from 'rxjs/operators';
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { PaymentService } from 'app/businesslogic';
import { JhiAlertService } from 'ng-jhipster';
import { IAccessSubscription } from 'app/shared/model/access-subscription.model';
import { AccessSubscriptionService } from 'app/entities/access-subscription';

@Component({
  templateUrl: './to-student.component.html',
  styleUrls: ['./to-student.component.scss']
})
export class ToStudentComponent implements OnInit {
  accessSubscriptions: IAccessSubscription[] = [];
  accessSubscriptionsIds: number[] = [];

  constructor(
    protected jhiAlertService: JhiAlertService,
    protected accessSubscriptionsService: AccessSubscriptionService,
    protected paymentService: PaymentService
  ) {}

  ngOnInit() {
    this.loadAll();
  }

  loadAll() {
    this.accessSubscriptionsService
      .queryAllMine()
      .pipe(
        filter((mayBeOk: HttpResponse<IAccessSubscription[]>) => mayBeOk.ok),
        map((response: HttpResponse<IAccessSubscription[]>) => response.body)
      )
      .subscribe(
        (res: IAccessSubscription[]) => {
          this.accessSubscriptions = res;
          this.accessSubscriptions.map((item: IAccessSubscription) => {
            this.accessSubscriptionsIds.push(item.id);
          });
        },
        (res: HttpErrorResponse) => this.onError(res.message)
      );
  }

  protected onError(errorMessage: string) {
    this.jhiAlertService.error(errorMessage, null, null);
  }
}

while this one already works well:
import { Component, OnInit } from '@angular/core';
import { filter, map } from 'rxjs/operators';
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { PaymentService } from 'app/businesslogic';
import { JhiAlertService } from 'ng-jhipster';
import { IAccessSubscription } from 'app/shared/model/access-subscription.model';
import { AccessSubscriptionService } from 'app/entities/access-subscription';

@Component({
  templateUrl: './to-student.component.html',
  styleUrls: ['./to-student.component.scss']
})
export class ToStudentComponent implements OnInit {
  accessSubscriptions: IAccessSubscription[] = [];
  accessSubscriptionsIds: number[] = [];

  constructor(protected jhiAlertService: JhiAlertService, protected accessSubscriptionsService: AccessSubscriptionService) {}

  ngOnInit() {
    this.loadAll();
  }

  loadAll() {
    this.accessSubscriptionsService
      .queryAllMine()
      .pipe(
        filter((mayBeOk: HttpResponse<IAccessSubscription[]>) => mayBeOk.ok),
        map((response: HttpResponse<IAccessSubscription[]>) => response.body)
      )
      .subscribe(
        (res: IAccessSubscription[]) => {
          this.accessSubscriptions = res;
          this.accessSubscriptions.map((item: IAccessSubscription) => {
            this.accessSubscriptionsIds.push(item.id);
          });
        },
        (res: HttpErrorResponse) => this.onError(res.message)
      );
  }

  protected onError(errorMessage: string) {
    this.jhiAlertService.error(errorMessage, null, null);
  }
}

So, non-working just contains an import of some service in the constructor that isn't ever used:
   protected paymentService: PaymentService

A: Some Angular errors can really be difficult to debug especially when they don't appear in dev builds.
Each time I faced such situation I actually rolled back my changes until I found the culprit commit.
If you're doing it after lot of changes, you can use a script with git bisect to identify the faulty lines assuming your commits are small of course.
Ideally, to avoid this "archaeological" search, you should put in place automatic continuous integration from beginning of your project, this way you are sure that deeper checkings from production builds will catch errors earlier.


text:
Q: yahoo finance stock data / class PagesController < ApplicationController MET_AKEY I am sorry if my question is not specific enough, however, I hope somebody will answer. I want to display stock market data with rails.
I have the following code as an example:
class PagesController < ApplicationController
def index
require 'open-uri'
require 'nokogiri'
@capabilities = Capability.all

url = "http://datapoint.metoffice.gov.uk/public/data/val/wxfcs/all/xml/sitelist?key=#{MET_AKEY}"

@docxml = Nokogiri::XML(open(url))

end
def show
@capability = Capability.find(params[:id])
gon.latitude = @capability.latitude
gon.longitude = @capability.longtitude

end
end
Now I want to change the url. My purpose is to get access to the yahoo finance stock data.
1) Which url I have to use? (I really tried to find it)
2) I guess I have to change my the gem file. Which other files I have to change in my application?

A: You should use their API instead of scraping page, check that link and try using it, if you will have aby trouble post specific error.


text:
Q: Can I build my meshes with a vector (OpenGL) I am trying to build my mesh by passing in the informations with a vector. I thought it would must be the same. But it is not working.
The actual information in this vector must be correct so I am actual pretty sure the problem is the building the actual bufferData.
Does somebody has a hint what is going wrong there? Or how I maybe do it in a better way?
void MeshBuilder::buildMesh(std::vector<Vertex> vert, std::vector<int> index){
Vertex vertex;
//Vertex Array Object: Binds Buffer Obj
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);

std::vector<GLfloat> verticies;
for (int i = 0; i < vert.size(); i++) {
    verticies.push_back(vert[i].getPosition().x);
    verticies.push_back(vert[i].getPosition().y);
    verticies.push_back(vert[i].getPosition().z);
    verticies.push_back(vert[i].getNormals().x);
    verticies.push_back(vert[i].getNormals().y);
    verticies.push_back(vert[i].getNormals().z);
    verticies.push_back(vert[i].getTexture().x);
    verticies.push_back(vert[i].getTexture().y);
}

std::vector<int> indicies;
for (int i = 0 ; i < index.size(); i++) {
    indicies.push_back(i);
}

//Vertex Buffer Object
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, verticies.size()*sizeof(GLfloat), &verticies, GL_STATIC_DRAW);
//Attributes
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, vertex.SIZE*4, (GLvoid*)0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, vertex.SIZE*4, (GLvoid*)12);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, vertex.SIZE*4, (GLvoid*)24);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);

glBindVertexArray(0);

//Element Buffer Object
glGenBuffers(1, &ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indicies.size()*sizeof(int), &indicies, GL_STATIC_DRAW);

std::cout << "Mesh buildet..." << std::endl;
}

A: In your method declaration & definition try changing it from void MeshBuilder::buildMesh(std::vector<Vertex> vert, std::vector<int> index); to void MeshBuilder::buildMesh(std::vector<Vertex>& vert, std::vector<int>& index) to pass by reference instead of making a copy; this will help speed things up.
The only other thing I can see that may cause a problem is that you are stopping your vertex array before you define your indices. Try moving your glBindVertexArray(0); that is before your //Element Buffer Object code to be called after these three lines of code. See if this makes a difference.
Also make sure that you do the following before the end of this function or after this function is called:

*

*Disable Attribute Pointers

*The Next Two Below Must Be After Vertex Array Buffer Is Unbound:

*

*Stop Buffer Index - glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );

*Stop Buffer - glBindBuffer( GL_ARRAY_BUFFER, 0 );


text:
Q: iOS Tableview Controller Keyboard offset (example project inside) I am currently implementing a chat into my app. It is a very simple tableview showing rows which are the messages. I have a big problem figuring out how to react to different keyboards.
Currently i calculate the height of the keyboard when the keyboard is shown and add it as a offset. I posted questions regarding this topic before, people tend to tell me i should work with the insets, but i can not make it work.
I want the content of the tableview to move like in iMessage or Whatsapp, where the messages move up with the keyboard and go back. It does work for the standard keyboard but once you switch to the emoji one it gets messed up.
I need help to find a solution or maybe show me the correct way to handle keyboards in tableviews.
To safe everyones time i created a dummy project which holds my current status of the chat. I hope someone has achieved this before and could help me out, since i am desperate to find a solution now.
https://www.dropbox.com/s/bldknydjfrwknr9/chatOffset.zip?dl=0
Maybe the way with the offsets is wrong and someone can show me a better solution?

A: You should implement this code. Note that this is in Swift 2.3, but I have implemented this code on Swift 3 and it worked I just don't have a copy of the Swift 3 code right now.
// Tag your bottom Layout Constraint (probably the one at the bottom of your tableView which connects to the self.view or the one connected to your textField to the self.view)
@IBOutlet var bottomLayoutConstraint: NSLayoutConstraint!

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    // this code snippet will observe the showing of keyboard
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.keyboardWillShowNotification(_:)), name: UIKeyboardWillShowNotification, object: nil)

    // this code snippet will observe the hiding of keyboard
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.keyboardWillHideNotification(_:)), name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWillShowNotification(notification: NSNotification) {
    updateBottomLayoutConstraintWithNotification(notification)
}

func keyboardWillHideNotification(notification: NSNotification) {
    updateBottomLayoutConstraintWithNotification(notification)
}

func updateBottomLayoutConstraintWithNotification(notification: NSNotification) {
    let userInfo = notification.userInfo!

    // get data from the userInfo
    let animationDuration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
    let keyboardEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
    let convertedKeyboardEndFrame = view.convertRect(keyboardEndFrame, fromView: view.window)
    let rawAnimationCurve = (notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).unsignedIntValue << 16
    let animationCurve = UIViewAnimationOptions(rawValue: UInt(rawAnimationCurve))

    bottomLayoutConstraint.constant = CGRectGetMaxY(view.bounds) - CGRectGetMinY(convertedKeyboardEndFrame)

    // animate the changes
    UIView.animateWithDuration(animationDuration, delay: 0.0, options: [.BeginFromCurrentState, animationCurve], animations: {
        self.view.layoutIfNeeded()
        }, completion: nil)
}

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)

    // remove the observers so the code won't be called all the time
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}

A: Thanks to Zonily Jame
Here is my conversion of his code to Swift 3.2 in Xcode 9
   @IBOutlet weak var bottomLayoutConstraint: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShowNotification(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHideNotification(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        // remove the observers so the code won't be called all the time
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    func keyboardWillShowNotification(notification: NSNotification) {
        updateBottomLayoutConstraintWithNotification(notification:notification)
    }

    func keyboardWillHideNotification(notification: NSNotification) {
        updateBottomLayoutConstraintWithNotification(notification:notification)
    }

    func updateBottomLayoutConstraintWithNotification(notification: NSNotification) {
        let userInfo = notification.userInfo!

        // get data from the userInfo
        let animationDuration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let keyboardEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let convertedKeyboardEndFrame = view.convert(keyboardEndFrame, from: view.window)
        let rawAnimationCurve = (notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).uint32Value << 16
        let animationCurve = UIViewAnimationOptions(rawValue: UInt(rawAnimationCurve))

        bottomLayoutConstraint.constant = (view.bounds).maxY - (convertedKeyboardEndFrame).minY

        // animate the changes
        UIView.animate(withDuration: animationDuration, delay: 0.0, options: [.beginFromCurrentState, animationCurve], animations: {
            self.view.layoutIfNeeded()
        }, completion: nil)
    }

A: I was experiencing one issue with Zonily Jame's and iCyberPaul's answer. On keyboard dismissal, my table view (embedded in a stack view with a bottom constraint to the safe area bottom) was extending behind the tab bar. This modified version simply sets the bottom constraint constant to 0 on will hide. This version also provides a drop-in handler.
Usage:

*

*Declare adoption of HandlesKeyboard protocol in a UIViewController subclass, e.g., extension MyViewController: HandlesKeyboard { }

*Create bottomConstraintForKeyboardHandling @IBOutlet for bottom-most view/container.

*Call startHandlingKeyboardChanges() in viewDidLoad or viewWillAppear.

*Implement stopHandlingKeyboardChanges() to remove self as an observer and call it in deinit or viewWillDisappear.

View/download GitHub gist
import UIKit

protocol HandlesKeyboard where Self: UIViewController {

    var bottomConstraintForKeyboardHandling: NSLayoutConstraint! { get }
    func startHandlingKeyboardChanges()
    func stopHandlingKeyboardChanges()
}

extension HandlesKeyboard {

    /// Registers caller to start handling keyboard will show and will hide notifications
    /// - Warning: Caller *must* implement `stopHandlingKeyboardChanges()` to unregister, e.g., in `deinit`
    /// ```
    /// func stopHandlingKeyboardChanges() {
    ///     NotificationCenter.default.removeObserver(self)
    /// }
    ///
    /// deinit {
    ///     stopHandlingKeyboardChanges()
    /// }
    /// ```
    func startHandlingKeyboardChanges() {
        NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: nil) { [weak self] in
            self?.updateBottomConstraint(notification: $0)
        }

        NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: nil) { [weak self] in
            self?.updateBottomConstraint(notification: $0)
        }
    }

    // Intentionally not implemented to ensure caller unregisters
//    func stopHandlingKeyboardChanges() {
//        NotificationCenter.default.removeObserver(self)
//    }

    func updateBottomConstraint(notification: Notification) {
        guard let userInfo = notification.userInfo,
            let animationDuration = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue,
            let keyboardEndFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
            let rawAnimationCurve = (userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber)?.uint32Value
            else { return }

        if notification.name == UIResponder.keyboardWillHideNotification {
            bottomConstraintForKeyboardHandling.constant = 0.0
        } else {
            bottomConstraintForKeyboardHandling.constant = view.bounds.maxY - view.convert(keyboardEndFrame, to: view.window).minY
        }

        let animationCurve = UIView.AnimationOptions(rawValue: UInt(rawAnimationCurve << 16))

        UIView.animate(withDuration: animationDuration, delay: 0.0, options: [.beginFromCurrentState, animationCurve], animations: { [weak self] in
            self?.view.layoutIfNeeded()
            }, completion: nil)
    }
}


text:
Q: Driving a Sainsmart Relay using Raspberry Pi I am actually a software engineer and not really familiar with wiring. I've been playing around with a Raspberry Pi Model B, and am looking to hook up a 2 PRONG Extension Cable to a Sainsmart 8 Channel Solid State Relay.
I am driving the GPIO pins from RPIO (Python). What I want to do is hook up a basic night light as the first channel output from the SSR and control it from GPIO pin 17. The problem is, I can't even get this to work. I am able to get the LED to light up pretty easily, but there seems to be no output. I've tried driving the relay on a HIGH and LOW signal, but no dice.
My wiring diagram is shown below... Apologies for it being very rudimentary... Any ideas what may be wrong? Is my relay bad?
Also note, I've several mechanical relays too and they all seem to do the same thing.
Also, I've been told that the GROUND side of a 2 PRONG cable is the side where the insulation has labeling. I'm assuming the GROUND part of the 2 prong cable is plugged into the top part of the output channel of the relay and VCC on the bottom. Can someone confirm with me?
I've also tried this with an Arduino, and it doesn't seem to work either. Sorry for the convoluted post, but this has been driving me nuts for the past couple of weeks!
EDIT: The LED on the board does turn on, but I haven't had luck powering something separate off from the port. And yes, I have tried powering it from a separate 5V supply.

A: This is very old now but I keep getting the link in search results so I thought I would comment in case it helps anyone else reading this as I am.
In the original diagram it looks like the questioner is thinking that the 2 pins of the relay that his wire is attached to provide current and ground to run a light.  They Don't ...
Its just a switch so you hook the hot wire of a light to one side and hook that same wire to the other side of the relay.  When the relay is powered it switches the switch on and the current can flow thru the relay just as if it were a light switch.
Terrible drawing coming :)
Ground-plug-on-cord------is optional ------------Ground of light/ appliance
Common- plug-on cord ----------------------------Common (usually white) light
Hot wire -----one side of relay---- other end of hot wire to other side of relay
So in my case I did this:
Took my light and carefully cut just the black wire and left the green and white wires connected as they were.  Then I hooked one end of the black wire to one of the terminals on the relay and the other end of the black wire to the other terminal of the same relay.  Then I plugged the power cord into an outlet.
When the relay is closed power flows to the light and it lights (if the light switch is on obviously) when the relay is open no current can flow and ther is no power to the light.
Its not the relay that is supplying power to the light. That comes from the wall outlet.  The relay is just enabling or disabling power from flowing thru the black wire by connecting or disrupting the path for electricity to flow.
YMMV
Be careful when working with AC power.
But switching AC power with a SainSmart relay and a raspberry pi is quite straightforward once you understand a little about it.

A: At first glance it looks fine.
Generally for wire two joined conductors the ground will have a stripe running on it. I've seen actual text specifying the wire's specifications on both sides.
Does the LED on the board turn on, or does your statement just mean that you were able to power a separate LED from that port?
You also mentioned you had driven some mechanical relays from that I/O port. What was the coil current for those? It's possible the port could have been damaged it it was overdrawn.
Have you tried other channels on the board, or powering it from a separate 5V supply?

A: That relay board is only good for switching AC loads of 100V or more. If you have a lower voltage load, it's not going to work.
For low voltage loads use transistors, MOSFETs or a ULN2803 driver board.


text:
Q: Keyboard lags three seconds first use iPad only - Obj-C My Keyboard lags on iPad ios8 and ios9, but was never doing it before the Xcode 7 update. Same code works fine on iphone, and second time page is loaded ipad keyboard works fine. After I press "next" to the next view controller, it takes three or four seconds to load the page because of the keyboard (I've debugged and removing this code allows page to load in less than a second). However, my view requires the keyboard be up when the page is loaded.
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.firstPinField becomeFirstResponder];
}

have tried in viewWillAppear, viewDidLoad
Is this a bug in xCode7, or does any one have an idea for me to try?

A: Keyboard takes some time to load. Try this library, which basically just creates a hidden UITextField, and force keyboard to load when the app starts.

A: Try it by adding in main queue in view did load


text:
Q: Need to get site URL in ConfigureServices method of Startup.cs I'm using ASP.NET Core MVC 2.2 and I need to get the current URL of the website in the ConfigureServices method of Startup.cs.
This is because the URL is passed into the constructor of a library that I am configuring in that method.
services.AddScoped<IEmailProvider>(ep => new SendGridEmailProvider(Configuration["Email:SendGridApiKey"],
                Configuration.GetValue<bool>("Email:TestMode", true),
                Configuration["Email:TestModeEmailAddresses"],
                Configuration["ENVIRONMENT"],
                "THIS SHOULD BE THE APPLICATION URL"));

I'm pretty sure that I can't use standard dependency injection techniques within ConfigureServices as this is where all the dependency injection is actually set up!
Is there some way of getting the current URL of the request? I just need the base URL like www.site.com.

A: You can add the HttpContext to the DI container:
services.AddHttpContextAccessor();

Then you can make a class to hold your EmailOptions:
public class EmailOptions
{
    public string ApiKey { get; set; }
    public bool TestMode { get; set; }
    public string TestModeEmail { get; set; }
    public string Environment { get; set; }
    public string Url { get; set; }
}

Then add a class to configure your EmailOptions:
public class ConfigureEmailOptions : IConfigureOptions<EmailOptions>
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly IConfiguration _configuration;
    private readonly IHostingEnvironment _environment;

    public ConfigureEmailOptions(
        IHttpContextAccessor httpContextAccessor,
        IConfiguration configuration,
        IHostingEnvironment environment)
    {
        _httpContextAccessor = httpContextAccessor;
        _configuration = configuration;
        _environment = environment;
    }

    public void Configure(EmailOptions options)
    {
        options.ApiKey = _configuration["Email:SendGridApiKey"];
        options.TestMode = _configuration.GetValue<bool>("Email:TestMode", true);
        options.TestModeEmail = _configuration["Email:TestModeEmailAddresses"];
        options.Environment = _environment.EnvironmentName;
        options.Url = _httpContextAccessor.HttpContext.Request.Scheme + "://" + _httpContextAccessor.HttpContext.Request.Host + _httpContextAccessor.HttpContext.Request.PathBase;
    }
}

Then add your EmailOptions to the DI container:
services.AddTransient<IConfigureOptions<EmailOptions>, ConfigureEmailOptions>();
services.Configure<EmailOptions>(Configuration);

After that, you should be able to inject IOptions<EmailOptions> into your SendGridEmailProvider. (You could also inject IHttpContextAccessor directly into your SendGridEmailProvider, but that would be a tighter coupling.)

A: I have a similar situation with an ASP.Net 5 application, the solution proposed by @crgolden using IHttpContextAccessor for a Scoped service works just fine
I didn't implement the IConfigureOptions (surely is a good approach, but maybe an overkill for my case), I simply called GetService<IHttpContextAccessor>() in the implementation factory method to get the instance of the service.
For this case it will be:
public void ConfigureServices(IServiceCollection services)
{
    // [...]

    services.AddHttpContextAccessor();

    services.AddScoped<IEmailProvider>(ep => new SendGridEmailProvider(Configuration["Email:SendGridApiKey"],
            Configuration.GetValue<bool>("Email:TestMode", true),
            Configuration["Email:TestModeEmailAddresses"],
            Configuration["ENVIRONMENT"],
            GetUrl(ep.GetService<IHttpContextAccessor>())));
}

public string GetUrl(IHttpContextAccessor ca)
{
    return ca.HttpContext.Request.Scheme + "://" + ca.HttpContext.Request.Host + ca.HttpContext.Request.PathBase;
}


text:
Q: Compare Data in Two Tables I have two tables that I need to compare to make sure the values match. For context, one is the employee's time sheet and the other is a table to holds their requests. Each has a time sheet code and a number of hours. My plan was to compare by summary to see if they match. However, I am having problems getting my logic to work perfectly every time. Without me posting my code (it is becoming a mess quickly anyway), how would you approach this? The comparison needs to be able to be run programmatically and in the end return a true/false.
This can be an RPG solution or a SQL solution.
This is what I need to make sure is true.
Table 1
02  1.5
04  16.0

Table 2
02  1.5
04  16.0

The problem is when
Table 1
02  1.5

Table 2
02  1.5
04  16.0

or when
Table 1
02  1.5
04  16.0

Table 2
02  1.5

or more so when
Table 1
02  1.5
04  16.0

Table 2

A: This will compare the total hours in A and B for each ID value, and only return records there the sum of B does not equal A.  It treats unmatched values of B as zero.
SELECT A.id, A.hours, SUM(COALESCE(B.Hours,0))
FROM A
LEFT OUTER JOIN B
  ON B.ID = A.ID
WHERE 1=1
  AND A.id = B.id
GROUP BY A.id
HAVING A.Hours != SUM(COALESCE(B.Hours,0))

Cheers,
Daniel

A: This should give the requested results:
with w1 ( wid, sumHrs )
 as ( SELECT id, sum(hours)
        FROM A   a1
        GROUP BY id ),
     w2 ( wid, sumHrs )
 as ( SELECT id, sum(hours)
        FROM B  b1
        GROUP BY id )
 select '1', w1.wid from w1 INNER JOIN w2
                                on w1.wid = w2.wid
                      where w1.sumHrs <> w2.sumHrs
union
 select '2', w1.wid from w1 EXCEPTION JOIN w2
                                on w1.wid = w2.wid
union
 select '3', w2.wid from w2 EXCEPTION JOIN w1
                                on w2.wid = w1.wid

There might be minor detail changes needed due to adapting and simplifying from a sample I have that's close but not exact. All of the basic concepts should be clear, though.
The CTE gives a couple summary "views" for use in the full statement. The INNER JOIN gives matching IDs with mismatched HOURS. The first EXCEPTION JOIN gives rows from the first table with no matching ID in the second table, and the second EXCEPTION JOIN gives rows that aren't matched in the other direction. And the UNIONs collect all results together.

A: In general, if you merge two tables, and the count of the resulting table is the same as the count of the individual tables, you can say that they have the same values.
I am not sure how to apply in your case, but maybe you can.

A: The simplest solution show lines that are in conflict:
CREATE TABLE requests ( employees_id integer, hours decimal );
CREATE TABLE hours ( employees_id integer, hours decimal );

SELECT * FROM requests, hours WHERE requests.employees_id = hours.employees_id AND requests.hours != hours.hours;

But it doesn't work if e.g. one 2h request needs to match two 1h markings.

A: I did something like this recently - here are my notes... the result set shows differences in values plus rows that are present in one table but not the other.
Step1: Create temporary tables containing the rows you want to compare.
Step2: Perform a FULL OUTER JOIN on the temp tables using the non aggregate columns as matching criterion.
DECLARE @Ta TABLE (PubA varchar(255), CampA varchar(255), RevA money)

INSERT INTO @Ta (PubA, CampA, RevA)
    SELECT Publisher, [Campaign Name], SUM([Revenue USD])
    FROM D1.dbo.Stats
    GROUP BY Publisher, [Campaign Name]

DECLARE @Tb TABLE (PubB varchar(255), CampB varchar(255), RevB money)

INSERT INTO @Tb (PubB, CampB, RevB)
    SELECT Publisher, [Campaign Name], SUM([Revenue USD])
    FROM D2.dbo.Stats
    GROUP BY Publisher, [Campaign Name]

SELECT PubA, CampA, RevA, PubB, CampB, RevB, RevA-RevB DiffRev
FROM @Ta
FULL OUTER JOIN @Tb
ON PubA=PubB and CampA=CampB
ORDER BY DiffRev DESC
GO

A: I put my two SQL results into views then based on many peoples feedback already came up with this. I think this could be created into it's own stored procedure.
SELECT SUM ( ERROR_COUNT ) AS TOTAL_ERRORS INTO NUM_ERRORS FROM (
SELECT COUNT ( * ) AS ERROR_COUNT
FROM MPRLIB . V_TSHOURSUMM A EXCEPTION JOIN MPRLIB . V_REQHOURSUMM B
ON A . EM_NUMBER = B . EM_NUMBER AND A . TIMESHEET_CODE = B . TIMESHEET_CODE AND A.HOURS_SUMMARY = B . HOURS_SUMMARY
WHERE A . EM_NUMBER = EMPLOYEE_ID OR B . EM_NUMBER = EMPLOYEE_ID
UNION
SELECT COUNT ( * ) AS ERROR_COUNT
FROM MPRLIB . V_REQHOURSUMM A EXCEPTION JOIN MPRLIB . V_TSHOURSUMM B
ON A . EM_NUMBER = B . EM_NUMBER AND A . TIMESHEET_CODE = B . TIMESHEET_CODE AND A . HOURS_SUMMARY = B . HOURS_SUMMARY
WHERE A . EM_NUMBER = EMPLOYEE_ID OR B . EM_NUMBER = EMPLOYEE_ID ) TABLE

It seems to work, but seems... excessive. Thoughts? Is there a better way?


text:
Q: Need to know when a non-modal window has closed I have opened childwindow from parentWindow (non-modal) - what's the best approach to achieving a 'wait' so that parentWindow will know when childWindow has closed? For a couple of reasons I cannot use showDialog(). I have tried a while loop (testing the childWindow's visibility property) but it just breaks (no exception - but just doesn't open childWindow). Is it a case of multi-threading??

A:
what's the best approach to achieving a 'wait' so that parentWindow
  will know when childWindow has closed?

You could use events so the parent window is notified when the child window closes. For instance, there is the Closed event.
Window childWindow = new ....
childWindow.Closed += (sender, e) =>
    {
        // Put logic here
        // Will be called after the child window is closed
    };
childWindow.Show();

A: I think you can use this:
    public ShowChild()
    {
        childWindow child = new childWindow();
        child.Closed += new EventHandler(child_Closed);
        child.Show();
    }

    void child_Closed(object sender, EventArgs e)
    {
        // Child window closed
    }


text:
Q: Implementing option menu one time for several activities I am trying to implement an options menu for my app and the same menu is used in different activities. In the Android developers site, it says the following:

Tip: If your application contains multiple activities and some of them
  provide the same options menu, consider creating an activity that
  implements nothing except the onCreateOptionsMenu() and
  onOptionsItemSelected() methods. Then extend this class for each
  activity that should share the same options menu. This way, you can
  manage one set of code for handling menu actions and each descendant
  class inherits the menu behaviors. If you want to add menu items to
  one of the descendant activities, override onCreateOptionsMenu() in
  that activity. Call super.onCreateOptionsMenu(menu) so the original
  menu items are created, then add new menu items with menu.add(). You
  can also override the super class's behavior for individual menu
  items.

My activities extend from Activity, ListActivity or MapActivity, so what would be the correct way to implement what they are suggesting here? is it possible? Because I cannot extend this new class for all of these, I could only do something like public abstract BaseMenu extends Activity (as explained in this question) but this doesn't work for me. So I am wondering if there is a work around I can implement.
Thanks in advance

A: For that common Base menu class you need to extend MapActivity class . So you can extend that common base menu class for you all activities.
For that ListActivity you can also implement the list without ListActivity, you can implement it by only Activity or MapActivity.
you have to declare you listview in xml file with the id like below.
 <ListView
            android:id="@+id/listView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>

Then you have to declare it in your activity class .
ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(your adapter);

Like above you can implement it without extend ListActivity.

A: you cannot use mapview without extending mapactivity class.... refer this..
MapView without MapActivity ..so you should let your base class extend map activity... and for activity using listview.. put listview in xml and you can use it in your activity..

A: I would create a static MenuProvider class that implements your onCreateOptionsMenu() and onOptionItemsSelected() methods statically to be called from onCreateOptionsMenu() and onOptionsItemsSelected() of the activities, like so:
public static class MenuProvider {

    // You can pass it the activity and other variables used by this method if
    //   you need to.
    // Since the implementation is the same across all activities, they should
    //   pass the same variables.
    public static void onCreateOptionsMenu(MenuItem item, Activity callingActivity, ...)
       ... // Do stuff on create
    }

    public static void onOptionItemsSelected(MenuItem item, Activity callingActivity, ...)
       ... // Do stuff on item select
    }
}

And in each of your activities, you would do:
public class MyMapActivity extends MapActivity {
    ...

    public void onCreateOptionsMenu(MenuItem item)
       MenuProvider.onCreateOptionsMenu(item, this, ... /*other variables */);
    }

    public static void onOptionItemsSelected(MenuItem item)
       MenuProvider.onOptionItemsSelected(item, this, ... /*other variables */);
    }

    ...
}


text:
Q: How can i use mysql transaction in cakephp? How can i use mysql transaction in cakephp (Without using saveAll() method)? i am using cakephp version 1.2 i have searched a lot but did not get any good example If anyone knows please help me thanks in advance ...

A: Here's a blog post with examples : http://monmonja.com/blog/2008/07/transaction-on-cakephp-12/
I recommend you upgrade to 1.3 though. CakePHP 2.0 will be coming out soon. The manual entry for 1.3 is here : http://book.cakephp.org/view/1633/Transactions
UPDATE
CakePHP 2.0 is also similar - http://book.cakephp.org/2.0/en/models/transactions.html
$dataSource = $this->getDataSource();
$dataSource->begin();

// Perform some tasks

if (/*all's well*/) {
    $dataSource->commit();
} else {
    $dataSource->rollback();
}


text:
Q: Am I taking a performance hit from virtualizing in an Ubuntu Host installed via wubi? I decided recently that since I virtualize all my programming environments there is basically no reason for me to be running Windows as a host OS. So, to get me started I installed Ubuntu via wubi and am happily dual-booting to it. From inside I can use virtualbox to access my windows 7 VM and start it up to develop in.
It's not particularly slower, but not any faster than it is on the Windows host and I wonder if that is because that's as fast as it's ever going to be on my hardware or because wubi still runs on top of windows.
Basically, I'm unclear on how exactly wubi works and what if any performance hits using it entails.

A: IIRC Linux installed via wubi does not run on top of windows at all, it just runs from a "virtual disk" file in the Windows filesystem. Therefore you will not see any performance degradation such as the hit in I/O performance common with some virtualisation solutions.
There will be a slight hit has all access to the vdisk files have to go through an extra filesystem layer, and the vdisk files may themselves be fragmented as well as the contents, but for many I/O patterns you will not particularly notice this.
So Windows in a VM running under Linux booted from a wubi based setup is likely to run very nearly as well as if Linux were install on it own physical partitions. If you do notice any unexpected performance drop, or if you end up wanting to remove the Windows host OS completely, it is possible to migrate a wbui install to direct physical partitions.


text:
Q: Algebraic Manipulation What is the best method to get the LHS equal to RHS?
$\frac{n(n+1)(n+2)}{3} + (n+1)(n+2) = \frac{(n+1)(n+2)(n+3)}{3}$
Thank you.

A: Since $1=\frac 33$, one has $$\begin{align}\frac{n(n+1)(n+2)}{3}+\color{blue}{1}\cdot (n+1)(n+2)&=\frac{n(n+1)(n+2)}{3}+\frac{\color{blue}{3}(n+1)(n+2)}{\color{blue}3}\\&=\frac{n\color{red}{(n+1)(n+2)}}{\color{red}{3}}+\frac{3\color{red}{(n+1)(n+2)}}{\color{red}{3}}\\&=\color{red}{\frac{(n+1)(n+2)}{3}}(n+3)\end{align}$$

A: Your equation is :
$$ \frac{n(n+1)(n+2)}{3} + (n+1)(n+2) = \frac{(n+1)(n+2)(n+3)}{3} \tag{$\star$}$$
Notice that the product $(n+1)(n+2)$ is common to all the terms in $(\star)$. If $n \in \mathbb{Z} \smallsetminus \left\{-2,-1 \right\}$, then $(n+1)(n+2) \neq 0$ and you can $\color{blue}{\text{simplify}}$ by $(n+1)(n+2)$ as follows :
$$ \frac{\require{cancel} n\color{blue}{\cancel{(n+1)(n+2)}}}{3} + \require{cancel} \color{blue}{\cancel{(n+1)(n+2)}} = \frac{\require{cancel} \color{blue}{\cancel{(n+1)(n+2)}}(n+3)}{3} \tag{$\star$}$$
It gives :
$$ \frac{n}{3} + 1 = \frac{n+3}{3} = \frac{n}{3} + 1. $$
which is true for all $n \in \mathbb{Z} \smallsetminus \left\{-2,-1 \right\}$.

A: Firstly, take $(n+1)(n+2)$ out as a factor:
$((n+1)(n+2))[\frac n3 +1] = \frac{n+3}{3} (n+1)(n+2)$
Then divide through by $(n+1)(n+2)$:
$(\frac n3 +1) = \frac{n+3}{3}$
Multiply both sides by $3$:
$n+3 = n+3$
Therefore LHS = RHS


text:
Q: QGIS: Export multiple points layers to Excel I am trying to export multiple points layers to separate Excel files. I could do it manually but since I have 500+ points layers it would take too long. Is there any Python code to solve this?

A: This should export all vector layers added to the table of contents to excel files:
import os
output_folder = r'C:\GIS\data\testdata'

options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "xlsx"

for lyr in QgsProject.instance().mapLayers().values():
    if isinstance(lyr, qgis._core.QgsVectorLayer):
        path = os.path.join(output_folder,lyr.name()+'.xlsx')
        QgsVectorFileWriter.writeAsVectorFormatV2(lyr, path, QgsCoordinateTransformContext() ,options)


text:
Q: How to convert a string variable with special characters in Python to print properly Sorry if the title is confusing but I have literally researched this for two hours and have no idea how I am supposed to ask this question so anyone feel free to edit this post.
I have this string variable that I created using web scraping and it uses special characters and looks something like "\ud83d\ude00\u0107\u00e7 \n hello" without the quotations when I print it. The issue is that I want it to print the actual special characters but I am not sure what encoding method I should use. If I copy and paste the exact string and print it, it works fine but as a variable I created, it doesn't display the special characters, just the text.
I have tried converting it to a string, using json.load, unicode-escape, UTF-8, and a bunch of others but I am honestly not sure what method I should use
page = requests.get('https://www.example.com')
soup = str(BeautifulSoup(page.text, 'html.parser')).splitlines()

for line in soup:
    if 'hello' in line:
        print(line) #produces literal text of \ud83d\ude00\u0107\u00e7 \n hello

print('\ud83d\ude00\u0107\u00e7 \n hello') #produces wanted result

I would like to outcome to look like this:
ćç
hello

A: Through another hour of trial and error, I figured out this was the answer:
line.encode('utf-8').decode('unicode-escape')

A: Let a = "\ud83d\ude00\u0107\u00e7 \n hello"
 a.encode('utf-16', 'surrogatepass').decode('utf-16')

Output:
'ćç \n hello'


text:
Q: checking for matching string I have the following names stored in a text file.
|Rafal Dlugosz     |     Ryszard Wojtyna|
|Shuming Wang     |     Junzo Watada|
|Ryszard Wojtyna     |     Rafal Dlugosz|
|Qinghua Hu     |     Daren X. Yu|
|Seok-Beom Roh     |     Tae-Chon Ahn|
|Daren X. Yu    |     Qinghua Hu|

Names are separated with | symbol. I need to display only those pair of names where the First person name is equal to Second person name in some pair and for the same pair , the Second person name is equal to first name.
Example:
|Rafal Dlugosz     |     Ryszard Wojtyna|
|Ryszard Wojtyna     |     Rafal Dlugosz|
|Qinghua Hu     |     Daren X. Yu|
|Daren X. Yu    |     Qinghua Hu|

Any kind of help would be appreciated .Thank you.

A: My suggestion is the following - split the strings on each line and create an Array of pairs in each pair place the first name lexicographical in the first position of the pair and the other name in the second position of the pair. Sort this Array and duplicates will be next to each other.
Also you will have to add somehow the knowledge of the index of each pair in the initial array. Maybe using your own structure is the best option:
class Entry implements Comparable {
  String first_name_lexicographically;
  String second_name_lexicographically;
  int initial_index;
  public Entry(String line, int index); // split the line and initilize the fields
}

Now create an Array of Entry sort it and duplicate Entries as to your definition will be neighboring.


text:
Q: Going for multiple consumers - One or more queues? I have an application that produces messages for 1000 client applications.
Each client will poll this ActiveMQ and lookup his messages.

*

*Should I implement one queue for every client?

*Would it be better to use one queue for all clients and diffirentiate the messages with JMS properities?

Example code with JMS properties
Producer:
Message message = context.createTextMessage(text);
message.setStringProperty("Client", client);
context.createProducer().send(queue, message);

Consumer:
String messageSelector = "Client = '" + client + "'";
JMSConsumer receiver = context.createConsumer(queue, messageSelector);

The 'client' will then be my unique client identifier. Ex: client-1; client-2; ... or a GUID.

A: How many messages per second per client do you expect? All 1000 clients getting messages and that too with message selection will bring down through put. It would be a good idea to split clients across manageable number of queues.


text:
Q: Physical or logical backup takes more space when backing up same MySQL database? Physical backup is copying the data files that belongs to database. Logical backup is using SQL statements.
So physical or logical backup takes more space when backing up same MySQL database?

A: If you backup the files by copying the directory tree, the backup is the same size as the original.
If you use mysqldump (or similar tool) to backup, that will contain CREATE and INSERT statements to recreate the database from scratch.  This can be larger or smaller, depending on the data involved.
An example of "smaller": a BIGINT takes 8 bytes in a table, but if the value is 1, it will take about 2 bytes in a logical dump (1 and a comma).


text:
Q: How to solve this equation involving log? I want to know for which natural numbers $n$ we have the inequality $n < 8\log_2(n)$.  I know the answer is $n \leq 43,$ but I have no idea how to get there.

A: I'm just going to explain the answer of Dr. Sonnhard Graubner more thoroughly.
It is well known that $\log_2 n = \frac{\ln (n)}{\ln (2)}$
So we have $$n < \frac{8}{\ln (2)} \cdot \ln(n)$$ Which is equivalent to
$$\frac{n}{\ln(n)} < \frac{8}{\ln(2)}$$
Now consider the function $h(x)=\frac{x}{\ln(x)}$, we have $h'(x)= \frac{\ln(x)-1}{\ln^2(x)}$
Therefore $h$ is increasing whenever $\ln(x)>1$, so for $x>e$. It follows that $\frac{n}{\ln(n)}$ is increasing for $n\geq 3$.
Therefore it it enough to find the first time $\frac{n}{\ln(n)}$ passes $\frac{8}{\ln(2)}$. Checking by hand (say using a calculator) you can show that for $n=43$ we have an inequality while for $n=44$ we don't.

A: You can write $$\frac{\ln(2)}{8}=\frac{\ln(n)}{n}$$ and consider the function
$$h(n)=\frac{\ln(n)}{n}$$


text:
Q: Issue when Programmatically Log a user into WordPress back-end from front-end I was trying to create a custom front-end login page. I know there are many front end login plugins like profile builder, but I need to develop a custom one as per the special client requirement of a read-only username that gets populated by the username passed as URL parameter and then upon entering password and submit, we need to log the user in and redirect him to WordPress profile page. That's why I created a custom login page as a theme template.
On submit I added this code after verifying the password to log the user in and redirect to profile page
wp_set_current_user( $user_info->ID, $user_info->user_login );
wp_set_auth_cookie( $user_info->ID, true, false );
do_action( 'wp_login', $user_info->user_login );

if (is_user_logged_in()) {
  wp_safe_redirect('/wp-admin/profile.php');
}

Sometimes this works perfectly and the profile page get loaded. But sometimes, it's not working and get's redirected from profile page to wp-login.php
I even tried adding the below code
$creds = array();
$creds['user_login'] = $user_info->user_login;
$creds['user_password'] = $user_pass;
$creds['remember'] = true;

$user = wp_signon( $creds, false );

But no use.
I am stuck at this as I don't see anything else other than what I tried in the internet to programmatically log a user in Wordpress. But it's sometimes not working. The user is identified as logged in in front end all the time (when checking with is_user_logged_in() or retrieving currently logged in user in the front end). But the backend is sometimes not identifying it as logged in.
Please help me figure out what the issue is and how to fix it

A: You can use this Front-End Only Users plugin or You can follow this code to get your work done.
It can be done by this args
$args = array(
                        'echo'           => true,
                        'redirect'       => home_url( '/wp-admin/' ),
                        'form_id'        => 'loginform',
                        'label_username' => __( 'Username' ),
                        'label_password' => __( 'Password' ),
                        'label_remember' => __( 'Remember Me' ),
                        'label_log_in'   => __( 'Log In' ),
                        'id_username'    => 'user_login',
                        'id_password'    => 'user_pass',
                        'id_remember'    => 'rememberme',
                        'id_submit'      => 'wp-submit',
                        'remember'       => true,
                        'value_username' => NULL,
                        'value_remember' => true
                    );

                    // Calling the login form.
                    wp_login_form( $args );


text:
Q: Why embed lua into a game engine? I've been looking into building a basic game engine from the ground up and after making a list of features that are common to other engines, one of the bigger things is the fact that they have an embedded scripting language like lua or python.
My question is how is an embedded scripting language superior to just making a header file (or something of the like) that the user can include in a c++ file which gives them access to many of the functions and states. I'm sure there's a very good answer out there, I just haven't stumbled on it yet.
Also beyond why it's needed, what are languages like lua used for in things like game engines?

A: Lua is a far simpler language than C++, and all you need to edit it is a text editor. This puts the ability to script events and/or high level game logic in the hand of your designers and end users. Dynamic typing and garbage collecting allows them write very succinct code that focusses on game logic rather than all the systems-level housekeeping chores you get in a language like C++. It's also far easier to sandbox.
Lua is a popular choice because it's small, portable, hackable ANSI C code base; easy to embed, extend, and -- most importantly for game developers -- it has a minimal runtime footprint (one of the fastest interpreted languages). It's also a great combination of easy to learn/read/write syntax, but with powerful features like coroutines which can be very useful in games.

A: The reason for including a scripting language is to allow users to customize the behavior without having to recompile the code.
I'm not sure about what you are asking in the second part of the question. Are you asking what other languages are used, or are you asking what ways are languages like Lua used?
If you asked about what other languages are good for this, one such language is Tcl. Tcl was designed from the ground up to be an embedded scripting language, and is very mature and robust, and easily learned by non-technical people.
As for what scripting languages are good for ... configuration files is one way. By using a programming language rather than a text file with name/value pairs, it allows users to add logic to their start-up files. For example, maybe you allow users to assign different functions to keys on the keyboard; with a programming language they can add different functions for different computers. Or, if you're creating a game like a RPG, perhaps you can assign different keys for different character classes. If playing as a mage, F12 might be cast a spell, but if playing as a warrior f12 might be to do a finishing blow.
There are many ways to use scripting languages, and many different langages to choose from. It all boils down to allowing your users to customize the behavior of the game without having to recompile the code.

A: You might find this article by a Game developer useful in understanding why embedded languages are used.
http://www.grimrock.net/2012/07/25/making-of-grimrock-rapid-programming/
Another good reason, is unless you are sharing your source code with your game users and they are all C programmers, languages such as lua make it possible for users to extend the game, for example look at World of Warcraft.


text:
Q: Convert string column into characters rows I have a table that contains following data:

id
value

1
P126

And I need to convert this table into

id
value

1
P

2
1

3
2

4
6

I tried STRING_SPLIT, but it is not working for empty delimiter.
Can someone please help me to format the data?

A: You can solve this by using a recursive cte:
DECLARE @t nvarchar(10) = 'P126';

WITH cte AS (
SELECT 1 id, LEFT(@t, 1) col, RIGHT(@t, LEN(@t)-1) txt
UNION ALL
SELECT id+1, LEFT(txt, 1), RIGHT(txt, LEN(txt)-1)
  FROM cte
  WHERE LEN(txt) >= 1
)
SELECT id, col
  FROM cte

A: You can do this like:
declare @str as varchar(2048) = 'P126'

;with c0 as(
select @str as s
), c1 as(
select number as n from master.dbo.spt_values where type = 'P' and number > 0
)
select SUBSTRING(c0.s, c1.n, 1) as item
       , ROW_NUMBER() over(order by c1.n) as pos
       , c0.s
from c0
inner join c1 on c1.n <= LEN(c0.s)

A: Create table and insert values:
CREATE TABLE [dbo].[test3](
    [id] [int] NULL,
    [value] [varchar](20) NULL
)

insert into [dbo].[test3] values (1,'P126');

Solution 1:
We can pass the value from the table to the variable @t via select query.
DECLARE @t nvarchar(10);
select @t=value from [dbo].[test3];

WITH cte AS (
SELECT 1 id, LEFT(@t, 1) col, RIGHT(@t, LEN(@t)-1) txt
UNION ALL
SELECT id+1, LEFT(txt, 1), RIGHT(txt, LEN(txt)-1)
  FROM cte
  WHERE LEN(txt) >= 1
)
SELECT id, col
  FROM cte

Solution 2:
We can define a function.
Create a function to split string:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create function [dbo].[MySplitStringFunc]( @str nvarchar(100))
returns @tableName Table
  (
    id int identity(1,1),
    value nchar(1)
  )
as

begin

  declare @insertStr nvarchar(100)
  declare @newstr nvarchar(100)
  declare @id int
  set @id=1;
  set @insertStr = substring(@str,@id,1)
  set @newstr = stuff(@str,@id,1,'')
  begin
    insert @tableName Values(@insertStr)
  end
  while(len(@newstr)>1)
    begin
      set @id =@id + 1
      set @insertStr = substring(@str,@id,1)
      insert @tableName values(@insertStr)
      set @newstr = stuff(@newstr,1,1,'')
    end

  insert @tableName values(@newstr)

  return
end

Call the function and it returned a table:
declare @string nvarchar(100)
select @string=value from [dbo].[test3]
select * from [dbo].[MySplitStringFunc](@string)


text:
Q: Forwarding Jasmin server SMPP traffic on Linux I'm running the Jasmin SMPP server on Ubuntu Server. The server works locally but now I want to be able to access it over the Internet. I'm not sure how to do this. Should I use a proxy or IP tables or something? The local server is running on 127.0.0.1:2775 and I want it to run on my servers public IP address on the same port. The server is a VPS hosted at DigitalOcean.
Any ideas on how to approach this?
Thanks in advance.


text:
Q: C copy 3-dimensional array I have a pointer to a 3-dimensional array, like this:
char ***_cube3d

And I am initialising it like this:
_cube3d = (char ***)malloc(size * (sizeof(char**)));
for (int i = 0; i< size; i++) {
    _cube3d[i] = (char **)malloc(size * sizeof(char*));
    for (int j = 0; j<size; j++) {
        _cube3d[i][j] = (char *)malloc(size * sizeof(char));
    }
}

Note that the array is of dynamic size, and can contain thousands of elements, so we cannot declare it as an array in advance.
Now, I want to copy all of its contents into another array, as efficiently as possible. I know the nested loop solution where we copy each element one by one, however, it seems extremely inefficient to me. Is there a way to speed this process up? C++ code is welcome, although I would prefer it in plain C, since I am planning to iterate this solution into Objective C, and I would like to avoid injecting C++ code into a clean Objective C project.
Can anyone point me in the right direction?

A: Using what you already have (but fixing the first malloc with sizeof(char***))
You could copy the array by running a bunch of for loops like this:
char new_cube[side][side][side];
for(unsigned int x = 0; x < side; x++)
    for(unsigned int y = 0; y < side; y++)
        for(unsigned int z = 0; z < side; z++)
            new_cube[x][y][z] = old_cube[x][y][z];

OR:
char new_cube[side][side][side];
for(unsigned int x = 0; x < side; x++)
    for(unsigned int y = 0; y < side; y++)
        memcpy(new_cude[x][y], old_cube[x][y], sizeof(char)*side);

which might be a bit faster.
using this method you avoid using any c++(as you said you would like) and your code complexity is kept minimal.

A: If you are using C.99, you can use a variable length array (VLA) to dynamically allocate your 3-dimensional array.  Once side is determined, you can declare your pointer to be:
char (*cube3d_)[side][side];

And then initialize it like this:
cube3d_ = malloc(side * sizeof(*cube3d_));

Note that in C, you are not required to cast the return value of malloc(), and doing so can actually lead to undefined behavior in the worst case. Since the "cube" has been allocated as a contiguous block, it can be copied with memcpy().
C++ does not have VLA. You can use a vector to get the C++ equivalent of your multi-dynamic allocation structure:
std::vector<std::vector<std::vector<char> > >
cube3d_(side, std::vector<std::vector<char> >(side, std::vector<char>(side)));

You can then copy it using a copy constructor or an assignment.

If cube3d_ is a member variable of an object/structure, so long as your object knows the value of side, you can still use a VLA pointer to access the memory.  For example:
struct Obj {
    size_t side_;
    void *cube3d_;
};

//...
size_t side = 3;

//...
Obj o;
o.side_ = side;
char (*p)[o.side_][o.side_] = malloc(o.side_ * sizeof(*p));
o.cube3d_ = p;

//...
char (*q)[o.side_][o.side_] = o.cube3d_;
q[1][2][2] = 'a';

A: Here is an approach using C and structs to provide some degree of object oriented along with a set of helper functions.
The idea here was to use Kerrick's suggestion of a contiguous array.
I am not sure if I got the offset calculation correct and it has not been tested so it is worth what you are paying for it.  However it may be helpful as a starting place.
The idea is to have a single contiguous area of memory to make memory management easier.  And to use a function to access a particular element using a zero based offset in the x, y, and z directions.  And since I was not sure as to the element size/type, I made that a variable as well.
#include <malloc.h>

typedef struct _Array3d {
    int   elSize;     // size of each element of the array in bytes
    int   side;       // length of each side of the 3d cube in elements
    char  * (*Access) (struct _Array3d *pObj, int x, int y, int z);
    char  buffer[1];
} Array3d;

static  char * Array3d_Access (Array3d *pObj, int x, int y, int z)
{
    char *pBuf = NULL;

    if (pObj && x < pObj->side && y < pObj->side && z < pObj->side) {
        pBuf = &(pObj->buffer[x * pObj->side * pObj->elSize * pObj->side * pObj->elSize + y * pObj->side * pObj->elSize + z * pObj->elSize]);
    }

    return pBuf;
}

// Create an Array3d cube by specifying the length of each side along with the size of each element.
Array3d *Array3d_Factory (int side, int elSize)
{
    Array3d *pBuffer = malloc (sizeof(Array3d) + side * elSize * side * elSize * side * elSize);

    if (pBuffer) {
        pBuffer->elSize = elSize;
        pBuffer->side = side;
        pBuffer->Access = Array3d_Access;
    }

    return pBuffer;
}

// Create an Array3d cube that is the same size as an existing Array3d cube.
Array3d *Array3d_FactoryObj (Array3d *pObj)
{
    Array3d *pBuffer = NULL;

    if (pObj) {
        int     iBufferSize = pObj->side * pObj->elSize * pObj->side * pObj->elSize * pObj->side * pObj->elSize;

        pBuffer = malloc (sizeof(Array3d) + iBufferSize);
        if (pBuffer) {
            pBuffer->elSize = pObj->elSize;
            pBuffer->side = pObj->side;
            pBuffer->Access = pObj->Access;
        }
    }

    return pBuffer;
}

// Duplicate or clone an existing Array3d cube into new one.
// Returns NULL if cloning did not happen.
Array3d *Array3d_Dup (Array3d *pObjDest, Array3d *pObjSrc)
{
    if (pObjSrc && pObjDest && pObjSrc->elSize == pObjDest->elSize && pObjSrc->side == pObjDest->side) {
        int     iBufferSize = pObjSrc->side * pObjSrc->elSize * pObjSrc->side * pObjSrc->elSize * pObjSrc->side * pObjSrc->elSize;

        memcpy (pObjDest->buffer, pObjSrc->buffer, iBufferSize);
    } else {
        pObjDest = NULL;
    }

    return pObjDest;
}

int main(int argc, _TCHAR* argv[])
{
    Array3d *pObj = Array3d_Factory (10, 20 * sizeof(char));

    char *pChar = pObj->Access (pObj, 1, 2, 3);
    return 0;
}


text:
Q: Copy all files of one type from directory into one folder This is a new one for me so I'm pretty much flying blind.
I have a folder at 192.168.1.2\mainFolder that contains folder1, folder2, and folder3. Inside each of those folders are a handful of different file extentions, and a couple of files of each type. I need to take all files that exist inside mainFolder of the .dep type, and copy them to 192.168.1.2\copyFolder
copyFolder will not have any folders inside it, but just many many files.
What is the best way to go about doing this? I have been told by TPTB that robocopy would be helpful, however I have never used robocopy and thought you guys may know of something better

A: So you don't want .dep files inside folder1, 2 etc.? Robocopy / xcopy is usually a good choice. Powershell is slow for such a simple operation. If you just want the .dep files in mainfolder but not those inside the subfolders, try:
robocopy \\192.168.1.2\mainFolder \\192.168.1.2\copyFolder *.dep


text:
Q: Linear algebra - determinant of $n\times n$ I have this question:

Solve the next determinant:

$D = \begin{vmatrix}
 1&  1& *&  *&  1&  1& \\
 1&  1&  *&  *&  1&  2& \\
 *&  *&  *&  1&  3&  1& \\
 *&  *&  *&  4&  1&  1& \\
 *&  *&  *&  *&  *&  *& \\
 1&  1&  n-1&  *&  *&  1& \\
 1&  n&  1&  &  *&  1&
\end{vmatrix}$
Here, $D$ is defined by:
$$
D_{ij} = \begin{cases} i & \mathrm{if}\ i+j=n+2 \\ 1 & \mathrm{else}\end{cases}
$$
What I've done so far:
$D = \begin{vmatrix}
 1&  1& *&  *&  1&  1& \\
 1&  1&  *&  *&  1&  2& \\
 *&  *&  *&  1&  3&  1& \\
 *&  *&  *&  4&  1&  1& \\
 *&  *&  *&  *&  *&  *& \\
 1&  1&  n-1&  *&  *&  1& \\
 1&  n&  1&  *&  *&  1&
\end{vmatrix}\xrightarrow[i \neq 1]{R_{i}\rightarrow R_{i} - R_{1}}
(-1)
\begin{vmatrix}
 1&  1& *&  *&  1&  1& \\
 0&  0&  *&  *&  0&  1& \\
 *&  *&  *&  0&  2&  0& \\
 *&  *&  *&  3&  0&  0& \\
 *&  *&  *&  *&  *&  *& \\
 0&  0&  n-2&  0&  *&  0& \\
 0&  n-1&  0&  *&  *&  0&
\end{vmatrix}$
$det(A) = \sum_{i = 1}^{n}(-1)^{i+1}a_{i1}+\det(A_{i1}^{M}) = (-1) * \begin{vmatrix}
 0&  0&  *&  *&  0& 1&  \\
 0&  0&  *&  *&  2&  0&\\
 *&  *&  *&  *&  *&  *&\\
 *&  *&  *&  *&  *&  *&\\
 0&  n-2&  0&  *&  0& 0&\\
 n-1&  0&  *&  *&  *&  0&
\end{vmatrix}$
How should I best proceed?

A: We can compute the terms of the sum in the Leibniz formula:
$$\det(A) = \sum_{\sigma \in S_n} \left( \mathrm{sgn}(\sigma) \prod_{i=1}^n a_{i,\sigma_i}\right)$$
It is clear from visual inspection of your last $n \times n$ matrix that only one term in this sum is nonzero. This is because each row besides the first has only one nonzero term, and so only one permutation, $\sigma^*$, chooses a nonzero term in each row.
A simple induction on $n$ shows that the value of $\mathrm{sgn}(\sigma^*)$ is $(-1)^n$. This yields a final answer of $$(-1)^n(n-1)!$$


text:
Q: Warning of running Turbo script from the body, and content wrongly placed above the nav bar I can't figure out what is causing this.  I have searched extensively on this site and elsewhere and can't find an instance of this same problem.  This should be a simple blog as part of a Udemy course.  However, any content added to the blog is also shown at the top of the page and a warning is in the console.
Here is the warning message in the dev console:

You are loading Turbo from a  element inside the
element. This is probably not what you meant to do!
Load your application's JavaScript bundle inside the  element
instead.  elements in  are evaluated with each page
change.
For more information, see:
https://turbo.hotwired.dev/handbook/building#working-with-script-elements
—— Suppress this warning by adding a "data-turbo-suppress-warning"
attribute to: Etiam porta sem malesuada magna
mollis euismod. Cras mattis consectetur purus sit amet fermentum.
Aenean lacinia bibendum nulla sed consectetur.
" />
<link rel="stylesheet" href="/assets/blogs-24c34aed3f27702e779f75c22507646d115e288bc601f6d2ff6ce647b3266cf6.css" media="all" data-turbolinks-track="reload">


text:
Q: How to prevent a TableCursor with a ControlEditor from redrawing the previous cell when a selection is changed? I'm working on Table that has TableCursor and a text editor. The problem is that after I select a cell the contents of the previous cell are drawn on top of the newly selected cell for a fraction of a second, and I want to prevent that from happening.
The following sample code exhibits the same problem:
http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/DemonstratesTableCursor.htm
If anyone wants to run the code, throw in these 3 lines before the TableCursor variable declaration and observe the problem as you select a different cell.
for (int i = 0; i < NUM; i++) {
    for (int j = 0; j < NUM; j++) {
        table.getItem(i).setText(j, Math.random() + "");
    }
}

A: This appears to do the trick:
cursor.addListener(SWT.Paint, new Listener()
{
    @Override
    public void handleEvent(Event event)
    {
          cursor.setRedraw(false);
    }

});
cursor.addListener(SWT.Selection, new Listener()
{
    @Override
    public void handleEvent(Event event)
    {
         event.display.asyncExec(new Runnable()
          {
              public void run()
              {
                  cursor.setRedraw(true);
              }
          });
    }
});


text:
Q: live555 Server streaming x264 not working, how to debug? Before diving into the SDK Version, i simply tried to stream an x264 encdoed video to VLC. Streaming MP3 Works, but x264 takes a while then i get an error, that vlc cannot open the file.
1) Downloaded Live555 Server
2) Started EXE which states the url to use as: rtsp://172.18.1.85/<filename>
3) In VLC i am using: rtsp://172.18.1.85/fantastic.264  As the server output says "Each files type is inferred from it's name suffix" so i renamed the file from fantastic.mp4 to fantastic.264
As i've stated an mp3 stream works fine in the same directory where fantastic.264 is placed.

A: The file ending was correct but it wasn't an "elementary h264 stream". So I had to reconvert it to an elementary h264 file.
Quick Fix:
ffmpeg -i fantastic.mp4 -vcodec libx264 -f h264 fantastic.264

You can get here more Information:
What does Elementary Stream mean in Terms of H264


text:
Q: java null object reference error / I want my TextView changes color and text when I click the button enter image description here
Logcat says 15th line has error. But I don't know the reason. :( I'm noob so plz explain me softly plz..
Down below is the whole content of logcat.
...
2020-10-17 16:50:03.488 9840-9840/? E/city_implement: Unknown bits set in runtime_flags: 0x8000
2020-10-17 16:50:04.351 9840-9840/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.acticity_implements, PID: 9840
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.acticity_implements/com.example.acticity_implements.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.acticity_implements.MainActivity.onCreate(MainActivity.java:15)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
...
xml code of buttonRed is this.
enter image description here

A: This can be broken down quite clear, from top to bottom:

*

*Line 15 throws a NullPointerException and has two references: buttonRed and this. this cannot be ever null, so it must be buttonRed.

*On line 14 findViewById is used to get the reference to the button, this apparently returns null.

This is, because you do not set your layout yet and there is no button. If you remove all code from onCreate, you will see you get a white screen without buttons.
Call setcontentview(R.layout.YOUR_LAYOUT) in onCreate, right after super.onCreate()


text:
Q: Mongodb aggregate $match a document OR all I have an parameterized mongodb aggregate query where the parameter receives a given ObjectID to be filtered or NULL if I want to return all documents. I mean, I would like to use the same pipeline to return one OR all documents.
My pipeline query is:
db.user.aggregate([
  {'$match': { _id : <MYUSERPARAM> } }
]);

The value of MYUSERPARAM will have a given ObjectId to be filtered or have some value if I don't want to filter a single document and I want to return all the documents.
Then my system will replace the MYUSERPARAM and run the query, such as:
To filter a single document:
db.user.aggregate([
  {'$match': { _id : ObjectId("5e2b9ab8b1dbae5124e4b635") } }
]);

or
somehow return all documents:
db.user.aggregate([
  {'$match': { _id : $all } }
]);

But the approach above is not working.
How can I have a pipeline query to filter a single document OR return all the documents just changing a single value/parameter in the query like the example above ?

A: Sounds like NoSQL injection:
db.user.aggregate([
  {'$match': { _id : {$ne: ""} } }
]);

or

db.user.aggregate([
  {'$match': { _id : {$exists: true} } }
]);


text:
Q: Получение себестоимости товара через API МоегоСклада Как можно получить себестоимость товара на заданную дату?
При запросе:
https://online.moysklad.ru/api/remap/1.1/report/stock/all?stockMode=all&product.id=291fb2ac-2e36-11e6-7a69-9711000b4b5e&filter=moment=2018-08-31%2016:31

параметр момент никак не влияет на результат.

A: filter= лишний, и формат даты смотрите в документации (идем по ссылке и кликаем на показать, чтоб раскрыть иформацию по параметрам)
В вашем случае попробуйте:
https://online.moysklad.ru/api/remap/1.1/report/stock/all?stockMode=all&product.id=291fb2ac-2e36-11e6-7a69-9711000b4b5e&moment=2018-08-31%2016-31-00


text:
Q: Django logout_then_login with next param In some cases I want to logout user, redirect it to the login page with next param, so when user will succesfully logged in, Django should redirect user to the some page.
I've found logout_then_login() method but looks like it does not support next after login page param. I've tried to pass 'next' param in extra_content param, but it doesn't work.
How can I do this? Maybe there are some other django methods to do this?
Speaking generally, I just want to make forced logout, make user to re-login and redirect it to the page where it was logget out.

A: From the docs (Scroll down for this method)
logout_then_login(request[, login_url, current_app, extra_context])
Logs a user out, then redirects to the login page.
URL name: No default URL provided
Optional arguments:

*

*login_url: The URL of the login page to redirect to. Defaults to settings.LOGIN_URL if not supplied.

*current_app: A hint indicating which application contains the current view. See the namespaced URL resolution strategy for more information.

*extra_context: A dictionary of context data that will be added to the default context data passed to the template.

Here we can see that the login method will accept a next parameter as a get variable.
Adding next to the login_url should do what you want:
from django.conf import settings
...
def myView(request):
    login_url = "%s?next=%s" % (settings.LOGIN_URL, request.path)
    logout_then_login(request, login_url=login_url)


text:
Q: Print data to connection before blocking I'm writing a NAT traversal node in PHP and I would like to be able to send data before the connection is closed. I need the script to send a string before blocking while waiting for data on a socket. It seems that echo writes to a buffer that is flushed and sent in bulk when the script exits or die is called. This is my current code:
$sktSocket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
$bSuccess = socket_bind($sktSocket, $_SERVER['SERVER_ADDR'], $sPass);
if($bSuccess){
    echo "wait for connection";
    flush();
    ob_flush();
    $remote_ip = "";
    $remote_port = "";
    $r = socket_recvfrom($sktSocket, $buf, 512, MSG_WAITALL, $remote_ip, $remote_port);
    //socket_sendto($sktSocket, "OK " . $buf , 100 , 0 , $remote_ip , $remote_port);
    socket_close($sktSocket);
}

I've tried flush, and ob_flush, but those do not do what I need.
Is there a way in php to write to the output stream before the blocking call (socket_recvfrom) so that the data is sent and then it blocks?


text:
Q: Retrieving data from parse.com and displaying in a table layout I am able to retrieve the data, according to the logs, but not sure how to display them.  I have created an activity with a table layout and tablerow with a textview to display the categories.

Logs:

A: If you just want to generate a prototype, you can use ParseQueryAdapter.
The code is from Parse.com docs
// Inside an Activity
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  // Uses a layout with a ListView (id: "listview"), which uses our Adapter.
  setContentView(R.layout.main);

  ParseQueryAdapter<ParseObject> adapter = new ParseQueryAdapter<ParseObject>(this, "Instrument");
  adapter.setTextKey("name");
  adapter.setImageKey("photo");

  ListView listView = (ListView) findViewById(R.id.listview);
  listView.setAdapter;
}

https://parse.com/docs/android/guide#user-interface-parsequeryadapter
https://github.com/ParsePlatform/ParseUI-Android
You can custom your query by a queryFactory
https://parse.com/docs/android/guide#user-interface-customizing-the-query
Or you can custom your XXXAdapter(ListAdapter, ArrayAdapter, BaseAdapter).
Before call findInBG show a loading animation. Once done be called, set this list to your adapter, and then adapter.notifyDataSetChanged().
If you are just not familiar with using ListView, you should Google it.

A: As I see,  this logs is JSON. May be the better way is use Gson deserialization.


text:
Q: When using an Erlang supervisor, can I execute code in response to a child exiting? When the child exits (either normally or on an error) I want to take some actions. Do I use erlang:monitor/2? And if so how do I get the pid? Also, will I be able to see why it stopped?

A: Yes, monitor will do the job.
You will get back: {'DOWN', MonitorRef, Type, Object, Info}
Where the Object is the pid and Info is the exit reason
You can also do with link and trap_exit, but links are bi-directional so you'd take that child out with you if the parent died.
The easiest way to get the PID of the child process will be to have the child register itself with the listener (the one using monitor) when it starts. Have it send self() and then the listener can monitor that PID.


text:
Q: Showing that a ring is a field as well for one of the provided choices.
Let $\mathbb M$ be one of the following rings: $\mathbb{R}, \mathbb{Q},  \mathbb{F_9}, \mathbb{C} $. Let $I$ be the ideal generated by $x^4+2x-2$. Is the ring $\mathbb M[x]/I$ a field for some of the above choices for $R$?

I have been trying to work my way around some problems involving ideals, but I get really confused when they get mixed with rings and fields. I'm stuck and don't know how to proceed.

A: In general, given a ring $R$ and an ideal $J$ of $R,$ we have that $R/J$ is a field if and only if $J$ is a maximal ideal of $R.$ Now, since each $\Bbb M$ is a field, here, then $\Bbb M[x]$ is a principal ideal domain, and so $I$ is maximal if and only if $I=\langle p(x)\rangle$ for some irreducible polynomial $p(x)\in\Bbb M[x].$ So, what you must determine is whether $x^4+2x-2$ is irreducible over any of the given fields $\Bbb M.$
Added: As a hint for how to address the case that $\Bbb M=\Bbb F_9,$ note that $\Bbb F_9$ has characteristic $3,$ and so $x^4+2x-2=x^4+2x+1,$ as far as $\Bbb F_9$ is concerned.


text:
Q: How to implement a new layer over JavaScript framework? What's the best way to implement a new layer over JavaScript framework (jQuery, Prototype, ...)?
+------------+
| JavaScript |
+------------+
|   jQuery   |
+------------+
|  MyLibrary |
+------------+

For example...
MyLibrary = MyLibrary || {};

MyLibrary.animate = function(params) {
   // some code
}

MyLibrary.insert = function(params) {
   // some code
}

Execution
MyLibrary.animate(params);

Thanks for reply!

A: Why not just extend jQuery, with plugins, to do what you want. Attempting to wrap the entire jQuery library would seem to be a lot of work just to add some functions.


text:
Q: lua error when running Garry's Mod server [ERROR] gamemodes/starwarsrp/gamemode/modules/base/sv_gamemode_functions.lua:256: attempt to index local 'jobTable' (a nil value)
  1. unknown - gamemodes/starwarsrp/gamemode/modules/base/sv_gamemode_functions.lua:256

Here is line 256 and 257:
 256 if jobTable.ShowSpare2 then
 257      return jobTable.ShowSpare2(ply)

A: jobTable is nil. It is not allowed to index nil values. That measn you may not write something like jobTable[1] or jobTable.ShowSpare(ply).
Either find out why jobTable is nil in your code or if you cannot ensure it is not nil, avoid indexing it by doing something like
if jobTable then return jobTable.ShowSpare(ply)

or
return jobTable and jobTable.ShowSpare(ply)


text:
Q: Azure Custom Domain (Namecheap) not working without www I thought I had all my mappings perfectly done:

I'm able to add the www.mydomain.me to azure but not mydomain.me. Is there something I'm missing?
Edit: When I attempt to point to mydomain.me in my broswer, I get the following error message:
Error 404 - Web app not found.

The web app you have attempted to reach is not available in this Microsoft Azure App Service region. This could be due to one of several reasons:

1. The web app owner has registered a custom domain to point to the Microsoft Azure App Service, but has not yet configured Azure to recognize it. Click here to read more.

2. The web app owner has moved the web app to a different region, but the DNS cache is still directing to the old IP Address that was used in the previous region. Click here to read more.

Thanks

A: It's hard to tell what's wrong since you've hidden the settings.  Here's what should work:

*

*A Record points to the IP address found on the Azure portal

*CName awverify points to awverify.yourservice.azurewebsites.net

*CName www points to yourservice.azurewebsites.net


text:
Q: Determine if current application is activated (has focus)
Note: There's a very similar question, but it's WPF-specific; this one is not.

How can I determine if the current application is activated (i.e. has focus)?

A: This works:
/// <summary>Returns true if the current application has focus, false otherwise</summary>
public static bool ApplicationIsActivated()
{
    var activatedHandle = GetForegroundWindow();
    if (activatedHandle == IntPtr.Zero) {
        return false;       // No window is currently activated
    }

    var procId = Process.GetCurrentProcess().Id;
    int activeProcId;
    GetWindowThreadProcessId(activatedHandle, out activeProcId);

    return activeProcId == procId;
}

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);

It has the advantage of being thread-safe, not requiring the main form (or its handle) and is not WPF or WinForms specific. It will work with child windows (even independent ones created on a separate thread). Also, there's zero setup required.
The disadvantage is that it uses a little P/Invoke, but I can live with that :-)

A: You can subscribe to Main Window's Activated event

A: First get the handle either using:
IntPtr myWindowHandle;
myWindowHandle = new WindowInteropHelper(Application.Current.MainWindow).Handle;

or
HwndSource source = (HwndSource)HwndSource.FromVisual(this);
myWindowHandle = source.Handle;

Then compare whethers it is the ForeGroundWindow:
if (myWindowHandle == GetForegroundWindow())
{
  // Do stuff!

}

[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();

A: since it's likely that some element in your UI has contain focus for the form to be active try:
this.ContainsFocus

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.containsfocus(v=vs.110).aspx

A: The solution I found which requires neither native calls nor requires handling events is to check Form.ActiveForm. In my tests, that was null when no window in the application was focused and otherwise non-null.
var windowInApplicationIsFocused = Form.ActiveForm != null;

Ah, this is specific to winforms. But that applies to my situation ;-).

A: Handle the Activated event of your main application Form.

A: In WPF the easiest way to check if a window is active is:
if(this.IsActive)
{
 //the window is active
}