text:
Q: Segmentation fault - C++ array I'm trying to change the text of some Labels with the following connections:
connect(ui->styleSelector, SIGNAL(currentIndexChanged(int)), this, SLOT(setStyle(int)));
connect(this, SIGNAL(instrumentChanged(QString)), ui->label_inst_1, SLOT(setText(QString)));
connect(this, SIGNAL(instrumentChanged_2(QString)), ui->label_inst_2, SLOT(setText(QString)));
connect(this, SIGNAL(instrumentChanged_3(QString)), ui->label_inst_3, SLOT(setText(QString)));

My setStyle slot:
    void SamplerModule::setStyle(int style){
    m_style = style;
    emit instrumentChanged(m_instruments[m_style][0]);
    emit instrumentChanged_2(m_instruments[m_style][1]);
    emit instrumentChanged_3(m_instruments[m_style][3]);
}

And my array (set in my Class constructor)
QString m_instruments[3][3];

m_instruments[0][1] = "Trompette";
m_instruments[0][2] = "Basse";
m_instruments[0][3] = "Piano";

m_instruments[1][1] = "Guitare";
m_instruments[1][2] = "Batterie";
m_instruments[1][3] = "Basse";

m_instruments[2][1] = "Basse";
m_instruments[2][2] = "Batterie";
m_instruments[2][3] = "Guitare";

But when i'm trying to run the code, I've a segmentation fault because of my signals which use m_instruments[x][0].
I really don't understand why. My slot setStyle has the right to access this array, so why this segmentation fault ?

Detail:
If i set QString m_instruments[3][3]; instead of QString m_instruments[][3]; in my header then the seg fault disappears. However, the array appreas empty outside of the constructor.
qDebug() << m_instruments[0][0]; returns "Trompette" in the consturctor but returns "" in my setStyle slot !

A: In your code, you have listed the following array:
QString m_instruments[3][3];

This array is length 3x3, which means you can access 3 column elements, 0, 1 and 2. On this line:
m_instruments[0][3] = "Piano";

You access element index 3, which is past the end of the array, which causes Undefined Behavior (in your case resulting in seg fault).
This may not be the only problem with your code, but it is certainly one of them.


text:
Q: Access SQL query with JOIN and a COUNT statement not counting anything I have two tables in MS Access. One for planets and one for the type of star it orbits.
I want to get a count of the planets per star type...so something like:
+----------+--------------------+
| StarType | PlanetsPerStarType |
+----------+--------------------+
| A        |                  4 |
| B        |                  1 |
| C        |                  7 |
+----------+--------------------+

So I wrote this SQL query:
SELECT StarType, COUNT(PlanetName) AS PlanetsPerStarType
FROM Planets AS p
LEFT JOIN StarClass AS s ON p.sid = s.sid
GROUP BY starType, PlanetName

But it just lists all the planets and a 1 for all the star types, it doesn't really count at all.
What could I be doing wrong?

A: By grouping by the starType and the PlanetName, the count is returning the number of records in each starType & PlanetName combination, which, unless you have more than one planet of the same name orbiting your star, will always be one.
For example, given the data:
+-----------+------------------+
| StarType  |    PlanetName    |
+-----------+------------------+
| G2V       | Mars             |
| G2V       | Earth            |
| G2V       | Venus            |
| Red Dwarf | Omicron Persei 8 |
| Red Dwarf | Vergon 6         |
+-----------+------------------+

Grouping by StarType and PlanetName will yield exactly the same data, since there are no repeating StarType and PlanetName combinations which would be consolidated into a group.
As such, the SQL code:
select t.StarType, count(t.PlanetName) as Planets
from YourTable t
group by t.StarType, t.PlanetName

Would yield:
+-----------+---------+
| StarType  | Planets |
+-----------+---------+
| G2V       |       1 |
| G2V       |       1 |
| G2V       |       1 |
| Red Dwarf |       1 |
| Red Dwarf |       1 |
+-----------+---------+

Since each group contains exactly one record.
If, instead, we group only by StarType, the Count aggregate function will return the number of records associated with each StarType:
select t.StarType, count(t.PlanetName) as Planets
from YourTable t
group by t.StarType

+-----------+---------+
| StarType  | Planets |
+-----------+---------+
| G2V       |       3 |
| Red Dwarf |       2 |
+-----------+---------+

redpajama_set_name: RedPajamaStackExchange


text:
Q: Nativescript error: Version strings are not in the same format I just have installed Nativescript on my macOS Sierra 10.12.12. But when i enter the command: tns platfrom add ios I get the following error message:
*Version strings are not in the same format*

*#platform add*

When I enter the same command for Android everything works fine.
tns doctor gives me the following feedback:
*Your components are up-to-date.*

*No issues were detected.*

Log Trace:
ns platform add ios --log trace > log.txt
Error: Version strings are not in the same format
at Object.versionCompare (/usr/local/lib/node_modules/nativescript/lib/common/helpers.js:111:15)
at /usr/local/lib/node_modules/nativescript/lib/services/ios-project-service.js:92:25
at Function.settle (/usr/local/lib/node_modules/nativescript/node_modules/fibers/future.js:249:26)
at FiberFuture.wait (/usr/local/lib/node_modules/nativescript/node_modules/fibers/future.js:565:10)
at /usr/local/lib/node_modules/nativescript/lib/services/platform-service.js:69:47
at Function.settle (/usr/local/lib/node_modules/nativescript/node_modules/fibers/future.js:249:26)
at FiberFuture.wait (/usr/local/lib/node_modules/nativescript/node_modules/fibers/future.js:565:10)
at .each.platform (/usr/local/lib/nodemodules/nativescript/lib/services/platform-service.js:55:58)
at arrayEach (/usr/local/lib/node_modules/nativescript/node_modules/lodash/lodash.js:451:11)
at Function.forEach (/usr/local/lib/node_modules/nativescript/node_modules/lodash/lodash.js:8634:14)

A: @Brad Martin
This is my package.json file:
{
  "description": "NativeScript Application",
  "license": "SEE LICENSE IN <your-license-filename>",
  "readme": "NativeScript Application",
  "repository": "<fill-your-repository-here>",
  "nativescript": {
    "id": "org.nativescript.HelloWorld",
    "nativescript-teststudio-variables": {
      "IOS_APP_URL": "telerikmt1"
    },
    "tns-android": {
      "version": "2.5.0"
    }
  },
  "dependencies": {
    "@angular/common": "2.4.3",
    "@angular/compiler": "2.4.3",
    "@angular/core": "2.4.3",
    "@angular/forms": "2.4.3",
    "@angular/http": "2.4.3",
    "@angular/platform-browser": "2.4.3",
    "@angular/platform-browser-dynamic": "2.4.3",
    "@angular/router": "3.4.3",
    "nativescript-angular": "1.4.0",
    "nativescript-teststudio": "^1.1.4",
    "nativescript-theme-core": "~1.0.2",
    "reflect-metadata": "~0.1.8",
    "rxjs": "~5.0.1",
    "tns-core-modules": "^2.5.1"
  },
  "devDependencies": {
    "babel-traverse": "6.23.1",
    "babel-types": "6.23.0",
    "babylon": "6.16.1",
    "lazy": "1.0.11",
    "nativescript-dev-android-snapshot": "^0.*.*",
    "nativescript-dev-typescript": "^0.3.5",
    "typescript": "~2.1.0",
    "zone.js": "~0.7.2"
  }
}


text:
Q: How to display previous shell commands after exiting vim in macOS Terminal? I'm using the macOS Terminal app.  When I exit vim, the text of the file I was editing remains on my screen and overlaps the commands I typed previously, so I can't see any of my previous commands.  How can I change this behavior so I can see my previous commands?
I've found this post
How can I stop VI from overlapping and hiding the last page of command line output?
but I don't see the altscreen command.

A: altscreen is only useful if you use Vim inside a screen session. If you don't, it's irrelevant.
In iTerm, the behavior you describe is controlled by the Disable save/restore alternate screen checkbox in the Preferences window:
Profiles > Terminal > Disable save/restore alternate screen > (uncheck the checkbox)
Uncheck it to get your previous prompts and command outputs back.
In Terminal, the default behavior is the one you want and I don't see anything in the options that would change it.


text:
Q: AutoMapper not working as expected? I have a class at my Domain layer something as below:
 public class Employee : AuditableEntity
    {
        public string FirstName { get; set; }
        public string Surname { get; set; }
        public double Salary{ get; set; }
        public int PhoneNo { get; set; }

        public double Bonus
        {
            get { return Salary + EmployeeAdditionals.Sum(e => e.Value); }
        }

        // virtual allow lazy loading
        public virtual ReadOnlyCollection<EmployeeAdditional> EmployeeAdditionals { get; private set; }

        // Paramterless constructor for EF
        public Employee()
        {
            EmployeeAdditionals = new List<EmployeeAdditional>();
        }

        public void AddAdditionalInfo(EmployeeAdditional additionalInfo)
        {
            additionalInfo.Employee = this;
            additionalInfo.EmployeeId = Id;

            ((Collection<EmployeeAdditional>) EmployeeAdditionals).Add(additionalInfo);
        }

I then have the following viewModel class in my MVC 5 Application:
 public class EmployeeDetailsViewModel : BaseViewModel
    {
        public EmployeeDetailsViewModel()
        {
            Employee = new Employee();
        }

        public Employee Employee { get; set; }
        //Other fields

    }

    public class Employee
    {
        [DisplayName("Employee First Name")]
        public string FirstName { get; set; }

        [DisplayName("Employee Surname")]
        public string Surname{ get; set; }

        public double Salary{ get; set; }

        [RegEx for Phone Number and Error Mesage]
        public int PhoneNo{ get; set; }

        public double Bonus { get; set; }
    }

I have mapping then in my controllers and viewModel builder to map my viewmodel to my domain model and domain model back to view model and I am attempting to use AutoMapper for this.
Using manual mapping something like below:
// set domain from viewModel
employee.FirstName= model.Employee.FirstName;
//etc for rest of fields

// set view model from domain
viewModel.Employee.FirstName = employee.FirstName;
//etc for rest of fields

Now in my AutoMapperBootstrapper class in Setup method I have the following:
  Mapper.CreateMap<Domain.Models.Employee, Employee>();
  Mapper.CreateMap<Employee, Domain.Models.Employee>();

Then I am using this is following in my controller and viewmodel builder:
//set domain from viewModel
Mapper.Map(employee, model.Employee);

// set viewmodel from domain
Mapper.Map(viewModel.Employee, employee);

When I hit a breakpoint on mapping from domain to viewModel I see the model.Employee with the values from screen but when I step over this line the values do not get mapped to domain employee and then the model.Emplyee values are reset to null for the strings, 0.0 for double, etc.
Is there something incorrect with my configuration or use of automapper?

A: You pass wrong parameter. If you want to use existing instance, make sure first parameter is source and second parameter is destination.
Try to switch the parameter.
//set domain from viewModel (viewModel is the source)
Mapper.Map(model.Employee, employee);
              ^^^^^         ^^^^^
              source      destination

// set viewmodel from domain (domain is the source)
Mapper.Map(employee, viewModel.Employee);
            ^^^^^           ^^^^^
            source      destination

A: Shouldn't your map code actually be like this? You have to use instances for Map(), it looks like you are using Types
//set domain from viewModel
Mapper.Map(viewEmployee, new model.Employee());

// set viewmodel from domain
Mapper.Map( employee, new viewmodel.Employee());

This is how I would expect you to use it:
var viewModel = Mapper.Map<ViewModel.Employee>(domainModel);  <-- this creates a ViewModel for a Domain Model

and the reverse would be:
var domainModel  = Mapper.Map<Domain.Employee>(viewModel);


text:
Q: How can I find points of max and min of $2\sin(x)-\sin(2x)$? How can I find points of max and min of  $2\sin(x)-\sin(2x)$ in $[0, 2π]$ ?
In fact the derivative is $2\cos x - 2\cos(2x)$, which I can't check with an inequality where is bigger or lesser than zero.
How can I solve $2\cos x - 2\cos(2x)\ge0$ ?

A: Note that$$2\cos(x)-2\cos(2x)=2\cos(x)-2\bigl(2\cos^2(x)-1\bigr)=-4\cos^2(x)+2\cos(x)+2.$$So, considere the polynomial function $p(x)=-4x^2+2x+2$ and check its sign.

A: Hint:
$$\cos(2x) = 2\cos^2 x - 1$$
Can you take it from here, now that you have a quadratic equation in $\cos(x)$?

A: By AM-GM
$$|2\sin{x}-\sin2x|=\sqrt{4\sin^2x(1-\cos{x})^2}=2\sqrt{(1-\cos{x})^3(1+\cos{x})}=$$
$$=6\sqrt3\sqrt{\left(\frac{1-\cos{x}}{3}\right)^3(1+\cos{x})}\leq6\sqrt3\sqrt{\left(\frac{3\cdot\frac{1-\cos{x}}{3}+1+\cos{x}}{4}\right)^4}=\frac{3\sqrt3}{2}.$$
The equality occurs for $\frac{1-\cos{x}}{3}=1+\cos{x}.$
Can you end it now?


text:
Q: how to get UILocalNotification repeat on certain days I am making a alarm clock app that fires a local notification on a certain user selected day i.e. if user selected M, F, Sat then it should fire an alarm every M/F/Sat only. The problem that I have is that my bloody alarm is firing every single day at that time. How can I restrict it to user selected days? Here is my code
//For testing purposes I want the alarm to fire only on Monday at 7:00am.
//This fires every day at 7:00am
[[UIApplication sharedApplication] cancelAllLocalNotifications];

 NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDate *now = [NSDate date];

    // set components for time 7:00 a.m. Monday
    NSDateComponents *componentsForFireDate = [calendar components:(NSYearCalendarUnit |   NSHourCalendarUnit | NSMinuteCalendarUnit| NSSecondCalendarUnit | NSWeekdayCalendarUnit) fromDate: now];

    [componentsForFireDate setWeekday: 2] ;
    [componentsForFireDate setHour: 7] ;
    [componentsForFireDate setMinute:0] ;
    [componentsForFireDate setSecond:0] ;

    NSDate *fireDateOfNotification = [calendar dateFromComponents: componentsForFireDate];

    // Create the notification
    UILocalNotification *notification = [[UILocalNotification alloc]  init] ;

    notification.fireDate = fireDateOfNotification ;
    notification.timeZone = [NSTimeZone localTimeZone] ;
    notification.alertBody = [NSString stringWithFormat: @"Wake up!"] ;
    notification.userInfo= [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Waking Up time"] forKey:@"wakeUp"];

//Problem is here NSDayCalendarUnit makes my alarm fire every day
    notification.repeatInterval= NSDayCalendarUnit ;

    //notification.soundName=UILocalNotificationDefaultSoundName;
    notification.soundName=@"alarm-clock-ringing-01.wav";

    [[UIApplication sharedApplication] scheduleLocalNotification:notification] ;

A: Would it work if you actually make the local notification fire only once but when your device receives the notification, make it post the same notification again. Your app does not need to be running for this to work.
You handle the local notification when your application is not running, in the applicationDidFinishLaunching of your app delegate:
UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];

// handles notification when application is relaunched after being terminated
// not when app is already in the foreground running.
if(localNotif)
{
    // repeat the same local notification again
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}

Note: repeatInterval will perform the same action by the unit you specified (in this case "day", will repeat every day regardless of what you specified as the date of the notification)

A: You could make three alarms: one for the closest Monday, closest Wednesday and closest Friday and set notification.repeatInterval = NSWeekCalendarUnit on each of them.


text:
Q: vstest.console.exe crashing on UWP unit test project with "Data at the root level is invalid." Trying to run a UWP unit test project using vstest.console.exe, I generate the appx package using MSBuild, and call:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\Extensions\TestPlatform> ./vstest.console.exe C:\builds\droplocation\Uwp.UnitTesting\AppPackages\Uwp.UnitTesting_1.0.0.0_x86_Debug_Test\wp.UnitTesting_1.0.0.0_x86_Debug.appx

But getting:
Microsoft (R) Test Execution Command Line Tool Version 15.5.0
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
Failed to launch testhost with error: System.AggregateException: One or more errors occurred. ---> Microsoft.Build.Exceptions.InvalidProjectFileException: The project file could not be loaded. Data at the root level is invalid. Line 1, position 1.  C:\builds\droplocation\RS.Uwp.UnitTesting\AppPackages\RS.Uwp.UnitTesting_1.0.0.0_x86_Debug_Test\RS.Uwp.UnitTesting_1.0.0.0_x86_Debug.appx ---> System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
   at System.Xml.XmlTextReaderImpl.Throw(Exception e)
   at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
   at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
   at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
   at System.Xml.XmlTextReaderImpl.Read()
   at System.Xml.XmlTextReader.Read()
   at Microsoft.Build.Internal.XmlReaderExtension.GetXmlReader(StreamReader input, Encoding& encoding)
   at Microsoft.Build.Internal.XmlReaderExtension..ctor(String file)
   at Microsoft.Build.Construction.ProjectRootElement.LoadDocument(String fullPath, Boolean preserveFormatting)
   --- End of inner exception stack trace ---
   at Microsoft.Build.Shared.ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(Boolean condition, String errorSubCategoryResourceName, BuildEventFileInfo projectFile, Exception innerException, String resourceName, Object[] args)
   at Microsoft.Build.Construction.ProjectRootElement.LoadDocument(String fullPath, Boolean preserveFormatting)
   at Microsoft.Build.Construction.ProjectRootElement..ctor(String path, ProjectRootElementCache projectRootElementCache, Boolean preserveFormatting)
   at Microsoft.Build.Construction.ProjectRootElement.CreateProjectFromPath(String projectFile, IDictionary`2 globalProperties, String toolsVersion, ProjectRootElementCache projectRootElementCache, Boolean preserveFormatting)
   at Microsoft.Build.Construction.ProjectRootElement.<>c__DisplayClass200_0.<OpenProjectOrSolution>b__0(String path, ProjectRootElementCache cache)
   at Microsoft.Build.Evaluation.ProjectRootElementCache.Get(String projectFile, OpenProjectRootElement openProjectRootElement, Boolean isExplicitlyLoaded, Nullable`1 preserveFormatting)
   at Microsoft.Build.Construction.ProjectRootElement.OpenProjectOrSolution(String fullPath, IDictionary`2 globalProperties, String toolsVersion, ProjectRootElementCache projectRootElementCache, Boolean isExplicitlyLoaded)
   at Microsoft.Build.Evaluation.ProjectCollection.LoadProject(String fileName, IDictionary`2 globalProperties, String toolsVersion)
   at Microsoft.VisualStudio.UwpTestHostRuntimeProvider.RecipeFile.get_Project()
   at Microsoft.VisualStudio.UwpTestHostRuntimeProvider.RecipeFile.get_LayoutPath()
   at Microsoft.VisualStudio.UwpTestHostRuntimeProvider.Deployer.Microsoft.VisualStudio.UwpTestHostRuntimeProvider.IDeployer.Deploy()
   at Microsoft.VisualStudio.UwpTestHostRuntimeProvider.UwpTestHostManager.<LaunchHostAsync>d__35.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.UwpTestHostRuntimeProvider.UwpTestHostManager.<Microsoft-VisualStudio-TestPlatform-ObjectModel-Host-ITestRuntimeProvider-LaunchTestHostAsync>d__30.MoveNext()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client.ProxyOperationManager.SetupChannel(IEnumerable`1 sources, CancellationToken cancellationToken)
---> (Inner Exception #0) Microsoft.Build.Exceptions.InvalidProjectFileException: The project file could not be loaded. Data at the root level is invalid. Line 1, position 1.  C:\builds\droplocation\RS.Uwp.UnitTesting\AppPackages\RS.Uwp.UnitTesting_1.0.0.0_x86_Debug_Test\RS.Uwp.UnitTesting_1.0.0.0_x86_Debug.appx ---> System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
   at System.Xml.XmlTextReaderImpl.Throw(Exception e)
   at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
   at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
   at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
   at System.Xml.XmlTextReaderImpl.Read()
   at System.Xml.XmlTextReader.Read()
   at Microsoft.Build.Internal.XmlReaderExtension.GetXmlReader(StreamReader input, Encoding& encoding)
   at Microsoft.Build.Internal.XmlReaderExtension..ctor(String file)
   at Microsoft.Build.Construction.ProjectRootElement.LoadDocument(String fullPath, Boolean preserveFormatting)
   --- End of inner exception stack trace ---
   at Microsoft.Build.Shared.ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(Boolean condition, String errorSubCategoryResourceName, BuildEventFileInfo projectFile, Exception innerException, String resourceName, Object[] args)
   at Microsoft.Build.Construction.ProjectRootElement.LoadDocument(String fullPath, Boolean preserveFormatting)
   at Microsoft.Build.Construction.ProjectRootElement..ctor(String path, ProjectRootElementCache projectRootElementCache, Boolean preserveFormatting)
   at Microsoft.Build.Construction.ProjectRootElement.CreateProjectFromPath(String projectFile, IDictionary`2 globalProperties, String toolsVersion, ProjectRootElementCache projectRootElementCache, Boolean preserveFormatting)
   at Microsoft.Build.Construction.ProjectRootElement.<>c__DisplayClass200_0.<OpenProjectOrSolution>b__0(String path, ProjectRootElementCache cache)
   at Microsoft.Build.Evaluation.ProjectRootElementCache.Get(String projectFile, OpenProjectRootElement openProjectRootElement, Boolean isExplicitlyLoaded, Nullable`1 preserveFormatting)
   at Microsoft.Build.Construction.ProjectRootElement.OpenProjectOrSolution(String fullPath, IDictionary`2 globalProperties, String toolsVersion, ProjectRootElementCache projectRootElementCache, Boolean isExplicitlyLoaded)
   at Microsoft.Build.Evaluation.ProjectCollection.LoadProject(String fileName, IDictionary`2 globalProperties, String toolsVersion)
   at Microsoft.VisualStudio.UwpTestHostRuntimeProvider.RecipeFile.get_Project()
   at Microsoft.VisualStudio.UwpTestHostRuntimeProvider.RecipeFile.get_LayoutPath()
   at Microsoft.VisualStudio.UwpTestHostRuntimeProvider.Deployer.Microsoft.VisualStudio.UwpTestHostRuntimeProvider.IDeployer.Deploy()
   at Microsoft.VisualStudio.UwpTestHostRuntimeProvider.UwpTestHostManager.<LaunchHostAsync>d__35.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.UwpTestHostRuntimeProvider.UwpTestHostManager.<Microsoft-VisualStudio-TestPlatform-ObjectModel-Host-ITestRuntimeProvider-LaunchTestHostAsync>d__30.MoveNext()<---

Test Run Aborted.

When I change the vstest.console.exe lcoation from:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\Extensions\TestPlatform

to:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TestWindow

It works on my local machine with VS2017 Professional, but when called with the build agent on the remove build server, it's still the same:
******************************************************************************
Starting: VsTest - UWP
******************************************************************************
==============================================================================
Task         : Visual Studio Test
Description  : Run tests with Visual Studio test runner
Version      : 2.3.8
Author       : Microsoft Corporation
Help         : [More Information](https://go.microsoft.com/fwlink/?LinkId=835764)
==============================================================================
Run the tests locally using vstest.console.exe
========================================================
Test selector : Test assemblies
Test assemblies : C:\agent\_work\2\a\AppxPackages\Uwp.UnitTesting_1.0.0.0_x86_Test\Uwp.UnitTesting_1.0.0.0_x86.appx
Test filter criteria : null
Search folder : C:\agent\_work\2\s
Run settings file : C:\agent\_work\2\s
Run in parallel : false
Run in isolation : true
Path to custom adapters : null
Other console options : null
Code coverage enabled : false
Rerun failed tests: false
vstest.console.exe, specified location : C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TestWindow
========================================================
"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe" @C:\agent\_work\_temp\635f6641-039f-11e8-b3d5-d35598e183b1.txt
Microsoft (R) Test Execution Command Line Tool Version 15.5.0
Copyright (c) Microsoft Corporation.  All rights reserved.
vstest.console.exe
"C:\agent\_work\2\a\AppxPackages\Uwp.UnitTesting_1.0.0.0_x86_Test\Uwp.UnitTesting_1.0.0.0_x86.appx"
/InIsolation
/logger:"trx"
/TestAdapterPath:"C:\agent\_work\2\s"
Starting test execution, please wait...
Failed to launch testhost with error: System.AggregateException: One or more errors occurred. ---> Microsoft.Build.Exceptions.InvalidProjectFileException: The project file could not be loaded. Data at the root level is invalid. Line 1, position 1.  C:\agent\_work\2\a\AppxPackages\Uwp.UnitTesting_1.0.0.0_x86_Test\Uwp.UnitTesting_1.0.0.0_x86.appx ---> System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
   at System.Xml.XmlTextReaderImpl.Throw(Exception e)

What's strange, when I try to run it manually on the build server, it crashes with following output:
PS C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TestWindow> ./vs
test.console.exe C:\agent\_work\2\a\AppxPackages\Uwp.UnitTesting_1.0.0.0_x86_Test\Uwp.UnitTesting_1.0.0.0_x86.appx
 /InIsolation /Platform:x86
Microsoft (R) Test Execution Command Line Tool Version 15.0.27130.2020
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...

Unhandled Exception: System.Runtime.CallbackException: A user callback threw an exception.  Check the exception stack an
d inner exception to determine the callback that failed. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: applicationName
   at Microsoft.VisualStudio.TestPlatform.ObjectModel.ValidateArg.NotNull[T](T arg, String parameterName)
   at Microsoft.VisualStudio.TestPlatform.Client.LocalCrashDumpUtilities.TryGetLocalCrashDumpPath(String applicationName
, String& crashDumpPath)
   at Microsoft.VisualStudio.TestPlatform.Client.TestExecutorServiceClient.TryGetLocalCrashDumpPath(String applicationNa
me, String& crashDumpPath)
   at Microsoft.VisualStudio.TestPlatform.Client.TestExecutorServiceClient.GetTestRunAbortedMessage(String executorProce
ssName, Int32 executorProcessId, Boolean hasExited, Boolean isRemoteExecution)
   at Microsoft.VisualStudio.TestPlatform.Client.TestExecutorServiceClient.TestExecutorServiceChannel_Reset(Object sende
r, EventArgs e)
   at System.ServiceModel.Channels.CommunicationObject.OnClosed()
   --- End of inner exception stack trace ---
   at System.ServiceModel.Channels.CommunicationObject.OnClosed()
   at System.ServiceModel.ServiceHostBase.OnClosed()
   at System.ServiceModel.ServiceHost.OnClosed()
   at System.ServiceModel.Channels.CommunicationObject.Close(TimeSpan timeout)
   at Microsoft.VisualStudio.TestPlatform.Client.UniversalTestExecutorProxy.Close()
   at Microsoft.VisualStudio.TestPlatform.Client.TestExecutorServiceClient.StarPlatformSpecificTestExecution(IPlatformTe
stExecutorClient platformTestExecutorClient, ITestExecutorLauncher launcher, Architecture targetPlatform, FrameworkVersi
on targetFramework)
   at Microsoft.VisualStudio.TestPlatform.Client.TestExecutorServiceClient.Initialize_NoLock(Architecture targetPlatform
, FrameworkVersion targetFramework)
   at Microsoft.VisualStudio.TestPlatform.Client.TestExecutorServiceClient.EnsureInitialized(IDictionary`2 environmentVa
riables, TestExecutionContext context)
   at Microsoft.VisualStudio.TestPlatform.Client.TestExecutorServiceClient.<>c__DisplayClass18_0.<StartTestRun>b__0()
   at Microsoft.VisualStudio.TestPlatform.Client.TestExecutorServiceClient.InvokeTestExecutorServiceAction(Action action
)
   at Microsoft.VisualStudio.TestPlatform.Client.TestExecutorServiceClient.StartTestRun(IEnumerable`1 sources, TestExecu
tionContext executionContext, String runSettings, IDictionary`2 environmentVariables, String dataCollectionServiceUri, I
TestCaseLog testCaseLog, ITestRunLog testRunLog, IFrameworkHandleInternal frameworkHandle)
   at Microsoft.VisualStudio.TestPlatform.Client.Rocksteady.RocksteadyExecutionManager.StartTestRun(TestRunCriteria test
RunCriteria, Boolean inIsolation, DataCollectionParameters dataCollectionParameters, ITestRunEventsHandler runEventsHand
ler)
   at Microsoft.VisualStudio.TestPlatform.Client.TestRunRequest.ExecuteAsync()
   at Microsoft.VisualStudio.TestPlatform.CommandLine.Processors.RunTestsArgumentProcessor.RunTests(IEnumerable`1 source
s, String packageFullName, String deviceInfo, Boolean isPhoneAppx, Boolean isUniversalTestAppx)
   at Microsoft.VisualStudio.TestPlatform.CommandLine.Processors.RunTestsArgumentProcessor.ExecuteAppContainerSources(Li
st`1 appContainerSources, String deviceInfo, Boolean isPhoneAppx)
   at Microsoft.VisualStudio.TestPlatform.CommandLine.Processors.RunTestsArgumentProcessor.Execute()
   at Microsoft.VisualStudio.TestPlatform.CommandLine.Executor.Execute(String[] args)
   at RockSteady.Program.Main(String[] args)


text:
Q: Tcl - numbering in loop error I have the following loop :
for {set i 1} {$i<=$nbrx} {incr i 1} {
    for {set j 1} {$j<=$nbry} {incr j 1} {

            node $numberer [expr ($i-1)*$dx] [expr ($j-1)*$dy]

        etc. etc.
    }
}

nbrx and nbry are very high valued variable (around 2000)
I give the following value to dx and dy = 0.1
I end up, on the fourth cycle (like i = 1 and j = 4) with the evaluation of
[expr ($j-1)*$dy] as being 0.30000000000000004
Then if the loops keep going in, at some point (always the same) I will have this kind of value with .000000000000004 or 0.000000000001 whilst most of the other value will be singled value (like I would expect them to be).
Any1 got a idea of why this is happening? Thanks for the help!


text:
Q: Is IE 11 the latest and available for Windows 8 Pro x64? I'm running Windows 8 Pro, x64, fully patched. It has Internet Explorer 10.0.9200.17116 installed. I checked Windows update and there are no updates available.
I had a popup spring from somewhere, and it stated to download the latest version of Internet Explorer. I think it may have come from the check box below (or then again, it may have been a phishing attempt):

I found it kind of odd, so I went to Microsoft's download for Internet Explorer 11 x64. Here's what Microsoft's download page told me:

There's a Next button available (not shown above), so I followed it. The next page presents me with:

The two pages confuse me. Is IE 11 the latest and available for x64 or not? If I attempt the download and install, will Microsoft corrupt this system so I have to reinstall?

A: Here the answer from Ramhound:

IE11 cannot be installed on Windows 8 only Windows 7 and Windows 8.1;
  if you want IE11 upgrade to 8.1; it's not possible to upgrade to IE11
  with Windows 8.0

A: Internet Explorer 11 is included in the Windows 8.1 or Windows RT 8.1 update
From:
http://windows.microsoft.com/en-gb/windows-8/browse-web-internet-explorer-tutorial

A: For things like internet Explorer, unless you are an early adopter, Windows Update will take care of that. There are no popups to install browser updates for any current browser - these are all scams. Even if there were popups that are not scams, there are always ways to install updates through the official sources, just the way you tried to do.
The screenshots explain what is going on - You can download Internet Explorer 11, but it won't run on your system. This is an option provided for people who want to download it from one machine and then install it on another machine, as explained in the first screenshot. The installer will not corrupt the system, it will simply refuse to install on a system that is not supported.
Now, here's the tricky part: Windows Update should handle Windows Updates, but in the case of the update from Windows 8 to Windows 8.1, it doesn't. That's the update for Windows 8 which includes Internet Explorer 11. This update you have to install through the Windows Store (go to the start screen, type "Store", click the green "store" icon). You'll find the update there and then you can download and install it. For detailed instructions see: http://windows.microsoft.com/en-us/windows-8/update-from-windows-8-tutorial
Be aware that the update from Windows 8 to Windows 8.1 is not available if you are running Windows 8 64 bit on a very old 64 bit CPU which is missing some required instructions from its instruction set.


text:
Q: Scroll a div based on a draggable element Here's basically what I want: I want to scroll up and down a div which contains a very long content by using another element binded with jquery draggable.

$("#controller").draggable({
    revert: false,
    containment: "parent",
    axis: "x",
    create: function(){
        $(this).data("startLeft",parseInt($(this).css("left")));
        $(this).data("startTop",parseInt($(this).css("top")));
    },
    drag: function(event,ui){
        var rel_left = ui.position.left - parseInt($(this).data("startLeft"));
        var rel_top = ui.position.top - parseInt($(this).data("startTop"));

    }
});

here's a fiddle for more information : http://jsfiddle.net/xNLsE/4/

A: This involves several steps:

*

*Determine the ratio of draggable width to scrollable height. In other words, you need to know how many pixels to scroll based on the distance the user has dragged.
This ends up looking something like this:
var $controller = $('#controller')
    // The total height we care about scrolling:
    , scrollableHeight = $('#timeline').height() - $('#timeline_wrapper').height()
    // The scrollable width: The distance we can scroll minus the width of the control:
    , draggableWidth = $('#horizontal_control').width() - $controller.width()
    // The ratio between height and width
    , ratio = scrollableHeight / draggableWidth
    , initialOffset = $controller.offset().left;

I also included initialOffset which we'll use later.

*Multiply the distance dragged times the ratio to position the scrollable element. You'll do this on drag of the draggable element:
$controller.draggable({
    revert: false,
    containment: "parent",
    axis: "x",
    drag: function (event, ui) {
        var distance = ui.offset.left - initialOffset;

        $('#timeline_wrapper').scrollTop(distance * ratio);
    }
});

Note that we have to take into account the initial offset of the scrollable control.
Example: http://jsfiddle.net/xNLsE/8/


text:
Q: Valgrind / Memory Errors I'm receiving the following errors repeatedly throughout my code when I use valgrind.  I'm not quite sure what these mean and I can't identify the uninitialized values.
==16795== Conditional jump or move depends on uninitialised value(s)
==16795==    at 0x4A06E8A: strcmp (mc_replace_strmem.c:412)
==16795==    by 0x4009C7: dictionary_add (libdictionary.c:44)
==16795==    by 0x40061B: main (part2.c:28)
==16795==
==16795== Invalid write of size 1
==16795==    at 0x4A082E7: strcpy (mc_replace_strmem.c:303)
==16795==    by 0x400AA8: dictionary_add (libdictionary.c:57)
==16795==    by 0x40061B: main (part2.c:28)
==16795==  Address 0x4c361a3 is 0 bytes after a block of size 3 alloc'd
==16795==    at 0x4A05E1C: malloc (vg_replace_malloc.c:195)
==16795==    by 0x400931: node_newnode (libdictionary.c:28)
==16795==    by 0x400A8C: dictionary_add (libdictionary.c:54)
==16795==    by 0x40061B: main (part2.c:28)

I'm creating a linked-list data structure and these are the functions being called when this memory error is given.
// Here are the constructions of both a node and the dictionary data struct.
typedef struct node
{
char* key;
char* value;
struct node* next;
}node;

typedef struct _dictionary_t
{
node* head;

} dictionary_t;

// First a new dictionary is created
void dictionary_init(dictionary_t *d)
{
d->head = NULL;
d->head = malloc(sizeof(node));
node_init(d->head);
}

// A new node is created using the node_init method.
void node_init(node *n)
{
n->key = NULL;
n->value =NULL;

n->key = malloc(sizeof(char));
n->value = malloc(sizeof(char));
n->next = NULL;
}

// This new node method is used after the original initialization (when we are adding new terms)  The previous one is specifically for creating a sentinel at the beginning of the structure upon creation.
void node_newnode(node *n, int x, int y)
{
n->key = NULL;
n->value = NULL;

n->key = malloc(x*sizeof(char));
n->value = malloc(y*sizeof(char));
n->next = NULL;
}

// This function is also being called to add "key" and "value" as a pair in this case.
int dictionary_add(dictionary_t *d, const char *key, const char *value)
{
node *current;
current =  d->head;
if(strcmp(current->key,key)==0)
        return -1;
while(current->next != NULL){
        current=current->next;
        if(strcmp(current->key,key)==0)
                return -1;
}
        current->next = NULL;
        current->next = malloc(sizeof(node));

        node_newnode(current->next,strlen(key),strlen(value));

        current = current->next;
        strcpy((current->key), key);
        strcpy((current->value),value);
        return 0;
}

Anyone have any ideas on why I'm getting those errors.  The main method has thus far only created a dictionary and called the add function.  Valgrind is reporting 45+ errors over 38 contexts over the course of 8 function calls.  I think these are probably small errors that I'm committing repeatedly.
I'm now also getting the same errors with this function.  A valgrind --track-origins=yes command traces it to a stack allocation in the following function:
int dictionary_parse(dictionary_t *d, char *key_value)
{
char* colon;
char* space;
colon = key_value;
space = key_value;

space++;

int key_length = -1; //Default key length to check for failure

int i=0;
int j=0;   // Loop variables
int k=0;

int length = strlen(key_value);

for(i=0;i<length-2;i++){
        if(*colon == ':' && *space == ' '){
                key_length = i;
                break;
        }
        colon++;
        space++;
}

if(key_length == -1 || key_length == 0)
        return -1;

int value_length = length-2-key_length;

colon = key_value;

char key_word[key_length];
key_word[0] = '\0';
char value_word[value_length];
value_word[0] = '\0';

for(j=0;j<key_length;j++){
key_word[j] = *colon;
colon++;
}

space++;

for(k=0; k<value_length;k++){
value_word[k] = *space;
space++;
}

char* finalkey[key_length];
strcpy((char*)finalkey,key_word);
char* finalvalue[value_length];
strcpy((char*)finalvalue,value_word);

dictionary_add(d,(char*)finalkey,(char*)finalvalue);

return 0;

}

Thanks,
-newprogrammer

A: The first error ("Conditional jump or move depends on uninitialised value(s)") is because the character pointed to by current->key was never initialised.  You allocated a byte for it in node_init(), but you never actually set that byte to anything.  If you want the head node's key to act like an empty string, change node_init() like this:
n->key = malloc(sizeof(char));
n->key[0] = '\0';

The second error ("Invalid write of size 1") is because your node_newnode() function is allocating one byte less than is needed for the strings.  strlen(key) counts the actual characters in the string, but one more byte is needed for the null terminator character.  Use:
node_newnode(current->next,strlen(key) + 1,strlen(value) + 1);

(but personally I would just pass key and value to node_newnode(), and have it do both the allocation and the strcpy()).


text:
Q: Set of points at which a function coincides with its convexification is compact? Let $f:[0,1]\rightarrow\ \mathbb{\bar{R}}$, and let $\tilde{f}$ be the convexification of $f.$ (i.e., $\tilde{f}$ is the pointwise supremum of all affine functions that lie everywhere below $f$.) Let $X\subseteq[0,1]$ be the set of points at which $f(x)=\tilde{f}(x).$ Is $X$ a compact set?

A: If $f$ is general, then $X$ may not be compact. Pick an arbitrary, strictly convex function $g$ with $g(0.5) = 0$, and define $f(x) = g(x)$ for $x \neq 0.5$ and $f(0.5) = 1$. You have $\tilde f = g$ and $X  = [0,1]\setminus \{0.5\}$ which is not compact.
If $f$ is continuous, then the result is true, because if $\tilde f(x)<f(x)$ then this happens on a whole neighborhood of $x$ (by the continuity of $f,\tilde f$). This means that $[0,1]\setminus X$ is open, and thus, $X$ is compact.


text:
Q: как на electron js сделать вкладки? Я делаю обертку для сайта на electron js через
const site_first = "https://github.com"
const site_second = "https://www.electronjs.org/"
const site_third = "https://developer.mozilla.org/ru/"
const win = new BrowserWindow({ width: 800, height: 800 })
win.loadURL(site_first)

как сделать между ними переключение через похожий интерфейс:

я видел способ через bootstrap, но он только для html что мне не подходит.
Подскажите пожалуйста как это можно сделать.


text:
Q: Prove that $\sup_{x,x'\in\mathsf{X}} |f(x) - f(x')| = 2 \inf_{c\in\mathbb{R}} |f - c|_\infty$. I would like to prove that $\sup_{x,x'\in\mathsf{X}} |f(x) - f(x')| = 2 \inf_{c\in\mathbb{R}} |f - c|_\infty$ where $f$ is a bounded function on $X$ and $|f|_\infty = \sup_{x\in\mathsf{X}} |f(x)|$.
The steps I followed: I wrote the supremum as,
\begin{align*}
\sup_{x'\in \mathsf{X}} \sup_{x\in \mathsf{X}} |f(x) - f(x')|
\end{align*}
so essentially I have,
\begin{align*}
\sup_{x'\in \mathsf{X}} |f - f(x')|_\infty
\end{align*}
But I couldn't see how to continue to to an infimum and with a $2$ factor. Thanks in advance!

A: Here is my own answer. I'd be grateful if someone points out a flaw. It is a bit long, I think that it can be made shorter.
Left hand side. Starting from the left hand side. We see that for all $x,x'\in\mathsf{X}$, we have straightforwardly (I omit $\mathsf{X}$ from the notation),
\begin{align*}
|f(x) - f(x')| &= \max\{f(x) - f(x'),f(x')-f(x)\} \\ &\leq \max\{\sup_x f(x) - \inf_x f(x), \sup_x f(x) - \inf_x f(x)\}
\end{align*}
for all $x,x'$, hence,
\begin{align*}
\sup_{x,x'} |f(x) - f(x')| \leq \sup_x f(x) - \inf_x f(x)
\end{align*}
For the other direction, choose $x,x'$ s.t. $f(x) \geq \sup_x f(x) - \epsilon/2$ and $f(x') \leq \inf_x f(x) + \epsilon/2$. Then,
$$|f(x) - f(x')| \geq \sup_x f(x) - \inf_x f(x) - \epsilon$$
Taking $\sup$ of LHS preserves the inequality, $\epsilon$ is arbitrary, hence we have the other direction $\sup_{x,x'} |f(x) - f(x')| \geq \sup_x f(x) - \inf_x f(x)$. So we have shown,
$$\sup_{x,x'} |f(x) - f(x')| =\sup_x f(x) - \inf_x f(x)$$
Right hand side. The strategy here is to show that,
\begin{align*}
\inf_{c\in\mathbb{R}} \sup_x |f(x) - c| = \frac{\sup_x f(x) - \inf_x f(x)}{2}.
\end{align*}
For $\leq$ direction, pick $c_\star = \frac{\sup_x f(x) + \inf_x f(x)}{2}$.
\begin{align*}
|f(x) - c_\star| &= \max\{f(x) - c_\star, c_\star - f(x)\} \\
&\leq \max\{\sup_x f(x) - c_\star, c_\star - \inf_x f(x)\} \\
&=\frac{\sup_x f(x) - \inf_x f(x)}{2}
\end{align*}
True for also $\sup$. Since it is true for $c_\star$, infimum should be at least smaller, so we have,
\begin{align*}
\inf_c \sup_x |f(x) - c_\star| &\leq \frac{\sup_x f(x) - \inf_x f(x)}{2}
\end{align*}
For $\geq$ direction, we have,
\begin{align*}
|f(x) - c| \geq \min\{f(x)-c,c-f(x)\}
\end{align*}
Take supremums of both sides over $x$,
\begin{align*}
\sup_x |f(x) - c| \geq \min \{\sup_x f(x) - c, c - \inf_x f(x)\}
\end{align*}
If $c \geq c_\star$, then,
\begin{align*}
\sup_x |f(x) - c| \geq \sup_x f(x) - c\geq \frac{\sup_x f(x) - \inf_x f(x)}{2}
\end{align*}
but if $c \leq c_\star$, then
\begin{align*}
\sup_x |f(x) - c| \geq c - \inf_x f(x) \geq \frac{\sup_x f(x) - \inf_x f(x)}{2}
\end{align*}

A: Hint: Approximate the term on the left by $|f(a) - f(b)|$ and set $c = \frac{f(a)+f(b)}{2}$. Similarly, approximate the term on the right by $f(a) - c$ and $c-f(b)$ for the other direction.


text:
Q: Using jquery to set php variable value? I currently have 2 pages:

*

*Follow.php:a PHP page which is all setup with twitters api and will follow any user on twitter with the specific parameter you put in.

*One index.php page, which has a list of links of people you can follow.
What I am looking to do is have it so when a user clicks on one of the people to follow on index.php, the variable in follow.php (which is used as a parameter and is the username of twitter account that is going to be followed) gets set to the name attribute of the link selected.
Now I am not the greatest developer, so I am not sure of the best way of doing this.  There is probably a better way of doing it that what I am thinking of.  I was thinking of using jquery to say something like:
$('a').click(function(){
<?php $group=?>$(this).attr('name'); //trying to set a php variable to name attr
})

This was going to be in its own new file,
then I was going to include this script into the follow.php script and use the variable.  This is not working, unsurprisingly.  I hope I explained what I was trying to do well.
So I have two questions.
Number 1:what is the best way of achieving what I am trying to do?  can i do this all in php?
Number 2: is it possible to do what I was trying to do with jquery and setting the php var equal to the name attr?

A: PHP runs on the server. JavaScript (jQuery) runs on the browser. PHP can be used to write JS, but JS can't affect PHP (except via AJAX or similar).

A: What you need to do is do a POST on the Follow.php page and accept the username value. This is a great resource for that: http://www.html.net/tutorials/php/lesson10.php
You can simply set the link href for each  tag on the index page to go got Follow.php?user=twitterHandle (where twitterHandle is the twitter username of a person). This way, you dont need to use any javascript at all.


text:
Q: how nodejs http.request send json params to java interface we have a java interface to send verify_code to the phone,and it was woking fine on postman。

my nodejs code as below
let test = {
        "phoneNumber": "15021071273",
        "smsParams": [
            "注册",
            "123456",
            "注册"
        ],
        "tmplId": 109341
    }

    var content = JSON.stringify(test);

    // An object of options to indicate where to post to
    var post_options = {
        host: '172.16.211.33', //'common-message'
        port: '10011',
        path: '/sms/sendTecentyunSms',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': content.length
        }
    };

    // Set up the request
    var post_req = http.request(post_options, function (res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('Response: ' + chunk);
        });
    });

    // post the data
    post_req.write(content);
    post_req.end();

and the java interface reponses:

Response: {"timestamp":1572935973619,"status":400,"error":"Bad Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"JSON parse error: Unexpected end-of-input within/between Object entries; nested exception is com.fasterxml.jackson.core.io.JsonEOFException: Unexpected end-of-input within/between Object entries\n at [Source: java.io.PushbackInputStream@3e497877; line: 1, column: 157]","path":"/sms/sendTecentyunSms"}

looks like it's just a json parsing error.
I also tried to JSON.stringy the tese.smsParams first,not working
req.write only accept a string or a buffer,so it can't just put a json object as a param。

A: Please try this way
var http = require('http')

var body = JSON.stringify({
        "phoneNumber": "15021071273",
        "smsParams": [
            "注册",
            "123456",
            "注册"
        ],
        "tmplId": 109341
    })

var request = new http.ClientRequest({
    hostname: "172.16.211.33",
    port: 10011,
    path: "/sms/sendTecentyunSms",
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "Content-Length": Buffer.byteLength(body)
    }
})

request.end(body)

request.on('response', function (response) {
  console.log('STATUS: ' + response.statusCode);
  console.log('HEADERS: ' + JSON.stringify(response.headers));
  response.setEncoding('utf8');
  response.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

A: Try this:

    var content = JSON.stringify(test);

    // An object of options to indicate where to post to
    var post_options = {
        host: '172.16.211.33', //'common-message'
        port: '10011',
        path: '/sms/sendTecentyunSms',
        body:content,
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': content.length
        }
    };

Or try the request module
const request = require('request');

let test = {
    "phoneNumber": "15021071273",
    "smsParams": [
        "注册",
        "123456",
        "注册"
    ],
    "tmplId": 109341
}

var content = JSON.stringify(test);

// An object of options to indicate where to post to
var post_options = {
    method: 'post',
    url:"http://172.16.211.33:10011/sms/sendTecentyunSms",
    body:content
};

request(post_options,(err, res, body) => {
  if (err) { return console.log(err); }
  console.log(body.url);
  console.log(body.explanation);
});

you can play with it here


text:
Q: How to show a dialog after the user select a row of a ? I have this datatable:
<h:form id="form">
<p:dataTable id="tblInfo" var="ref" value="#{consultasBean.listaRefacciones}" paginator="true" rows="10" selectionMode="single" selection="#{consultasBean.refaccionSeleccionada}" rowKey="#{ref.idRefaccion}">
       <p:column headerText="Equipo">
          <h:outputText value="#{ref.equipo}" />
       </p:column>
       <p:column headerText="Marca">
          <h:outputText value="#{ref.marca}" />
       </p:column>
       //More colums here...
</p:dataTable>

And I want to show this dialog after the user select a row:
<p:dialog id="myDialog" widgetVar="refaccionDialog" header="Detalle Refaccion" resizable="false" width="300" showEffect="explode" hideEffect="explode">
     <h:panelGrid id="display" columns="2" cellpadding="4">
          <h:outputText value="Info:" />
          <h:outputText value="#{consultasBean.refaccionSeleccionada.equipo}" />
     </h:panelGrid>
     //More things here...
 </p:dialog>

And this is part of my bean (viewscoped):
private List<RefaccionBean> listaRefacciones = null;
private RefaccionBean refaccionSeleccionada = null;
// setters and getters...

listaRefacciones already has info, so dont worry about how it gets it.
I know i have to use p:ajax but just dont know how.
I was checking this (example 1 is what i want) but the info is too old and does not work now.
Please help me.

A: Just include a p:ajax inside your table
<p:ajax event="rowSelect" oncomplete="PF('refaccionDialog').show()" update=":dialogId" />

Hope this helps.

A: rowKey attribute of datatable is wrongly written.
it should be like as follows
  rowKey="#{ref.idRefaccion}"

The datatable code should as follows
   <h:form id="form">
   <p:dataTable id="tblInfo" var="ref" value="#{consultasBean.listaRefacciones}" paginator="true" rows="10" selectionMode="single"
      selection="#{consultasBean.refaccionSeleccionada}" rowKey="#{ref.idRefaccion}">
   <p:column headerText="Equipo">
      <h:outputText value="#{ref.equipo}" />
   </p:column>
   <p:column headerText="Marca">
      <h:outputText value="#{ref.marca}" />
   </p:column>
   //More colums here...
   </p:dataTable>


text:
Q: Regular line pattern of flat pixels after using gdalwarp I observe a regular pattern of flat pixel bands on a DEM reprojected using gdalwarp:

The red line represents a profile for which the following graph is an extract between the two squared dots, so it crosses two flat pixel bands that are clearly visible:

I simply reprojected an original WGS84 DEM to the UTM of the region with:
$ gdalwarp -t_srs EPSG:23032 input_dem.tif reprojected.tif;

The green line is the profile of the original WGS84 DEM, it's super smooth and it doesn't show the flat pixels pattern.
Is this a known issue? And what could I do to avoid this pattern?
Info:
The version of GDAL I use is from this Docker image ubuntu-small-latest available at https://hub.docker.com/r/osgeo/gdal
# gdalinfo --version
GDAL 3.3.0dev-33cf0e31a992be112b3091f012368d15605ed51d, released 2021/03/17

A: I went through a lot of posts to figure out that, indeed, using the nearest neighbor interpolation method, in the case of a continuous raster such as a DEM, is not really a good idea. And that there is a mix between a "divinatory art" and an accumulated knowledge when it comes to applying filters.
In my case, the resulting re-projected raster is suffering some aliasing effects. I cannot explain why the repetitive pattern spacing is ~80 meters, which is not really 'near' (as in 'nearest neighbor'). And when I look closer (well, actually further), there is actually another pattern, oriented differently, with a much greater wavelength of roughly 650m.
Anyway, here are some great posts and answers out there that are worth reading imho:
Deciding what interpolation method to use for resampling raster data?
What resampling technique should be used when projecting aerial photos?
Pros and Cons of using Bilinear Interpolation and Cubic Convolution when dealing with DEMs?
Best Resampling Method for DEM reprojection in QGis
What resampling technique should be used to reproject an altitude raster?
What is the source of horizontal and vertical striping in USGS DEMs?
Why do "stripes" appear on raster?
What is Lanczos resampling useful for in a spatial context?
Based on all these, I randomly decided to chose the bilinear interpolation when reprojecting my raster DEM. I was hesitating with the cubic or cubicspline offered by the -r flag of gdalwarp as they also seem to be nice candidates. I also wanted to test the gaussian filter, but it doesn't seem to be available with gdalwarp.
The Lanczos method also looks great, but I prefer to avoid it when dealing with DEMs in order to not create altitudes that will extend out of the min-max range of the original DEM.
Here is a new line in blue, smoother and closer to the original DEM profile (green), representing the output result using the bilinear interpolation when re-projecting the DEM:


text:
Q: in case of violation in saveAll() in spring boot hibernate I am currently working on a Spring Boot Hibernate.
I need to save a list of objects in mySql database,
I read about the difference between saving using saveAll() and foreach save() and I can conclude that saveAll() is much faster. However, in case of exception say UK violation for example, the whole process rollback, and no object will be saved.
To be more simple: I want to save a list of object in one transaction, and in case of any constraint violation, ignore it and save the rest.
this is my entity:
package com.entity;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
@Transactional
public class Page {

@Id
@GeneratedValue(generator = "page_sequence-generator")
@GenericGenerator(
        name = "page_sequence-generator",
        strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
        parameters = {
                @Parameter(name = "sequence_name", value = "page_sequence"),
                @Parameter(name = "initial_value", value = "1"),
                @Parameter(name = "increment_size", value = "1")
        }
)
private long id;

@Column(nullable = false, unique = true)
private String url;

private boolean isPageConsumed;

public Page() {
}

public Page(String url, boolean isPageConsumed) {
    this.url = url;
    this.isPageConsumed = isPageConsumed;
}

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public String getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}

public boolean isPageConsumed() {
    return isPageConsumed;
}

public void setPageConsumed(boolean pageConsumed) {
    isPageConsumed = pageConsumed;
}

@Override
public String toString() {
    return "Page{" +
            "id=" + id +
            ", url='" + url + '\'' +
            ", isPageConsumed=" + isPageConsumed +
            '}';
}
}

And this is my repository:
@Repository
public interface PageRepository extends CrudRepository<Page, String> {

@Query(value = "SELECT p FROM Page p where p.isPageConsumed = '0'")
public Page findFirstPage();

}

Thank you :)

A: You could use Spring's @Transactional(noRolbackFor={SomeException.class}) on the controller method that invokes saveAll().


text:
Q: Convergence of $n^2/n!$ im trying to solve a simple excercise but i can't solve it, it says:

Prove that $$\lim_{n\to\infty}\frac{n^2}{n!}$$ converges to 0.

I can't see how i can make
$$|\frac{n^2}{n!}-0|<\epsilon$$
i was doing a similar probem for $\frac{2^n}{n!}$, where you can control $\left(\frac{2}{3}\right)^{n-2}$, but i can't find a way to control the inequality in this exercise, any help would be appreciated.

A: Hint:
$$
\begin{align}
\lim_{n\to\infty}\frac{n^2}{n!}
&=\lim_{n\to\infty}\frac{n^2}{n(n-1)}\frac1{(n-2)!}\\
&=\underbrace{\lim_{n\to\infty}\frac{n^2}{n(n-1)}}_1\underbrace{\lim_{n\to\infty}\frac1{(n-2)!}}_0
\end{align}
$$

A: Observe that $\frac{n^2}{n!}=\frac{nn}{(n-1)!n}$,so it's enough to prove that $lim_{n\to\infty}\frac{n}{(n-1)!}=0$ and that is true simply because $n<(n-1)!$ for all $n>3$
Edit: As pointed out by robjohn, the fact that $n<(n-1)!$ is not enough. It could be the case that $\frac{n}{(n-1)!}=c<1$ for some constant $c$ but this is not the case because the distance between the numerator and the denominator goes to infinity as $n$ goes to infinity. To see that observe that: $$(n-1)!-n=(n-1)!-(n-1)-1=(n-1)((n-2)!-1)-1$$ and $(n-2)!$ goes to infinity, so does $(n-2)!-1$, and also $n-1$ goes to infinity, so $(n-1)((n-2)!-1)-1$ goes to infinity


text:
Q: Retrieve selected text from select I'm using VueJS 2 (with this template) and below is what I've done so far:
<template>
     <select id="dropDown" v-model="mytrack">
           <option value="">Select track</option>
           <option v-for="track in tracksList" :value="track.circuitId">{{ track.name }}</option>
     </select>
     <button type="submit" @click="retrieveByTrack(track.circuitId)">
                                Search
     </button>
</template>

I want to be able to select an option from the select element and when I click the submit button I should call retrieveByTrack(track.circuitId) method passing the option value selected in the select element.

A: Simple like that.
I created fiddle for you:
https://jsfiddle.net/npw7fgta/

{{ $data |json }}

  <select v-model='result'> <option v-for="task in tasks" :value="task.id">{{ task.name }} </option> </select>

And JS:
var vm = new Vue({
  el: "#app",
  data: {

    tasks: [
    { id: 0 , name: 'First task'},
    { id: 5, name: 'fifth task'}
    ]

  }
});

Then you have task/track.id available in result so you can do whatever you want.


text:
Q: "Method foo() needlessly boxes a boolean constant" Sonar warning We have a bunch of these messages being reported in our Java code by SonarQube's analyzers.

Method foo(String, String) needlessly boxes a boolean constant

In many cases it is returning true for Boolean return type method.
I am wonder to what extent is this a (performance?) problem with Oracle Java 8 in 2017? Does it really end up creating new Boolean instance or does it optimize into Boolean.TRUE auto-magically?
UPDATE
The Sonar rule key is fb-contrib:NAB_NEEDLESS_BOOLEAN_CONSTANT_CONVERSION.

A: The reasoning behind this issue is that you are invoking a method for no good reason. How can we verify this :
Let's take this (complicated ;)) code
  Boolean foo(String s) {
   return true;
  }

What can be done is decompile this. This gives us the following bytecode instruction (simplified a bit for brevity)
ICONST_1
INVOKESTATIC java/lang/Boolean.valueOf (Z)Ljava/lang/Boolean;
ARETURN

As you can see there is a method invocation to create a Boolean from constant 1.
If we now change the code to something like:
  Boolean foo(String s) {
   return Boolean.TRUE;
  }

bytecode generated is :
GETSTATIC java/lang/Boolean.TRUE : Ljava/lang/Boolean;
ARETURN

Which is getting a static constant and returning it which should be more efficient.


text:
Q: Android Studio's review layout did not show text. Why this happen?

This problem happen after android studio suddenly close itself. I feel relieve when i see the interface output can show it's text but, it annoy me when i try to codes the interface and there is no text shown there. How can i solve this problem and what make this problem occur?

A: I already solve this problem by use the new render layout. I kind a hesitate to use it at first because i have face this problem before and it is also render problem. No matter how many time i change my codes according to suggestion and change the render layout. Still nothing works. I need start from scratch because i can't find the solution. But this time it's work.


text:
Q: Ruby on Rails - Bootstrap / Form_for vs input_groups - How to stop styles butting heads I'm playing around with some of the input boxes for my rails project.
I'm a bit taken with the first example given here. I like the little '@' notch and could use that for a formatting prompt to our users.
Their code looks like this:

  @
  <input type="text" class="form-control" placeholder="Username">

If i put that into my rails view it works perfectly and looks great.
But my form setup is running with a form_for function, and I'm having difficutly getting the two to play nicely.
My rails html.erb code looks like this below:

    <%= form_for @request do |f| %>
      <%= render 'shared/error_messages' %>
      <%= f.label :user_id%>
      <%= f.text_field :user_id%>
      <%= f.submit "Begin my request", class: "btn btn-primary" %>
    <% end %>

I've tried wrapping the two pieces of code together in various ways but to no effect!
General constants is that my rails code always comes out with hard rectangular edges (compared to the bootstrap smooth curves), I cannot get the input-group-addon to sit comfortably on the end of the input field, it variously rides above and below or sits awkwardly over the larger form block etc... so fail on my part. Anyone got any insight?
In terms of gems pertinent to bootstrap I'm using:
gem 'bootstrap-sass',       '3.2.0.0'
gem 'sass-rails',           '5.0.0.beta1'

A: The problem you are running into is form_for is using the rails FormBuilder to generate your form and the method text_field is translating to a specific piece of html. You can have it create a different piece of html by creating your own form builder. If you opt to use another gem like simple_form it gets even easier as you can just create additional types of fields. You can look over the documentation for that gem for more information.
class CustomFormBuilder < ActionView::Helpers::FormBuilder
  def text_field_with_addon(name, addon, *args)
    @template.content_tag(:div,
      @template.content_tag(:span, addon, class: 'input-group-addon') +
      @template.text_field(name, *args),
      class: 'input-group')
  end
end

Then use it like:
<%= form_for @request, builder: CustomFormBuilder do |f| %>
  <%= render 'shared/error_messages' %>
  <%= f.label :user_id%>
  <%= f.text_field_with_addon :user_id, '@' %>
  <%= f.submit "Begin my request", class: "btn btn-primary" %>
<% end %>


text:
Q: Geolocalisation on iPhone app iam developing iPhone application that allow user to define stations near to him, so that, the application should locate the user automatically, iam looking for module that i can integrate in my application to do so (geolocalisation), thx for help. Cordially.

A: You should look at CoreLocation Framework and LocateMe sample.


text:
Q: Reading in a file, loading correctly but not formatting correctly I can't figure out why I'm getting an error when I try to format my file in a certain way. The following code loads my file correctly, but it loads it as a 12x1 array.
disp(strcat('Navi_Endo_RefHomMat_', num2str(i), '.txt'))
Navi_HomMat_File_ID = fopen(strcat('Navi_Endo_RefHomMat_', num2str(i), '.txt'));
Navi_Endo_RefHomMat(i,:) = textscan(Navi_HomMat_File_ID,'%f');
fclose(Navi_HomMat_File_ID);

I want it to load as a 3x4 array though. When I try doing the following, I get an error "Assignment has more non-singleton rhs dimensions than non-singleton subscripts"
disp(strcat('Navi_Endo_RefHomMat_', num2str(i), '.txt'))
Navi_HomMat_File_ID = fopen(strcat('Navi_Endo_RefHomMat_', num2str(i), '.txt'));
Navi_Endo_RefHomMat(i,:) = textscan(Navi_HomMat_File_ID,'%f %f %f %f');
fclose(Navi_HomMat_File_ID);

My text file looks like this
   7.8466354e-01  -9.7684133e-02  -6.1201847e-01  -1.6701139e+01
   4.6962973e-01   7.3803591e-01   4.8431043e-01  -2.0213967e+02
   4.0442146e-01  -6.6750767e-01   6.2504598e-01  -1.7367594e+02
   0.0000000e+00   0.0000000e+00   0.0000000e+00   1.0000000e+00

I know I could easily change my variable my reshaping it to get a 3x4, but I want to read it in correctly without having to do that. Thanks!

A: Try to use this line:
Navi_Endo_RefHomCell = textscan(Navi_HomMat_File_ID, '%f %f %f %f');

You will end up with a cell Navi_Endo_RefHomCell but you can use cell2mat to solve this.


text:
Q: Observing a input textbox I have an input textbox and two buttons, one "Clear" and the other "Save", implemented in xul in a typical layout like this:
<textbox id="inputTextbox" placeholder="Enter here a new entry" value = ""
             oninput="enableBtns(event);"/>

<button id="clearBtn" label="Clear" accesskey="C" disabled="true"
           oncommand="clearField();"/>

<button id="saveBtn" label="Save" accesskey="S" disabled="true"
           oncommand="saveEntry();"/>

I want to do this: Initially the buttons are disabled. When I put some text in the textbox, the buttons become enabled. If I press one of them, the text is cleared or saved accordingly and the buttons become disabled again.
I can accomplish this functionality easily with the "oninput" attribute, using this code in my js:
enableBtns: function(event) {
  document.getElementById("clearBtn").disabled = !document.getElementById("inputTextbox").value;
  document.getElementById("saveBtn").disabled = !document.getElementById("inputTextbox").value; },

My problem now is how to achieve the same functionality for the button status, without the use of "oninput" attribute but making use of an observer.
So, how do I register an observer when the dialog pane loads, to monitor the textbox for input entry and change the status of the buttons? (if the textbox is not empty)
I have read many related articles on MDN but in all cases they mention situations and examples where the observer is used to monitor for changes in extension's preferences. I want to use the observer dynamically as a "sensor" for changes in the textbox. How can i do it..??
Any info, resources and sample code to work on it, will be very appreciated!
Thank you

A: (This answer is assuming that you are developing a Firefox extension, something your question doesn't quite make clear).
I think you might not be seeing the forest for the trees. You mention wanting to have an "observer" for your text input, but using the "oninput" event is an observer of sorts (it's technically called an event listener). This is the recommended way to operate on XUL controls, and does everything I think you want it to. All you need to do is to handle the special cases that your buttons introduce:
clearField: function() {
  document.getElementById("inputTextbox").value = "";
  enableBtns(); // This magically takes care of our button status!
}

saveEntry: function() {
  var value = document.getElementById("inputTextbox").value;
  // 1. Do something with the value here (save it wherever you want)
  // 2. Now you need to decide; do I want to leave the value in the textbox?
  //    Or do I want to clear the textbox? Either way, let's do that next.

  // 2a. If we clear the text box, I might simply call clearField() so it can do
  //     all the work for me.

  // 2b. If we leave the text box alone, you'll need to disable the buttons
  //     manually at this point. Pretty easy.
}

I believe the above solution will work for nearly every possibility. The one possibility it may not work for (and you would have to test this; I can't remember exactly how the oninput event gets fired), is if something other than the user modifies the text in the control (i.e. you're scraping data from a page URL). In that case, you would have to do all of your control updates from wherever you're scraping the data. But again, your question does not make it clear if that's your end goal.
One response question I might ask is why do you not want to use the oninput event?

A: If you're including jQuery on your page, then you can use jQuery's change handler:
$('#inputTextbox').change(function(){
  var disableButtons = $(this).val() == '';
};

http://api.jquery.com/change/
One possible issue you may have with that is it will only fire when the user de-focuses out of the textbox. If you want to immediately react to any keystrokes within the textbox, jQuery's keydown handler might be the better choice:
$('#inputTextbox').keydown(function(){
  // your code here
};

http://api.jquery.com/keydown/
And in order to bind this at the time the window loads, you would wrap it in jQuery's DOM-ready handler:
$(function(){
    // your code here
});

http://api.jquery.com/ready/


text:
Q: Question about the use of 'unlike'
*

*The moon is not a magnet the way the earth is.

*Unlike the earth, the moon is not a magnet.

The first sentence is from an article on science. Can I rewrite the sentence as the second? Please explain it to me.

A:

*

*The moon is not a magnet the way the earth is.

*Unlike the earth, the moon is not a magnet.

Regardless of scientific validity, the two sentences  differ in meaning.
1 says that the Moon is a magnet, but, comparing the ways the Moon and the Earth are magnets, the Moon is not a magnet like the Earth is a magnet; or the Moon is not magnetic to the degree that the Earth is a magnet. 2 says that the Earth is a magnet and the moon is not.
So, 1 and 2 are not equivalent.
I think you are reading 1 as "the moon is not a magnet, but the Earth is", which is in fact equivalent to 2. However, I think that reading of 1 is not entirely correct.

A: It works, but it's a bit awkward. Perhaps consider beginning the sentence with "Unlike the Earth..." Also Moon and Earth should be capitalized as they are proper nouns, and it sounds a little funny to be calling them "magnets." Better to call them "magnetic."

Unlike the Earth, the Moon is not magnetic.

A: In fact, both moon and earth are giant magnets.
"The magnetic field of the Moon is very weak in comparison to that of the Earth. Other major differences are that the Moon does not currently have a dipolar magnetic field (as would be generated by a geodynamo in its core) and the varying magnetization that is present is almost entirely crustal in origin."
(from https://en.wikipedia.org/wiki/Magnetic_field_of_the_Moon)
So, in my opinion, sentence 1 is scientifically correct.


text:
Q: Reactive Extensions(RX) Rotation angle We have all seen the nice RX handling of mouse drag n drop.
I want something similar but outputting the change in angle to the centre of the screen.
Like if the user hits the mouse button and circles the screen twice I would get values from 0 to 720 degrees.
Essentially rotating the thing on screen.
How would one do that?

A: This will give you the angle in radians from the center of the object. It will only operate in the range (-Pi, Pi] however. If you rotate three times, you won't get a value higher than a single rotation.
var mousedown = from evt in Observable.FromEventPattern<MouseButtonEventArgs>(this, "MouseDown")
        select evt.EventArgs.GetPosition(this);

var mouseup = from evt in Observable.FromEventPattern<MouseEventArgs>(this, "MouseUp")
              select evt.EventArgs.GetPosition(this);

var mousemove = from evt in Observable.FromEventPattern<MouseEventArgs>(this, "MouseMove")
                select evt.EventArgs.GetPosition(this);

Vector center = new Vector(this.Width / 2, this.Height / 2);

var radian = from start in mousedown
        from pos in mousemove.StartWith(start).TakeUntil(mouseup)
        select Math.Atan2((pos - center).Y, (pos -center).X);

EDIT
If you are after the change in angle, the following should work:
var angle = from start in mousedown
            from pos in mousemove.StartWith(start).TakeUntil(mouseup)
            select Vector.AngleBetween(pos - center, start - center);

A: Thanks for your help. Ive figured out the last bit myself:
        var down = Observable.FromEventPattern<MouseButtonEventArgs>(this, "MouseDown").Select(e=>e.EventArgs.GetPosition(this));

        var move = Observable.FromEventPattern<MouseEventArgs>(this, "MouseMove").Select(e => e.EventArgs.GetPosition(this));

        var up = Observable.FromEventPattern<MouseEventArgs>(this, "MouseUp").Select(e => e.EventArgs.GetPosition(this));

        Vector center = new Vector(this.Width / 2, this.Height / 2);

        var f = from start in down
                from pos in move.StartWith(start).TakeUntil(up).Buffer(2, 1)
                where pos.Count == 2
                select  Vector.AngleBetween(new Vector(pos[0].X, pos[0].Y) - center, new Vector(pos[1].X, pos[1].Y) - center);

        f.ObserveOnDispatcher().Subscribe(p => {
            game.Player.Angle += p;
        });


text:
Q: FTP: Creating Nested Directories Automatically We are trying to move a file to an FTP site. We need to create a folder structure like this:

/deeply/nested/folder/structure/index.html

Yesterday, we realized we can't create more than one folder at a time, so this doesn't work:

MKD /deeply/nested/folder/structure

So, in code, we wrote a loop that created each folder, one at a time, ignoring errors caused by the folder already existing. Ignoring errors is gross.
Is a way to create these nested folders in one action, rather than multiple? Is there a command to see if a folder already exists? If we just push the file out including the full path, will FTP be smart enough to create the directories for me?

A: No, there's no standard way to create a folder with subfolders. There's also no standard way to check if directory exists. You would need to use LIST or MLSD (where supported) and parse the result for this. Can't you just use some third-party component that supports the needed functionality?

A: I wrote a simple C# example here, maybe someone will need this code.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;

namespace Deployer
{
    public class RecursiveFolderUploader
    {
        private const string SrcFullPath = @"C:\prg\Snowinmars\Snowinmars.Ui";
        private readonly IList<string> foldersOnServer;
        private Client ftpClient; // that's your ftp client, init it

        public RecursiveFolderUploader()
        {
            this.foldersOnServer = new List<string>();
        }

        private void UploadAll(DirectoryInfo directoryInfo)
        {
            // ftp://login:password@127.0.0.1/path/to/root/mydir/anotherdir/file.dat
            // ^________________uri_______________________^_relevationPath_^
            foreach (var file in directoryInfo.EnumerateFiles())
            {
                if (!file.Directory.FullName.StartsWith(RecursiveFolderUploader.SrcFullPath))
                {
                    throw new InvalidOperationException($"File {file.FullName} is not from {RecursiveFolderUploader.SrcFullPath} folder");
                }

                string relevationPath; // all folders from root up to file

                if (file.Directory.FullName.Length == RecursiveFolderUploader.SrcFullPath.Length)
                {
                    relevationPath = "";
                }
                else
                {
                    relevationPath = file.Directory.FullName.Substring(RecursiveFolderUploader.SrcFullPath.Length, file.Directory.FullName.Length - RecursiveFolderUploader.SrcFullPath.Length);

                    if (relevationPath.StartsWith("\\"))
                    {
                        relevationPath = relevationPath.Remove(0, 1);
                    }
                }

                string destination;
                if (string.IsNullOrWhiteSpace(relevationPath))
                {
                    destination = file.Name;
                }
                else
                {
                    destination = Path.Combine(relevationPath, file.Name).Replace("\\", "/");
                }

                try
                {
                    ftpClient.UploadFile(file.FullName, destination);
                }
                catch (WebException e)
                {
                    // that means that there's no such folder or something else goes wrong
                    // we can check it by creating folders and try again
                    var parts = relevationPath.Replace("\\", "/").Split('/');

                    for (int i = 1; i <= parts.Length; i++)
                    {
                        var path = string.Join("/", parts.Take(i));

                        if (!foldersOnServer.Contains(path))
                        {
                            ftpClient.MakeDirectory(path);
                            foldersOnServer.Add(path);
                        }
                    }

                    try
                    {
                        ftpClient.UploadFile(file.FullName, destination);
                    }
                    catch (Exception innerE)
                    {
                        // if it doesn't help - trouble isn't in folders
                        throw new WebException($"Can't find folder {relevationPath}", innerE);
                    }
                }
            }

            foreach (var directory in directoryInfo.EnumerateDirectories())
            {
                UploadAll(directory);
            }
        }
    }
}


text:
Q: Visualforce email template in different languages I developed a Visualforce emailtemplate and used all the custom labels to translate into different languages.
the subject is coming as ??????? for all the languages except for english, but in preview i can able to see the subject in translated language .we are using the outlook as the mail-box.

A: https://help.salesforce.com/apex/HTViewSolution?id=000005102&language=en_US
Check encoding, Go to your template -> Edit -> Encoding -> select Unicode (UTF-8)
It has to work.


text:
Q: Jquery run function after append I have a table where I append table data. Part of that data is a checkbox. I need to check the box if the variable (inspectFall) has a 1 (checked). The below code works but seems messy with the .each() call. Is there a different way? Remember nothing is clicked, no even I can find is triggered (load, blur, etc). It calls the function to check the box. Thanks!
.append($('<td>').addClass('smallBox').append($('<input>', {'class': 'centerText', 'name': 'inspectFall', 'type': 'checkbox'}).each( function() { checkBoxes($(this), inspectFall); } )))

A: what you can do is to pass the object to your checkBoxes() function like this:
.append($('<td>').addClass('smallBox').append ($('<input>', checkBoxes({'class': 'centerText', 'name': 'inspectFall', 'type': 'checkbox'}))))

and then in your function you can extend and return the object if inspectFall has a 1 like this:
function checkBoxes(obj) {
  return inspectFall == 1 ?
    $.extend(obj,{ "checked" : "checked" }):
    obj;
}

or if you need the inspectFall variable to be passed as a parameter just add it to the function call like this:
.append($('<td>').addClass('smallBox').append ($('<input>', checkBoxes({'class': 'centerText', 'name': 'inspectFall', 'type': 'checkbox'}, inspectFall))))

and your function:
function checkBoxes(obj, inspectFall) {
  return inspectFall == 1 ?
    $.extend(obj,{ "checked" : "checked" }):
    obj;
}


text:
Q: How to test if array elements are all equal in bash? The following array represented the numbers of disks on each linux machines
Each single array includes the number of disks on a linux machine.
echo ${ARRAY_DISK_Quantity[*]}
4 4 4 4 2 4 4 4

what is the simple way to identify that all array's values are equal?
Good status:
4 4 4 4 4 4 4 4

Bad status:
4 4 4 4 4 4 2 4

Bad status:
6 6 6 6 6 6 6 6 6 6 2 6 2

A: With zsh:
if ((${#${(u)ARRAY_DISK_Quantity[@]}} == 1)); then
  echo OK
else
  echo not OK
fi

Where (u) is a parameter expansion flag to expand unique values. So we're getting a count of the unique values in the array.
Replace == 1 with <= 1 is you want to consider an empty array is OK.
With ksh93, you could sort the array and check that the  first element is the same as the last:
set -s -- "${ARRAY_DISK_Quantity[@]}"
if [ "$1" = "${@: -1}" ]; then
  echo OK
else
  echo not OK
fi

With ksh88 or pdksh/mksh:
set -s -- "${ARRAY_DISK_Quantity[@]}"
if eval '[ "$1" = "${'"$#"'}" ]'; then
  echo OK
else
  echo not OK
fi

With bash, you'd probably need a loop:
unique_values() {
  typeset i
  for i do
    [ "$1" = "$i" ] || return 1
  done
  return 0
}
if unique_values "${ARRAY_DISK_Quantity[@]}"; then
  echo OK
else
  echo not OK
fi

(would work with all the Bourne-like shells with array support (ksh, zsh, bash, yash)).
Note that it returns OK for an empty array. Add a [ "$#" -gt 0 ] || return at the start of the function if you don't want that.

A: bash + awk soltion:
function get_status() {
    arr=("$@")    # get the array passed as argument
    if awk 'v && $1!=v{ exit 1 }{ v=$1 }' <(printf "%d\n" "${arr[@]}"); then
        echo "status: Ok"
    else
        echo "status: Bad"
    fi
}

Test case #1:
ARRAY_DISK_Quantity=(4 4 4 4 4 2 4 4)
get_status "${ARRAY_DISK_Quantity[@]}"
status: Bad

Test case #2:
ARRAY_DISK_Quantity=(4 4 4 4 4 4 4 4)
get_status "${ARRAY_DISK_Quantity[@]}"
status: Ok

A: I have another bash only solution that should work with strings as well:
isarray.equal () {
    local placeholder="$1"
    local num=0
    while (( $# )); do
        if [[ "$1" != "$placeholder" ]]; then
            num=1
            echo 'Bad' && break
        fi
        shift
    done
    [[ "$num" -ne 1 ]] && echo 'Okay'
}

Demonstration:
[root@JBSTEST001 ~]# ARRAY_DISK_Quantity=(4 4 4 4 2 4 4 4)
[root@JBSTEST001 ~]# isarray.equal "${ARRAY_DISK_Quantity[@]}"
Bad
[root@JBSTEST001 ~]# ARRAY_DISK_Quantity=(4 4 4 4 4 4 4 4)
[root@JBSTEST001 ~]# isarray.equal "${ARRAY_DISK_Quantity[@]}"
Okay
[root@JBSTEST001 ~]# ARRAY_DISK_Quantity=(four four four four two four four four)
[root@JBSTEST001 ~]# isarray.equal "${ARRAY_DISK_Quantity[@]}"
Bad
[root@JBSTEST001 ~]# ARRAY_DISK_Quantity=(four four four four four four four four)
[root@JBSTEST001 ~]# isarray.equal "${ARRAY_DISK_Quantity[@]}"
Okay

A: With bash and GNU grep:
if grep -qE '^([0-9]+)( \1)*$' <<< "${ARRAY_DISK_Quantity[@]}"; then
  echo "okay"
else
  echo "not okay"
fi

A: bash + GNU sort + GNU grep solution:
if [ "${#array[@]}" -gt 0 ] && [ $(printf "%s\000" "${array[@]}" |
       LC_ALL=C sort -z -u |
       grep -z -c .) -eq 1 ] ; then
  echo ok
else
  echo bad
fi

English explanation: if unique-sorting the elements of the array results in only one element, then print "ok".  Otherwise print "bad".
The array is printed with NUL bytes separating each element, piped into GNU sort (relying on the -z aka --zero-terminated and -u aka --unique options), and then into grep (using options -z aka --null-data and -c aka --count) to count the output lines.
Unlike my previous version, I can't use wc here because it requires input lines terminated with a newline...and using sed or tr to convert NULs to newlines after the sort would defeat the purpose of using NUL separators.  grep -c makes a reasonable substitute.

Here's the same thing rewritten as a function:
function count_unique() {
  local LC_ALL=C

  if [ "$#" -eq 0 ] ; then
    echo 0
  else
    echo "$(printf "%s\000" "$@" |
              sort --zero-terminated --unique |
              grep --null-data --count .)"
  fi
}

ARRAY_DISK_Quantity=(4 4 4 4 2 4 4 4)

if [ "$(count_unique "${ARRAY_DISK_Quantity[@]}")" -eq 1 ] ; then
  echo "ok"
else
  echo "bad"
fi

A: bash only solution (assuming a is ARRAY_DISK_Quantity)
ttt=${a[0]}
res=0
for i in "${a[@]}"
do
    let res+=$(if [ "$ttt" -ne "$i" ]; then echo 1; else echo 0; fi);
done
if [ "$res" -eq 0 ]
then
    echo "ok"
else
    echo "bad"
fi

A: Here is POSIX Awk:
awk 'BEGIN {while (++z < ARGC) if (ARGV[z] != ARGV[1]) exit 1}' "${ARRAY_DISK_Quantity[@]}"

A: Use a for loop to compare each array element to the next. End the loop one iteration less than the length of the array to avoid comparing the last element to nothing at the end.
for (( i=0; i<((${#array[@]}-1)); i++ )); do
    [ "${array[$i]}" != "${array[(($i+1))]}" ] && echo "Mismatch"
done
echo "Match"


text:
Q: VNC client only sees a terminal I have tightvnc server running on my Xubuntu 16.04. I can then run this command :
xvnc4viewer 192.168.1.2:5901
I can connect successfully to my machine but the only thing I see is this :

I guess that the reason why is because of a wrong config from my part. This is my config file :
#!/bin/sh

xrdb $HOME/.Xresources
xsetroot -solid grey
x-terminal-emulator -geometry 80x24+10+10 -ls -title "$VNCDESKTOP Desktop" &
x-window-manager &
# Fix to make GNOME work
#export XKL_XMODMAP_DISABLE=1
/etc/X11/Xsession
# fix to make xfce work:
startxfce4 &

Can someone explain to me what am doing wrong on here? I want to see the desktop as I do when sitting on front of my server machine.

A: Okey I got what the problem was. This is the right configuration for Xubuntu 16.04 ( which is what I am using ) :
#!/bin/sh
xrdb $HOME/.Xresources
xsetroot -solid grey
startxfce4 &

And this are the right commands :
tightvncserver :10 -geometry 1920x1080 ---> Start the server

tightvncserver -kill :10. ---> Kill the server

xvnc4viewer IPADDRESS:5910  ---> Connect to the server ( replace server IP address ).

The last command I can use it from Linux. From Mac I can simply connect using Screen Sharing app.


text:
Q: Bag of words not correctly labeling responses I am trying to implement Bag of Words in opencv and has come with the implementation below. I am using Caltech 101 database. However, since its my first time and not being familiar, I have planned to used two image sets from the database, the chair image set and the soccer ball image set. I have coded for the svm using this.
Everything went allright, except when I call classifier.predict(descriptor) , I do not get the label vale as intended. I always get a0 instead of '1', irrespective of my test image. The number of images in the chair dataset is 10 and in the soccer ball dataset is 10. I labelled chair as 0 and soccer ball as 1 . The links represent the samples of each categories, the top 10 is of chairs, the bottom 10 is of soccer balls
function hello

    clear all; close all; clc;

    detector = cv.FeatureDetector('SURF');
    extractor = cv.DescriptorExtractor('SURF');

    links = {
    'http://i.imgur.com/48nMezh.jpg'
    'http://i.imgur.com/RrZ1i52.jpg'
    'http://i.imgur.com/ZI0N3vr.jpg'
    'http://i.imgur.com/b6lY0bJ.jpg'
    'http://i.imgur.com/Vs4TYPm.jpg'
    'http://i.imgur.com/GtcwRWY.jpg'
    'http://i.imgur.com/BGW1rqS.jpg'
    'http://i.imgur.com/jI9UFn8.jpg'
    'http://i.imgur.com/W1afQ2O.jpg'
    'http://i.imgur.com/PyX3adM.jpg'

    'http://i.imgur.com/U2g4kW5.jpg'
    'http://i.imgur.com/M8ZMBJ4.jpg'
    'http://i.imgur.com/CinqIWI.jpg'
    'http://i.imgur.com/QtgsblB.jpg'
    'http://i.imgur.com/SZX13Im.jpg'
    'http://i.imgur.com/7zVErXU.jpg'
    'http://i.imgur.com/uUMGw9i.jpg'
    'http://i.imgur.com/qYSkqEg.jpg'
    'http://i.imgur.com/sAj3pib.jpg'
    'http://i.imgur.com/DMPsKfo.jpg'
    };

    N = numel(links);

    trainer = cv.BOWKMeansTrainer(100);

    train = struct('val',repmat({' '},N,1),'img',cell(N,1), 'pts',cell(N,1), 'feat',cell(N,1));

    for i=1:N

      train(i).val = links{i};
      train(i).img = imread(links{i});

       if ndims(train(i).img > 2)
         train(i).img = rgb2gray(train(i).img);
       end;

       train(i).pts = detector.detect(train(i).img);
       train(i).feat = extractor.compute(train(i).img,train(i).pts);

     end;

     for i=1:N
          trainer.add(train(i).feat);
     end;

     dictionary = trainer.cluster();
     extractor = cv.BOWImgDescriptorExtractor('SURF','BruteForce');
     extractor.setVocabulary(dictionary);

     for i=1:N
          desc(i,:) = extractor.compute(train(i).img,train(i).pts);
     end;

     a = zeros(1,10)';
     b = ones(1,10)';
     labels = [a;b];

     classifier  = cv.SVM;
     classifier.train(desc,labels);

     test_im =rgb2gray(imread('D:\ball1.jpg'));

     test_pts = detector.detect(test_im);
     test_feat = extractor.compute(test_im,test_pts);

     val = classifier.predict(test_feat);
     disp('Value is: ')
     disp(val)

     end

These are my test samples:
Soccer Ball

(source: timeslive.co.za)
Chair

Searching through this site I think that my algorithm is okay, even though I am not quite confident about it. If anybody can help me in finding the bug, it will be appreciable.
Following Amro's code , this was my result:
Distribution of classes:
  Value    Count   Percent
      1       62     49.21%
      2       64     50.79%
Number of training instances = 61
Number of testing instances = 65
Number of keypoints detected = 38845
Codebook size = 100
SVM model parameters:
         svm_type: 'C_SVC'
      kernel_type: 'RBF'
           degree: 0
            gamma: 0.5063
            coef0: 0
                C: 62.5000
               nu: 0
                p: 0
    class_weights: 0
        term_crit: [1x1 struct]

Confusion matrix:

ans =

    29     1
     1    34

Accuracy = 96.92 %

A: Your logic looks fine to me.
Now I guess you'll have to tweak the various parameters if you want to improve the classification accuracy. This includes the clustering algorithm parameters (such as the vocabulary size, clusters initialization, termination criteria, etc..), the SVM parameters (kernel type, the C coefficient, ..), the local features algorithm used (SIFT, SURF, ..).
Ideally, whenever you want to perform parameter selection, you ought to use cross-validation. Some methods already have such mechanism embedded (CvSVM::train_auto for instance), but for the most part you'll have to do this manually...
Finally you should follow general machine learning guidelines; see the whole bias-variance tradeoff dilemma. The online Coursera ML class discusses this topic in detail in week 6, and explains how to perform error analysis and use learning curves to decide what to try next (do we need to add more instances, increase model complexity, and so on..).
With that said, I wrote my own version of the code. You might wanna compare it with your code:
% dataset of images
% I previously saved them as: chair1.jpg, ..., ball1.jpg, ball2.jpg, ...
d = [
    dir(fullfile('images','chair*.jpg')) ;
    dir(fullfile('images','ball*.jpg'))
];

% local-features algorithm used
detector = cv.FeatureDetector('SURF');
extractor = cv.DescriptorExtractor('SURF');

% extract local features from images
t = struct();
for i=1:numel(d)
    % load image as grayscale
    img = imread(fullfile('images', d(i).name));
    if ~ismatrix(img), img = rgb2gray(img); end

    % extract local features
    pts = detector.detect(img);
    feat = extractor.compute(img, pts);

    % store along with class label
    t(i).img = img;
    t(i).class = find(strncmp(d(i).name,{'chair','ball'},4));
    t(i).pts = pts;
    t(i).feat = feat;
end

% split into training/testing sets
% (a better way would be to use cvpartition from Statistics toolbox)
disp('Distribution of classes:')
tabulate([t.class])
tTrain = t([1:7 11:17]);
tTest = t([8:10 18:20]);
fprintf('Number of training instances = %d\n', numel(tTrain));
fprintf('Number of testing instances = %d\n', numel(tTest));

% build visual vocabulary (by clustering training descriptors)
K = 100;
bowTrainer = cv.BOWKMeansTrainer(K, 'Attempts',5, 'Initialization','PP');
clust = bowTrainer.cluster(vertcat(tTrain.feat));

fprintf('Number of keypoints detected = %d\n', numel([tTrain.pts]));
fprintf('Codebook size = %d\n', K);

% compute histograms of visual words for each training image
bowExtractor = cv.BOWImgDescriptorExtractor('SURF', 'BruteForce');
bowExtractor.setVocabulary(clust);
M = zeros(numel(tTrain), K);
for i=1:numel(tTrain)
    M(i,:) = bowExtractor.compute(tTrain(i).img, tTrain(i).pts);
end
labels = vertcat(tTrain.class);

% train an SVM model (perform paramter selection using cross-validation)
svm = cv.SVM();
svm.train_auto(M, labels, 'SvmType','C_SVC', 'KernelType','RBF');
disp('SVM model parameters:'); disp(svm.Params)

% evaluate classifier using testing images
actual = vertcat(tTest.class);
pred = zeros(size(actual));
for i=1:numel(tTest)
    descs = bowExtractor.compute(tTest(i).img, tTest(i).pts);
    pred(i) = svm.predict(descs);
end

% report performance
disp('Confusion matrix:')
confusionmat(actual, pred)
fprintf('Accuracy = %.2f %%\n', 100*nnz(pred==actual)./numel(pred));

Here are the output:
Distribution of classes:
  Value    Count   Percent
      1       10     50.00%
      2       10     50.00%
Number of training instances = 14
Number of testing instances = 6

Number of keypoints detected = 6300
Codebook size = 100

SVM model parameters:
         svm_type: 'C_SVC'
      kernel_type: 'RBF'
           degree: 0
            gamma: 0.5063
            coef0: 0
                C: 312.5000
               nu: 0
                p: 0
    class_weights: []
        term_crit: [1x1 struct]

Confusion matrix:
ans =
     3     0
     1     2
Accuracy = 83.33 %

So the classifier correctly labels 5 out of 6 images from the test set, which is not bad for a start :) Obviously you'll get different results each time you run the code due to the inherent randomness of the clustering step.

A: What is the number of images you are using to build your dictionary i.e. what is N? From your code, it seems that you are only using a 10 images (those listed in links). I hope this list is truncated down for this post else that would be too few. Typically you need in the order of 1000 or much more images to build the dictionary and the images need not be restricted to only these 2 classes that you are classifying. Otherwise, with only 10 images and 100 clusters your dictionary is likely to be messed up.
Also, you might want to use SIFT as a first choice as it tends to perform better than the other descriptors.
Lastly, you can also debug by checking the detected keypoints. You can get OpenCV to draw the keypoints. Sometimes your keypoint detector parameters are not set properly, resulting in too few keypoints getting detected, which in turn gives poor feature vectors.
To understand more about the BOW algorithm, you can take a look at these posts here and here. The second post has a link to a free pdf for an O'Reilley book on computer vision using python. The BOW model (and other useful stuff) is described in more details inside that book.
Hope this helps.


text:
Q: Apache http server dose not generate the "phpmyadmin" page after installing the Apache http server and make sure it working.
Just added the folder of phpMyAdmin-4.2.0-english to the \Apache2\htdocs.
Renamed the folder to phpmyadmin.
while trying to view the page via http://localhost/phpmyadmin/index.php.
the page is not generated as php page.
all i can see is a textual page. (the index.php content as a text).
Did i miss anything? there is anything else i should install?

A: Try installing it using your package manager first.  Once you get that to work, remove it and use the install you downloaded.
Assuming you're using Ubunutu/Debian:
$ sudo apt-get install apache2 php5 php5-mysql mysql-server phpmyadmin