text:
Q: Haskell - put function on pair I have a following State monad:
type S = (M.Map String Integer, [String])

Now, I have a function:
rTD :: [String] -> ReaderT Env (StateT S (ErrorT String IO))
rTD (s, _) <- get
-- (1) how to here use put function to modify one element of pair my Store ?

(1) how to here use put function to modify one element of pair my Store ?
Thanks in advance.

A: The general case:
rTD xs = do
    (m, ys) <- get
    let m' = ...
    let ys' = ...
    put (m', ys')

The gets/modify case:
rTD xs = do
    m <- gets fst
    let m' = ...
    modify (\s -> (m', snd s))

With lens:
rTD xs = do
    _1 %= Map.insert "key" 777
    _2 %= ("foo":)


text:
Q: Error during install of ng-bootstrap on my Angular 4 cli project Hi angular community !
Yesterday I setup ng-bootstrap following these steps Getting started with Ng-Bootstrap  and everyting worked fine.
This morning I started my ng serve --open as usual and I got this message in the terminal:
ERROR in multi ./src/styles.css ./~/font-awesome/css/font-awesome.min.css ./~/bootstrap/dist/css/bootstrap.min.css
Module not found: Error: Can't resolve '/home/papamilo/Documents/Workspace/Test_a2json/front-end_copy_new/node_modules/bootstrap/dist/css/bootstrap.min.css' in '/home/papamilo/Documents/Workspace/Test_a2json/front-end_copy_new/node_modules/@angular/cli/models/webpack-configs'
 @ multi ./src/styles.css ./~/font-awesome/css/font-awesome.min.css ./~/bootstrap/dist/css/bootstrap.min.css
webpack: Failed to compile

`
NOTE: The thing very strange is when I go to my  node module folder I cannot see any bootstrap folder
my angular-cli.json:
`{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
  "name": "front-end"
  },
 "apps": [
{
  "root": "src",
  "outDir": "dist",
  "assets": [
    "assets",
    "favicon.ico"
  ],
  "index": "index.html",
  "main": "main.ts",
  "polyfills": "polyfills.ts",
  "test": "test.ts",
  "tsconfig": "tsconfig.app.json",
  "testTsconfig": "tsconfig.spec.json",
  "prefix": "app",
  "styles": [
    "styles.css",
    "../node_modules/font-awesome/css/font-awesome.min.css",
    "../node_modules/bootstrap/dist/css/bootstrap.min.css"
  ],
  "scripts": [
    "../node_modules/chart.js/dist/Chart.js",
    "./assets/js/jquery-3.1.1.min.js",
    "./responsive.js"
  ],
  "environmentSource": "environments/environment.ts",
  "environments": {
    "dev": "environments/environment.ts",
    "prod": "environments/environment.prod.ts"
    }
   }
  ],
   "e2e": {
   "protractor": {
    "config": "./protractor.conf.js"
  }
  },
  "lint": [
  {
  "project": "src/tsconfig.app.json"
  },
  {
  "project": "src/tsconfig.spec.json"
  },
  {
  "project": "e2e/tsconfig.e2e.json"
  }
  ],
"test": {
"karma": {
  "config": "./karma.conf.js"
   }
  },
  "defaults": {
"styleExt": "css",
"component": {}
  }
}

`
my package.json:
`{
"name": "front-end",
"version": "0.0.0",
"license": "Private",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
"@angular/animations": "^4.0.3",
"@angular/common": "^4.0.0",
"@angular/compiler": "^4.0.0",
"@angular/compiler-cli": "^4.1.0-rc.0",
"@angular/core": "^4.0.0",
"@angular/forms": "^4.0.0",
"@angular/http": "^4.0.0",
"@angular/platform-browser": "^4.0.0",
"@angular/platform-browser-dynamic": "^4.0.0",
"@angular/router": "^4.0.0",
"@ng-bootstrap/ng-bootstrap": "^1.0.0-alpha.30",
"@ngrx/store": "^4.0.0",
"@swimlane/ngx-charts": "^5.3.1",
"angular-highcharts": "^3.2.1",
"angular2-highcharts": "^0.5.5",
"chart.js": "^2.5.0",
"core-js": "^2.4.1",
"d3": "^4.9.1",
"font-awesome": "^4.7.0",
"highcharts": "^5.0.12",
"rxjs": "^5.1.0",
"typescript": "^2.2.1",
"zone.js": "^0.8.4"
  },
  "devDependencies": {
"@angular/cli": "^1.2.1",
"@angular/compiler-cli": "^4.0.0",
"@types/highcharts": "^4.2.56",
"@types/jasmine": "2.5.38",
"@types/node": "~6.0.60",
"canonical-path": "0.0.2",
"codelyzer": "~2.0.0",
"concurrently": "^3.2.0",
"jasmine-core": "~2.5.2",
"jasmine-spec-reporter": "~3.2.0",
"karma": "~1.4.1",
"karma-chrome-launcher": "~2.1.1",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^0.2.0",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"lodash": "^4.16.4",
"protractor": "~5.1.0",
"rimraf": "^2.5.4",
"ts-node": "~2.0.0",
"tslint": "~4.5.0",
"typescript": "~2.2.0"
  }
}`

A: It seems that bootstrap dependency is not present, try to add it to your project:
npm install bootstrap@4.0.0-alpha.6 --save

Note: ng-bootstrap page says they are aiming bootstrap 4 which is in alpha state

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get P Value at different confidence levels other than default in python scipy t test How do I get P Value at different confidence level other than the default (95%) in python scipy t test or other statistical tests? For example:
import scipy
from scipy import stats
data = [10,12,34,34,45,67,56,78,90,67,80,45,47,58]
stats.ttest_1samp(data,40)

Results are as below --
Out[7]: Ttest_1sampResult(statistic=1.808, pvalue=0.093)

but I need p-value at 90% and 99% confidence level too.
Only one answer is there but not very clear about where its confidence level is specified.
Python p-value from t-statistic
Is there any other alternate to Scipy in Python for it, if it can't be done with Scipy?

A: There will only be a single p-value for the T-test of equality between the mean of an independent sample and the given population mean.
This may subjectively be considered significant at a given confidence level based on its value.
In your test, the p-value of 0.093 indicates that there is a 9.3% chance of the observed sample mean arising from an independent sample from a population with mean 40. This would be considered significant (i.e. would lead to rejection of the null hypothesis) at the 90% confidence level (since 9.3% <= 10%), but not at the 95% confidence level or 99% confidence level.


text:
Q: Simplified way of installing a com dll created in C# - Need expert suggestion The requirement
Call C# function from classic ASP.
The solution
After hours of research i was able to call a c# function from classic asp. I feel i have done so many steps (below). Not sure if this is the right way. Looking for expert suggestion.
Development Machine: VS 2010
Production Server: Windows 2008 with Framework 4 installed
Steps followed to create com dll in C# (development machine)

*

*Create a class library project

*Pasted the following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace cominter
{
    [Guid("EAA4976A-45C3-4BC5-BC0B-E474F4C3C83F")]
    public interface ComClass1Interface
    {
        string test();
}

[Guid("0D53A3E8-E51A-49C7-944E-E72A2064F938"),
    ClassInterface(ClassInterfaceType.None)]
[ComVisibleAttribute(true)]
public class ComClass1 : ComClass1Interface
{
    public string test()
    {
        return "vivek";
    }

}

}

*in the properties-> build, check Register for COM Interop

*in the properties-> Signing, check sign the assembly. created a key file

*built the solution

*used regasm /regfile to create regfile

Steps followed in Server 2008 (production) to install the dll

*

*Copied gacutil.exe and gacutil.exe.config from development machine C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\ to the server C:\Windows\Microsoft.NET\Framework\v4.0.30319

*ran the registry file generated from the development machine
Is there a better way? I'm also not sure if all the steps above are required. Any expert suggestion would be great.
Questions

*

*what is the use of GUID above teh class name and the inter face name. is it really required? i just copied this from msdn. if it is required, should i create my own id or leave it. is there a tool to create this guid

*is interface required. can it work without interface?

*is creating key necessary. When i installed this dll in production, I didn't copy the key file.

*what are the files to be copied. i copied dll and tlb file and ran the gacutil

*is there a better way of installing this com dll

*i ran the registry script. is this required?

A: I am not an expert on this topic, but I have done something similar a few times. I my cases it has been .Net assemblies used by VB6 applications not websites. So here are my experiences on your questions.

*

*I have never used a GUID on my projects, so it is not required. (There is a tool in the .NET SDK to create GUIDs)

*As far as I know an interface is required.

*The signing of your assembly is necessary, you cannot install/register your dll if it is not signed. You don't copy the keyfile, it is only used when compiling your project.

*You only need your dll and tlb file. If you are referencing any other libraries you are using, you need them as well.

*On my projects I have used an setup project from visual studio to register my VB6 app and my .Net library, that have worked fine for me when distributing the application.

*As far as I know, it is not required.


text:
Q: Need for initialization block in Java What is the need of initialization block in Java? How does it help in coding?
Do we just add a set of curly braces extra in our code?
Eg:
public class GFG
{
    // Initializer block starts..
    {
        // This code is executed before every constructor.
        System.out.println("Common part of constructors invoked !!");
    }
    // Initializer block ends

    public GFG()
    {
        System.out.println("Default Constructor invoked");
    }

    public static void main(String arr[])
    {
        GFG obj1;
        obj1 = new GFG();

    }
}

A: There are two types of initializer blocks.
You have a static initializer block which runs on creation of class. Its syntax is
static {
    //stuff here
}

The other one is instance initialization block which runs when you instantiate an object. Its syntax is
{
    //stuff here
}

If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.

This is to answer your question on when you should use them. You basically use them to initialize a variable with some kind of specific logic.  It's from the official Oracle documentation.


text:
Q: Change the SELECT in WHERE clause to another solution I want to make my query better. What opportunities that I have to change this code for a faster one?
SELECT sn
FROM package p
WHERE StatusID = 1
AND ( NOT EXISTS( SELECT * FROM packagedetail pd
                  WHERE pd.packageID = p.ID AND packageDetailStatus = 12 )
      OR ( EXISTS ( SELECT * FROM packagedetail pd
                  WHERE pd.packageID = p.ID AND packageDetailStatus = 12)
            AND  EXISTS ( SELECT * FROM unit u JOIN unitDetail ON u.ID = ud.unitID
                   WHERE (ud.InmostPackageID = p.ID OR ud.OutmostPackageID = p.ID)
                   AND u.UnitStateID in (8120, 8130, 8140)
                 )
         )
     )

( I know this is so ugly, but I want to know, how can I improve my skills )

A: One simplification that you can do is to not repeat the NOT EXISTS subquery again.
The below query is semantically equivalent to yours:
SELECT p.sn
FROM package p
WHERE p.StatusID = 1
AND (
  NOT EXISTS(SELECT * FROM packagedetail pd
             WHERE pd.packageID = p.ID AND packageDetailStatus = 12)
  OR
  EXISTS (SELECT * FROM unit u JOIN unitDetail ON u.ID = ud.unitID
          WHERE (ud.InmostPackageID = p.ID OR ud.OutmostPackageID = p.ID) AND u.UnitStateID in (8120, 8130, 8140))
);

because:
(NOT X) OR (X AND Y) = (NOT X) OR Y

A: An alternative that might make it easier to read:
SELECT sn
FROM
    package p
    cross apply
    (select
         exists_packagedetail   =case when exists   (
                                                        SELECT *
                                                        FROM packagedetail pd
                                                        WHERE pd.packageID = p.ID AND packageDetailStatus = 12
                                                    ) then 1 else 0 end
        ,exists_unitdetail      =case when exists   (
                                                        SELECT *
                                                        FROM
                                                            unit u
                                                            JOIN unitDetail ON u.ID = ud.unitID
                                                        WHERE (ud.InmostPackageID = p.ID OR ud.OutmostPackageID = p.ID) AND u.UnitStateID in (8120, 8130, 8140)
                                                    )then 1 else 0 end
    ) as q1
WHERE StatusID = 1 and (q1.exists_unitdetail=1 or q1.exists_packagedetail=0)


text:
Q: Commit using a different account in your github repository I have 2 GitHub accounts - Account A and B and i am working on repository xyz under my account A.If i need to make a commit using Account B in my Account A repository what prerequisite information should i have about Account B with me to make a commit . Is Account B user name and email id linked to git hub suffice to make a commit for Account A by using .
  $git config user.name accountB
  $git config user.email accountB@gmail.com

Do i need Account B password or ssh key to make a commit to Account A or account name and account email id is suffice

A: To create a commit with a different name and email address, you must change your configuration of user.name and user.email. To change them permanently, use
git config user.name accountB
git config user.email accountB@gmail.com

and make commits. To change these settings for only one commit, you can use
git -c user.name="accountB" -c user.email=accountB@gmail.com commit

Note that these settings have nothing to do with your Github account. They are not even security related. They do not change whether you can push to Github or not or which Github account you push to.


text:
Q: Create new Nuget package even if same version already exist I was working on a C# library project and i want to create a Nuget package out of it. I'm using this command for that
dotnet pack /p:Version=2.0.1 --include-symbols

It is working fine when the version is handled properly.
But there can be situation where i have to create a nuget package with same version as before [ to replace the 2.0.1 ] when last one was a mistake.
Right now when i try above command it is not doing anything if package with same version already exists?
Is there a way where i can replace the existing package without deleting it manually?

A: I tried a lot of things, and ended up doing as below.
Wrote a console application which will update the .csproj version part of the library project then build the library project with the help of powershell script.
class Program
    {
        private static string csProjectPath => ConfigurationManager.AppSettings["projectPath"] + ConfigurationManager.AppSettings["projectName"];
        private static string projectPath => ConfigurationManager.AppSettings["projectPath"];
        static void Main(string[] args)
        {
            try
            {
                var allowedTypes = new List<string> { "1", "2", "3", "4" };
                Console.WriteLine($"Build Type: {Environment.NewLine} 1. Major {Environment.NewLine} 2. Minor {Environment.NewLine} 3. Build Number {Environment.NewLine} 4. Revision ");
                var buildType = Console.ReadLine();
                while (!allowedTypes.Contains(buildType))
                {
                    Console.WriteLine("Please enter a valid entry");
                    Console.WriteLine($"Build Type: {Environment.NewLine} 1. Major {Environment.NewLine} 2. Minor {Environment.NewLine} 3. Build Number {Environment.NewLine} 4. Revision ");
                    buildType = Console.ReadLine();
                }

                RunPowershellScript(buildType);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }

        public static string GetCSProjectUpdateCommand(string buildType)
        {
            return @"
                $csprojPath = $args[0]
                $buildType = $args[1]

                $filePath = $csprojPath
                $xml = New-Object XML
                $xml.Load($filePath)
                $versionNode = $xml.Project.PropertyGroup.Version

                $currentSplit = $versionNode.Split('.')
                $currentRevisionNumber = 0

                $myBuildNumber = ''

                $splitNumber = $versionNode.Split('.')
                $majorNumber = $splitNumber[0]
                $minorNumber = $splitNumber[1]
                $buildNumber = $splitNumber[2]
                $revisNumber = $splitNumber[3]
                Switch($buildType)
                {
                    '1' { $myBuildNumber = ([int]$majorNumber + 1) + '.0.0.0'; break  }
                    '2' { $myBuildNumber = $majorNumber + '.' + ([int]$minorNumber + 1) + '.0.0'; break }
                    '3' { $myBuildNumber = $majorNumber + '.' + $minorNumber + '.' + ([int]$buildNumber + 1) +'.0'; break }
                    '4' { $myBuildNumber = $majorNumber + '.' + $minorNumber + '.' + $buildNumber + '.' + ([int]$updatedRevisionNumber + 1); break}
                    default { Write - Host 'Invalid data' }
                }

                if ($versionNode -eq $null) {
                    $versionNode = $xml.CreateElement('Version')
                        $xml.Project.PropertyGroup.AppendChild($versionNode)
                }
                $xml.Project.PropertyGroup.Version = $myBuildNumber
                $xml.Save($filePath)";
        }

        private static void RunPowershellScript(string buildType)
        {
            UpdateCSProject(buildType);
            BuildProject();
        }

        private static void UpdateCSProject(string buildType)
        {
            using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                PowerShellInstance.AddScript(GetCSProjectUpdateCommand(buildType));

                PowerShellInstance.AddArgument(csProjectPath);
                PowerShellInstance.AddArgument(buildType);

                IAsyncResult result = PowerShellInstance.BeginInvoke();
                while (result.IsCompleted == false)
                {
                    Console.WriteLine("Updating csproj...");
                    Thread.Sleep(1000);
                }
                Console.WriteLine("Update completed!");
            }
        }

        private static void BuildProject()
        {
            using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                PowerShellInstance.AddScript($"dotnet pack {projectPath} --include-symbols");
                PowerShellInstance.AddArgument(projectPath);
                IAsyncResult result = PowerShellInstance.BeginInvoke();
                while (result.IsCompleted == false)
                {
                    Console.WriteLine("Please wait, we are building the project...");
                    Thread.Sleep(1000);
                }
                Console.WriteLine("Build completed!. Nuget package created.");
            }
        }
    }
}


text:
Q: How do you select lower and uppercase characters in a string using an if-else statement in Python? I'm trying to solve a problem where I wish to select multiple words beginning with 's', but have both the lowercase and uppercase words be shown in the output.
To try and achieve my desired result, I used an if-else statement in a for-loop but it only selected the first value I chose. For example, if I wrote 'S' first, it selected the uppercase and ignored the lowercase.
st = 'Sally sells shakes from Shake Shack every Saturday.'

for i in st.split():
 if i[0] == 's' and 'S':
        print(i)

I expected the output to be:
sells
shakes
Sally
Shake
Shack
Saturday
But the actual output was:
sells
shakes

A: You can use lower() to make comparison lowercase:
st = 'Sally sells shakes from Shake Shack every Saturday.'

for i in st.split():
    if i.lower().startswith('s'):
        print(i)

result:
Sally
sells
shakes
Shake
Shack
Saturday.

A: use logical OR: Return True if one of the statements are True : Your word will start with 'S' or 's'
NOTE: i[0] == 's' and 'S', is not correct expression in this case
STATEMENT1: i[0] == 's'
STATEMENT2: i[0] == 'S'
if STATEMENT1 or STATEMENT2
st = 'Sally sells shakes from Shake Shack every Saturday.'

for i in st.split():
   if i[0] == 's' or i[0] == 'S':
       print(i)


text:
Q: Mongoose model references and CRUD I'm building a very basic 'TODO' app with MEAN stack. I'm testing endpoints with google's Postman, and have started troubleshooting on the front end. Currently the user can sign-up, login, and logout.  When I try to add a 'todo' item in postman, it creates the item, but it does not add to the user object(maybe this is because there's no way to be 'logged in' while testing in postman?). And when I login on the front end and try to create a todo item ('test') I get the following terminal error:
SyntaxError: Unexpected token t
at parse (/Users/AdamShaleen/code/todo/node_modules/body-parser/lib/types/json.js:83:15)

Here's some code snippets
// server endpoint
app.post('/todo', todoController.createTODO);

// full function definition
createTODO: function(request, response, next) {
    TODO.create(request.body, function(error, serverResponse) {
        if (error) {
            return response.status(500).send(error);
        }
        else {
        response.status(200).send(serverResponse);
        }
    });
},

// User Model
var User = new Schema ({
email: {type: String, index: true, trim: true, required: true, unique: true},
password: {type: String, required: true},
todo: [
    {
        id:{type: Schema.Types.ObjectId, ref: 'TODO'}
    }
]

// Todo model
var todoSchema = new Schema ({
item: {type: String}});

// Angular Service
this.createTodo = function(newTODO) {
return $http({
    method: 'POST',
    url: '/todo',
    data: newTODO
}).then(function(response) {
    return response.data;
});};

// Angular controller
$scope.addTODO = function() {
service.createTodo($scope.newTODO).then(function(response) {
    $scope.todos = response;
});};

// HTML
<input ng-model="newTODO" placeholder="New TODO"></input>
<button type="button" ng-click="addTODO(newTODO)">Add TODO</button>

Thanks for any suggestions or insight.  I'm very new to this.


text:
Q: How do I update the time using Streams in Flutter? I've been investigating the use of streams as I think this will the best solution for my app. I want to be able to check the time at specific intervals, then change the theme of a map automatically depending on whether the sun has risen or set. I have the themes and I have the sun code, but I need to join them together.
This is my code so far. If I use a double for the controller and subscription and simply generate a random number, then all is well. I get a different randomly generated number every second.
However, using the code below simply shows the same time over again.
Can somebody point me in the right direction with this?
import 'dart:async';
import 'dart:core';

import 'package:flutter/material.dart';

void main() => runApp(StreamTest());

class StreamTest extends StatefulWidget {
  @override
  _StreamTestState createState() => _StreamTestState();
}

class _StreamTestState extends State<StreamTest> {
  StreamController<DateTime> controller =
      StreamController<DateTime>.broadcast();
  StreamSubscription<DateTime> streamSubscription;
  DateTime currentTime = DateTime.now();

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Stream Demo",
      home: Scaffold(
        body: Center(
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              MaterialButton(
                color: Colors.yellow,
                child: Text("Subscribe"),
                onPressed: () async {
                  getTime().listen((value) {
                    print('CURRENT TIME $currentTime');
                  });
                },
              ),
              MaterialButton(
                child: Text('Unsubscribe'),
                color: Colors.red[200],
                onPressed: () {
                  streamSubscription.cancel();
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Stream<DateTime> getTime() async* {
  DateTime currentTime = DateTime.now();
  while (true) {
    await Future.delayed(Duration(seconds: 1));
    yield currentTime;
  }
}

thanks

A: as @pskink mentioned you can use Stream.periodic.
DateTime current = DateTime.now();
Stream timer = Stream.periodic( Duration(seconds: 1), (i){
       current = current.add(Duration(seconds: 1));
      return current;
    });

    timer.listen((data)=> print(data));

A: Inside your while (true) loop you're yielding the same variable you've set before. If you change it to yield DateTime.now() it will generate new values each iteration.
Also change variable inside print call to value: print('CURRENT TIME $value');.
To cancel the subscription later, store the value returned by listen method:
streamSubscription = getTime().listen((value) {

Result:
I/flutter ( 5716): CURRENT TIME 2019-11-14 13:50:34.318898
I/flutter ( 5716): CURRENT TIME 2019-11-14 13:50:35.323906
I/flutter ( 5716): CURRENT TIME 2019-11-14 13:50:36.328085
I/flutter ( 5716): CURRENT TIME 2019-11-14 13:50:37.332919


text:
Q: Merge and order rows I have a table in the following structure. I am writing a query to get all item_ids where key_name='topic' and key_string_value='investing', which is the simple part.
select item_id from table where key_name='topic' and key_string_value='investing'
But then for all the item_ids returned above, I want to order them by the values set for each item_id in key_name='importance' and key_name='product'.The table structure is making it very difficult as I am not an SQL expert. Any help would be appreciated.
item_id      key_name       key_string_value    Key_float_value

 1            topic           investing            null
 1            importance        null                500
 1            product           A                  null
 1            product           B                  null
 2             topic          Starting             null
 2            product            B                 null
 2            importance       null                 300
 2            topic            retail              null
 3            importance      null                  400
 3            topic           investing             null
 3            product           C                   null
 4            topic            Starting             null
 4            topic            investing           null
 4            importance       null                 400
 4            product            D                   null

A: @Schwern is on right - your structure should be normalized, and the names should be better too.  All this makes me think: homework.
The answer to the homework question is a self join, and looks like this:
select t1.item_id , imp.key_float_value, prd.key_string_value
from [table] t1
    LEFT OUTER JOIN [table] imp on imp.item_id = t1.item_id and imp.key_name='importance'
    LEFT OUTER JOIN [table] prd on prd.item_id = t1.item_id and prd.key_name='product'
where t1.key_name='topic' and t1.key_string_value='investing'
ORDER BY imp.key_float_value, prd.key_string_value

The square brackets on `[table] are because the use of the table keyword as the table name requires the name to be delimited.  Square brackets for TSQL.  Others use double quotes (")

A: You have a very poorly design table that will be slow and difficult to work with.  SQL is not a key/value store; it works on rows, columns and relationships.  Rather than fight it, I would suggest redesigning it.  Either use a NoSQL database which is easier to use and works more like normal programming data structures, or redesign it.
Here's the redesign I would suggest.
CREATE TABLE item (
    id                  INTEGER PRIMARY KEY,
    importance          INTEGER DEFAULT 0
);

CREATE TABLE item_topics (
    item_id             INTEGER REFERENCES item(id),
    topic               TEXT NOT NULL
);

CREATE TABLE item_products (
    item_id             INTEGER REFERENCES item(id),
    product             TEXT NOT NULL
);

The item itself, and any scalar (ie. single value) attributes go into one table.  Anything which can be a list (products and topics) needs its own table relating each item to its elements.  If this seems clunky, that's because it is, but that's how SQL works.
To find all items whose topic is investing, you have to join on the item_topics table.
SELECT item.id
FROM item
JOIN item_topics ON item.id = item_topics.id
WHERE topic = 'investing'

Then to order them, add ORDER BY item.importance.


text:
Q: How can I show that $(\bar{X}, S^2)$ is independent of $(X_{(n)}-\bar{X})/S$? Let $X_1,\ldots,X_n$ be a random sample from $N(\mu,\sigma^2)$ with both parameters unknown. How can I show that $(\bar{X}, S^2)$ is independent of $(X_{(n)}-\bar{X})/S$?
Work:
I am quite confident that I should use Basu's Theorem here. I can see that $(\bar{X}, S^2)$ is a complete sufficient statistic, but I am having trouble showing it. I assume that I will need to write $N(\mu,\sigma^2)$ as an exponential family to show this statistic is complete sufficient (for use in Basu's Theorem).
$$f(x\mid \mu,\sigma)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp\left(\frac{-1}{2\sigma^2}(x-\mu)^2\right)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp\left(\frac{-\mu^2}{2\sigma^2}\right)\exp\left(\frac{-x^2}{2\sigma^2} + \frac{x\mu}{\sigma^2}\right)$$
With this work, $T(\mathbf{X})=(\sum x_i, \sum x_i^2)$ is a complete statistic for $\mu, \sigma$, which is not $T(\mathbf{X})=(\bar{X}, S^2)$. I see that it closely resembles what I need, so how can I continue this work?
Additionally, we would need to show that $Y=(X_{(n)}-\bar{X})/S$ is ancillary, meaning that $Y$'s distribution is free of both $\mu$ and $\sigma$. However, I am not too sure on how to show this. Is this a case of applying a location-scale transformation?

A: To expand on my comment, you can write $Y$ as $$Y=\frac{\frac{X_{(n)}-\mu}{\sigma}-\frac{\overline X-\mu}{\sigma}}{S/\sigma}$$
From the distributions of $\overline X$ and $S$ it should be clear that those of $\frac{\overline X-\mu}{\sigma}$ and $S/\sigma$ are free of $(\mu,\sigma^2)$. As for the order statistic, notice that $\frac{X_{(n)}-\mu}{\sigma}$ has the same distribution as $Z_{(n)}$ where $Z_1,\ldots,Z_n$ are i.i.d standard normal. Hence its distribution is also free of $(\mu,\sigma^2)$. You can show this from the distribution function if you want.
This shows $Y$ is ancillary for $(\mu,\sigma^2)$. Note that @whuber's suggestion is along the same lines.
And the pdf of $X_1,X_2,\ldots,X_n$ is indeed a member of a full-rank (regular) exponential family, which shows that $\left(\sum\limits_{i=1}^n X_i,\sum\limits_{i=1}^n X_i^2\right)$ and equivalently its one-to-one transform $(\overline X,S^2)$ is a complete sufficient statistic for $(\mu,\sigma^2)$.


text:
Q: Adjusting the volume with a uislider cocos2d Im trying to add a slider for the settings page in my game, i have looked around but there doesnt seem to be much info.
Anyone help at all?
Cheers

A: Maybe this thread on the Cocos2d forum will help you. It tackles the problem you describe. As a conclusion it says that:

It can only be done using MPVolumeView

Read this piece in the Apple Developer documentation for more about the MPVolumeView.


text:
Q: Backup data while keeping POSIX ACLs and permissions I'm looking for a practical way to backup data from a server and keep all ACLs and permissions. I've looked at tar, but according to Google tar doesn't keep ACLs . I know rsync can keep ACLs and permissions, but only if the target system supports POSIX ACLs and have the same users. In my case I'm doing the backup to a directory that is located on AFS, so POSIX ACLs are not supported.
At the moment I have solved the problem by writing a script that uses find to recurse through the system (I'm using find because I which to exclude some directories) and saves the permissions and ACLs to a text file. This solution works, but is painfully slow. Is there a better solution?

A: apt-get install star
man star
star -acl -whatever -other -options -you -need

Star is tar with support for extended POSIX headers, that is, the ability to store some extra data about a file in the tar file.  The -acl option gets the ACLs; you need it for both archive creation and extraction.

A: If you don't want to install another program, you can backup the ACLs separately:
getfacl -R somedir > acls.txt

This dumps all the ACLs from somedir into the file acls.txt.
To restore, use:
setfacl -R --set-file=acls.txt somedir

A: beside star you can use bsdtar

A: Cross-posting my answer here: https://unix.stackexchange.com/a/725745/550161

When creating/extracting the archive you need to use both the --acls and --xattrs options and of-course have the proper permissions to read/write those acl and xattr.
Examples:
1. Creating the archive:
ZSTD_CLEVEL=19 tar --acls --xattrs -caPf systemd-network-conf.tzst --directory=/etc systemd/network systemd/networkd.conf.d

The above will create a zstd compressed tar archive, using compression level 19, while preserving the ACL's and extended attributes.

*

*The .tzst extension means "a tar archive using zstd compression", just like tgz is for a gzip'ed version etc.

*The compression level used by the implicit zstd compressor is set by the provided ZSTD_CLEVEL environment variable at start on same line.

*See man pages: tar(1) and zstd(1).

2. Extracting that archive:
sudo tar --acls --xattrs -xvf systemd-network-conf.tzst

The above will create, in your current directory, a sub-directory named systemd because that's the common root-dir inside the archive.

*

*All settings you had set using chown/chmod/setfacl in the originals, will be preserved in the extracted version.

3. Comparing original and extracted file attributes.
{cd /etc; getfacl -R systemd/network systemd/networkd.conf.d} >original.acl; cd -
getfacl -R systemd/network systemd/networkd.conf.d >extracted.acl
diff -u original.acl extracted.acl

*

*You should see no output from the first two lines because it is redirected to a file.
(Exception for first line, which will output your current directory due to the last cd - as separate command, which just restores your current directory.)

*You should see no output from the diff line either, because there's no difference.


text:
Q: get variable from a jQuery Plugin I need to know how is possible to get a plugin variable outside the plugin, to test it with some test framework.
So this is my simplified plugin:
(function ($) {
    $.fn.extend({
        myPlugin: function (argumentOptions) {
            var defaults = {
                image: 'img/default.png',
            };

            this.textSend = '';

            var options = $.extend(defaults, argumentOptions);
            var globalHere = this;

            return this.each(function () {
                obj.mouseup(function(e) {
                    globalHere.textSend = 'test';
                });
            });
        }
    });
})(jQuery);

I need to the variable this.textSend outside the plugin.
I have tried in this way:
$(document).ready(function(){

  var testfield = $('.txt');

  testfield.myPlugin({
      image:"../img/twitter.png"
  });

  testfield.focus();
  testfield.trigger($.Event( "mouseup"));
  console.log($.fn.myPlugin.textSend);
});

but the console.log return me undefined
How can i get that variable outside?
Thanks

A: You can store it inside the closed scope you created around your plugin and expose it through another function. Of course it'll need some refactoring, but this is the general idea:
(function ($) {
    var whateverNameYouWant; //here

    $.fn.extend({
        myPlugin: function (argumentOptions) {
            var defaults = {
                image: 'img/default.png',
            };

            this.textSend = '';
            whateverNameYouWant = this.textSend; //here

            var options = $.extend(defaults, argumentOptions);
            var globalHere = this;

            return this.each(function () {
                obj.mouseup(function(e) {
                    globalHere.textSend = 'test';
                    whateverNameYouWant = this.textSend; //here
                });
            });
        }
    });

    $.extend({
        getWhateverNameYouWant: function() {
            return whateverNameYouWant;
        }
    })
})(jQuery);

var value = $.getWhateverNameYouWant();

A: You will want to make sure you are returning this like so:

(function($) {
  $.fn.extend({
    myPlugin: function(argumentOptions) {
      var self = this;

      self.textSend = 'something';
      self.inc = 0;

      self.mouseup(function(e) {
        self.textSend = 'new thing #' + self.inc;
        self.inc++;
      });

      return self;
    }
  });
})(jQuery);

var instantiated = $('button').myPlugin({});
$('input').val(instantiated.textSend);

$('button').click(function(e) {
  $('input').val(instantiated.textSend);
});

Current textSend:
<input />

<button>Change textSend</button>

Hopefully will get you on the right track.
Update
Try new code.

A: At line console.log($.fn.myPlugin.textSend);
use testfield.textSend . now it has become proprty of selector via myplugin.


text:
Q: Enviar informacion de un datagridvew a otro datagridview Agradecería mucho si me ayudaran con esta duda que tengo.
Actualmente tengo un textbox que me busca artículos en una base de datos y las muestra en el datagridview de nombre "datalistado". Quiero que una vez mostrados los resultados, si yo le doy doble click a alguno, me lo envíe a otro datagridview llamado "datatotal".
Este es mi código actual:
 private void datalistado_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        foreach (DataGridViewRow row in datalistado.Rows)
        {
            try
            {
                if (Convert.ToBoolean(row.Cells[1].Value))
                {

                    DataGridViewRow fila = new DataGridViewRow();
                    fila.CreateCells(datatotal);
                    fila.Cells[1].Value = row.Cells[1].Value;
                    fila.Cells[2].Value = row.Cells[2].Value;
                    datatotal.Rows.Add(fila);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Sistema Restaurante", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

Gracias de antemano por la ayuda!

A: Ya logre solucionarlo gracias a sus comentarios! Esto fue lo que terminé haciendo:
private void datalistado_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    int rowId = datatotal.Rows.Add();

    // Tomando la fila
    DataGridViewRow row = datatotal.Rows[rowId];

    // Añadir datos a la fila!
    row.Cells["Nombre"].Value = datalistado.SelectedCells[1].Value.ToString();
    row.Cells["Precio"].Value = datalistado.SelectedCells[2].Value.ToString();
}


text:
Q: How to test a service function in kotlin which uses a late init Id? I am new to testing in kotlin and I was wondering how I can test this function:
this is my SegmentService file:
    fun createSegmentFromUserIds(userIds: List<String>, name:String, appId: String): Segmentation {
        val filter = createUserIdFilter(userIds)
        val createSegmentRequest =  CreateSegmentRequest(
            name = name, attribute = filter, type = SegmentType.STATIC
        )
        val segmentation = segmentMetaService.saveSegmentInfo(createSegmentRequest, appId)
        querySegmentService.runUpdateQuery(users = userIds, appId = appId, segmentId = segmentation.id)
        return segmentation
    }

this is the saveSegmentInfo function:
fun saveSegmentInfo(createSegmentFilter: CreateSegmentRequest, appId: String): Segmentation {
    val segmentInfo = segmentationRepository.save(createSegmentFilter.let {
        Segmentation(
            attribute = it.attribute, name = it.name, appId = appId, type = it.type
        )
    })
    logger.info("Segment info saved with id: ${segmentInfo.id}, name: ${segmentInfo.name}")
    return segmentInfo
}

and this is the Segmentation Document
@Document(Segmentation.COLLECTION_NAME)
class Segmentation(
@Field(ATTRIBUTE)
val attribute: Filter,

@Field(NAME)
val name: String,

@Indexed
@Field(APP_ID)
val appId: String,

@Field(STATUS)
var status: SegmentStatus = SegmentStatus.CREATED,

@Field(TYPE)
var type: SegmentType = SegmentType.STATIC,

@Field(USER_COUNT)
var userCount: Long? = null,
) {
    @Id
    lateinit var id: String

    @Field(CREATION_DATE)
    var creationDate: Date = Date()
}

I have written this test for it:
class SegmentServiceTest {
    private val segmentMetaService = mock(SegmentMetaService::class.java)
    private val querySegmentService = mock(QuerySegmentService::class.java)
    private val converterService = mock(ConverterService::class.java)
    private val userAttributeService = mock(UserAttributeService::class.java)
    private val segmentConsumerUserInfoProducer = mock(SegmentConsumerUsersInfoProducer::class.java)
    private val segmentationRepository = mock(SegmentationRepository::class.java)
    @Test
    fun `createSegmentFromUserIds should create a new segment`() {
        val segmentService = SegmentService(
            segmentMetaService = segmentMetaService,
            querySegmentService = querySegmentService,
            converterService = converterService,
            userAttributeService = userAttributeService,
            segmentConsumerUserInfoProducer = segmentConsumerUserInfoProducer
        )

        val userIds = listOf("user-1", "user-2", "user-3")
        val filter = AndFilter(
            operations = listOf(
                AndFilter(
                    operations = listOf(
                        StringListContainsFilter(
                            field = "userId", operationType = StringQueryOperationType.IN, values = userIds
                        )
                    )
                )
            )
        )
        val createSegmentRequest = CreateSegmentRequest(
            name = "segment-name", attribute = filter, type = SegmentType.STATIC
        )
        val segment = Segmentation(attribute = filter, name = "segment-name", type = SegmentType.STATIC, appId = "app-id" )
        `when`(segmentationRepository.save(any())).thenReturn(segment)

        `when`(segmentMetaService.saveSegmentInfo(createSegmentRequest, "app-id")).thenReturn(segment)
        val createdSegment = segmentService.createSegmentFromUserIds(userIds = userIds, name = "segment-name", appId = "app-id")
        assertEquals(segment, createdSegment)
    }
}

but I am facing this error:
kotlin.UninitializedPropertyAccessException: lateinit property id has not been initialized

So what am I doing wrong here?
How can I initialize the Id? or should I refactor my code so for it to become testable?

A: I think you are mocking / providing the answers to the wrong calls.

*

*you mock segmentationRepository.save(..) but this call won't ever be made since that call is inside segmentMetaService.saveSegmentInfo(...) which is mocked so the real code is not called.

*when you call segmentService.createSegmentFromUserIds(..), my guess (stack trace would be useful on the error, BTW), is that this method proceeds passed the invocation of segmentMetaService.saveSegmentInfo(...) but in the next line you call querySegmentService.runUpdateQuery(users = userIds, appId = appId, segmentId = segmentation.id) which is accessing the uninitialised id.

The fix will be to set the segment.id when you set up the object for the answer to segmentMetaService.saveSegmentInfo(..)


text:
Q: How do I add missing rows (filled with 0's) in a data frame using some column as reference? I have this (big) data frame and I want to add the missing rows (filled with 0's) in relation to the column named "date".
For example:
date    0        1         2          3         4         5
199807  0       546.98     19355.55   1110.6    4720.34   3435.9
199808  0       1668.85    4398.29    5816.71   599.7     535.28
199809  608.79  446.68     2297.68    1862.64   415.6     933.46
199811  0       0          1366.59    1337.01   0         711.59
199812  0       0          601.8      2079.9    2030.24   368.44
199901  0       1462.8     0          552.78    0         0
199903  0       621.2      2242       753.36    0         0

And I would like this:
date    0        1        2            3         4          5
199807  0        546.98   19355.55     1110.6    4720.34    3435.9
199808  0        1668.85  4398.29      5816.71   599.7      535.28
199809  608.79   446.68   2297.68      1862.64   415.6      933.46
199810  0        0        0            0         0          0
199811  0        0        1366.59      1337.01   0          711.59
199812  0        0        601.8        2079.9    2030.24    368.44
199901  0        1462.8   0            552.78    0          0
199902  0        0        0            0         0          0
199903  0        621.2    2242         753.36    0          0

Thank you very much

A: It can be done as follows:
1) Create a placeholder dataset with all dates and zeros in all other columns
2) for dates, which are in the original dataset, write values from original to placeholder dataset
# Create a placeholder dataset, including all dates, 0 at all other columns
df <- data.frame(date = c(199801:199812, 199901:199912),
                 `1` = 0, `2` = 0, `3` = 0, check.names = FALSE)

# create the dataset with some data (this will be the 'original' dataset)
df2 <- data.frame(date = c(199807:199809, 199811:199812, 199901:199903),
                  `1` = rnorm(8), `2` = rnorm(8), `3` = rnorm(8), check.names = FALSE)

# write data from original dataset to placeholder dataset
df[df$date %in% df2$date,] <- df2


text:
Q: Spring Controller init method as far as I understand are spring controllers stateless right? If I set a field to a value, this is revoked by the next call.
Is there a possibility to add a init-method or something? A method which is called once, when my controller is triggerd? I'm using spring 3.0 and a annotation configuration atm.

A:
As far as I understand are spring controllers stateless right? If I set a field to a value, this is revoked by the next call.

I believe that is incorrect: Spring controllers can be stateful.  You should be very careful though because a Controller is expected to be re-entrant and thread-safe and to support multiple threads simultaneously executing multiple requests.
It is probably safe to say that it best practice for a controller to be designed to be effectively stateless; i.e. no state that changes while the controller is "live".

Is there a possibility to add a init-method or something?

It is not entirely clear what you mean.  However:

*

*The controller's handleRequest is called to start a request.

*If you declare any bean (e.g. a controller bean) as ApplicationContextAware it will be called back to inform it of the ApplicationContext.

*If you declare any bean as ServletContextAware it will be called back to inform it of the ServletContext.

*If you declare any bean as an InitializingBean it will be called back when all properties have been set.

And there are doubtless other callbacks and hooks that you could use to trigger some delayed initialization / context setting.
(I'm not sure how these callbacks / hooks map to annotations ... but I'm sure that they do.)

A: Spring Controllers should be handled stateless by default, that is correct. Nevertheless this does not mean your value will be revoked by the next call. From the programmers perspective it is not decidable if you end up with same instance of your controller or a different instance. It is further more not assured that no one else used the controller (and therefore changed its state in the meantime). This is why it is not advisable to save any state at all in fields of your controller. Maybe you should reconsider the need for a field in your controller.
In fact there is a init method for spring beans. You can simply annotate a public void method on your controller with @PostConstruct. This method is executed after dependencies have been injected. Thus, this method is invoked exactly ones after the controller instance is created.
As far as I understand your question you look for some method that is executed before every call to a method of your controller. In that case you could simply at a call to your "init"-method in the beginning of each of your controller methods. If you dont want to do this explicit in your code AOP provide you an alternative.


text:
Q: Suddenly my PC stops recognizing PCIe video card My PC specs:

*

*Intel Core i5 2400

*Intel DH61WW Motherboard

*4 GB RAM

*500 W Gigabyte PSU

*XFX GeForce GTS 250

*Windows 7 Ultimate

*Custom make, bought on July 2011 except the graphics card, which I bought 2 years ago

Well, it's a mid range gaming PC and I play games a lot. The PC and monitor are connected to a UPS.
Yesterday I was playing Skyrim. Just crossed 52 hours of gameplay. Suddenly it crashed. It happened once before and Skyrim is known to be full of bugs despite I'm playing 1.3 patch. I restarted the game.
After playing about 1-2 minutes, my monitor goes dark. At first I though there was a power loss somehow. But the power indicator was turned on. The monitor goes to stand by mode after showing a message that it is no longer getting any video signal.
I was able to run the computer using build in video adapter. Then after 30 minutes of trial and error, I found that the PC is no longer detecting the graphics card. I checked the power supply to the graphics card, the fan was spinning. I plugged off the card, removed dust from it, plugged it in, connected the power supply, found the fan spinning but the BIOS confirmed that there is nothing in the PCIe slot. The board only has one PCIe slot.
I don't have another PC to test the card, nor do I have anything to test the PCIe slot itself. The only thing I can do is to take the PC to my vendor.
Before taking it to my vendor, is there anything else I can try? I can't do much with the hardware, but want to try some software that may tell me whether the graphics card or the PCIe slot is damaged or something else happened.


text:
Q: Busqueda según count de una propiedad de navegacion - C# - ASP.NET - MVC Buen día.
De antemano muchas gracias por cualquier ayuda que me puedan brindar.
Actualmente estoy trabajando sobre un proyecto generado con ASP.NET y se me presento un problema al intentar generar 2 listas que voy a utilizar para mostrar un ranking en la vista.
Este es el codigo que hice, el cual evidentemente esta mal, porque puse un breakpoint para verificar y nunca toma valores el mismo, es decir que estoy plantenando mal la busqueda.
        var miembros = _context.Miembros
            .ToList()
            .OrderBy(miembro => miembro.Entradas.Count)
            .Where(miembro => miembro.Entradas.Count > 0)
            .Take(3);

        var topEntradas = _context.Entradas
            .ToList()
            .OrderBy(e => e.Preguntas.Count)
            .Where(e => e.Preguntas.Count > 0)
            .Take(5);

Para dar un poco de contexto. En el caso de los miembros, tienen una lista de entradas realizadas, así que necesito traer los 3 miembros con más entradas generadas.
Las entradas tienen una listado de preguntas, y de igual forma me gustaria tener las 5 con más preguntas generadas.
Quedo atento a cualquier dato extra que necesien y de nuevo muy agradecido con cualquier comentario que me pueda ayudar.

Muchas gracias por la pronta respueta y la bienvenida.
Si, se que es algo complicado poder simplificar todo en una pregunta.
Como referencia, este codigo me funciona correctamente
var ultimas5 = _context.Entradas
            .ToList()
            .OrderBy(ultimas5 => ultimas5.Fecha)
            .Take(5);

El problema surge cuando le agrego el Count.
Toda la razón, un dato bastante importante, al intentar acceder a la lista desde la vista (lo estoy haciendo con un ciclo foreach), me arroja la excepción.
ArgumentNullException: Value cannot be null. (Parameter 'source')
System.Linq.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument)
Esta salta cuando llega a la linea de donde esta el Count.

A: Espero esta consulta te sirva:
var miembros = (from m in _context.Miembros
                select new
                {
                  m.Campo1,
                  m.Campo2,
                  m.CampoN,
                  Total = m.Entradas.Count()
                }).Where(m2 => m2.Total > 0).
                   OrderByDescending(m2 => m2.Total).
                   Select(m2 => new
                   {
                     m2.Campo1,
                     m2.Campo2,
                     m2.CampoN
                     //No se pondria m2.Total
                   }).Take(3).ToList();

Aquí usamos las palabras claves select new para construir un objeto anónimo, el cual tendrá todos los campos del objeto miembro, y tendrá además, un campo adicional llamado Total que seria el total de entradas por cada objeto miembro. Esto devolverá un IEnumerable donde cada elemento de ese IEnumerable será un objeto anónimo con todos los campos propios del objeto miembro y el nuevo campo Total.
A este IEnumerable se le aplica el método extensor Where donde se filtraran todos los objetos anónimos que cumplan con la condición Total > 0, posterior a este filtro se ordena descendentemente por el campo Total y por ultimo aplicando el método extensor Select se construye un nuevo objeto anónimo, con todos los campos que te interesen, posteriormente se tomarían los tres primeros elementos.


text:
Q: Fill Color of Multiple Drawlines that Intersect Forming Closed Shape I needed to draw a Car using Java and Graphics2D. I used multiple    basicstrokes to come up with the shape of the car. How do I fill it with color? An example would be drawing 3 lines in the shape of a triangle and then wanting to fill it with color.

A: You can not simply fill a shape that was only created by drawing three lines. You have to define the shape, including all the lines that it consists of.
How exactly this is implemented depends on serveal factors. For example, whether you want to use the same stroke for all three lines, or whether they need different strokes.
It could be helpful if you had already provided some information of how exactly you are drawing the lines at the moment. I'll try to make a guess here...
So assuming that your current code roughly looks like this:
void paintCar(Graphics2D g)
{
    g.setStroke(new BasicStroke(1.0f));
    g.setColor(Color.BLUE);

    // Draw the triangle
    g.drawLine(100,100,200,100);
    g.drawLine(100,200,150, 50);
    g.drawLine(150, 50,100,100);
}

the easiest way to additionally fill this triangle would be to change it as follows:
void paintCar(Graphics2D g)
{
    g.setStroke(new BasicStroke(1.0f));
    g.setColor(Color.BLUE);

    Path2D path = new Path2D();

    // Build the triangle
    path.append(new Line2D.Double(100,100,200,100), false);
    path.append(new Line2D.Double(100,200,150, 50), true);
    path.append(new Line2D.Double(150, 50,100,100), true);

    // Draw the triangle
    g.draw(path);

    // Fill the triangle, with a different color
    g.setColor(Color.CYAN);
    g.fill(path);
}

But note...
... that there are more elegant and concise ways of achieving this. Usually, one would not append individual Line2D segments, but simply use the Path2D to build the shape:
void paintCar(Graphics2D g)
{
    g.setStroke(new BasicStroke(1.0f));
    g.setColor(Color.BLUE);

    // Build the triangle
    Path2D path = new Path2D();
    path.moveTo(100,100);
    path.lineTo(200,100);
    path.lineTo(150, 50);
    path.closePath();

    // Draw the triangle
    g.draw(path);

    // Fill the triangle, with a different color
    g.setColor(Color.CYAN);
    g.fill(path);
}

So if you have the coordinates of your shape in an appropriate form (maybe stored as a list of Point2D objects), you may more easily build a shape that you can draw and fill then.


text:
Q: Comparing equality of Collections in JPA First of all i'll demonstrate backgorund of this problem...
I tried to make fast and redudant-free implementation of a repository. Problematic object looks like this:
class SomeObject {
    @Id
    private Long id;
    private List<SomeData>;
    private List<SomeOtherData>;

    ....
}

SomeData and SomeOtherData are Entities, and they're normally mapped by JPA. Later i've made SomeObject instances immutable, which enables some further optimalization. SomeObject becomed interchangeable, and i don't want to make duplicates in db. In order to find possible duplicate i need to compare those lists.
The main question arises: How to check equality of SomeData collection in SomeObject (order is meaningless) with some arbitrary collection of SomeData (supilled as parameter) ?
I've tried workaround by combining JPA SIZEOF and dozens of MEMBER BY to ensure equality of both collections. It worked but performance was absolutely horrible.

A: Using HashSet's and implementing hashcode/equals in your two classes might solve your problem, you could also use a @PrePersist method to ensure that you applying the filter consistently. If you need more complicated filtering maybe look into org.apache.commons.collections.CollectionUtils. It is assumed that you are also using a unique constraint in your database if duplicates are not acceptable.


text:
Q: Parent directories of a source file How could I get the adress of a c++ source's parent directory (and all directories of higher level) - from within the code itself? I.e. program created from the source can access said directories without me specifying them.

A: You can use the __FILE__ macro to get the path of the source file. Then by applying string manipulation techniques you can simply get the parent directory.
More info here.

A: Some compilers support the __FILE__ macro, you can use to get a character literal with the full path of your source file.
You can extract the parent directory names from this literal if it's available.

But what's your use case for doing so actually?
I have some doubts about your deployment strategies, possibly in question.
If you rely on source directory structures, to e.g. load further resource files, that's not portable for potential target environments, that only have your executable artifacts installed. You may reconsider your deployment and configuration strategies.


text:
Q: How can I retrieve this element in firebase realtime? I am saving items to firebase and I get the following structure

I am using the following code to try to retrieve the descripcion and precio data that is inside the second child
 DatabaseReference itemFactura = FirebaseDatabase.getInstance().getReference().child("factura");
 itemFactura.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        if(dataSnapshot.exists()){
            int cantidad = 0;

            for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                if(Boolean.parseBoolean(snapshot.child("estado").getValue().toString())){
                            ArrayList<String> elementos = new ArrayList<String>();
                            elementos.add(snapshot.child("descripcion").getValue().toString());
                            elementos.add(snapshot.child("precio").getValue().toString());
                            tabla.agregarFilaTabla(elementos);
                            cantidad = Integer.parseInt(snapshot.child("precio").getValue().toString()) + cantidad;
                }
            }
            cantidadTotal.setText(String.valueOf(cantidad));
        }

    }

But it marks me a null because it can't find them

A: You have two nested levels with dynamic keys in your JSON, so you need two nested loops over getChildren() in your onDataChange:
DatabaseReference itemFactura = FirebaseDatabase.getInstance().getReference().child("factura");
 itemFactura.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if(dataSnapshot.exists()){
            int cantidad = 0;
            for (DataSnapshot level1snapshot : dataSnapshot.getChildren()){
                for (DataSnapshot level2snapshot : level1snapshot.getChildren()){
                    if(level2snapshot.child("estado").getValue(Boolean.class) != null){
                        ...


text:
Q: Reset JSF form fields I know a lot has been going around this topic, but all the solutions point out to creating a reset button ... is there no way of just clearing the fields and re-populating them ?
Here is what is my code
<p:commandButton id="basic" value="#{c.machine}" action="#{updateEntry.setMachine(c.machine)}" oncomplete="dlg1.show();" styleClass="ui-Machinebutton"/>

This sets the value 'machine' in 'updateEntry' and once completed launches the dialog box 'dlg1'
Dialog Box
<p:dialog id="Update_Entry" header="Update Entry" widgetVar="dlg1" modal="true" height="250" dynamic="True" resizable="False">
                    <h:form prependId="false" id="Update_Entry_Form" method="post" autocomplete="off">

                            <h:panelGrid id="update_grid" columns="2" style="margin-bottom:10px">

                                <f:facet name="header">
                                    <p:messages />
                                </f:facet>
                                <h:outputLabel for="machine" value="Machine *" />
                                <p:inputText id="machine" value="#{updateEntry.machine}" required="true" requiredMessage="Machine is required">
                                    <f:validateLength minimum="5" maximum="5"/>
                                </p:inputText>

The form loads the value fine for the first time, but it always loads the previous value even if updateEntry.machine is updated. How do i clear this off automatically ? I am using PrimeFaces

A: You forgot to ajax-update the dialog's content before opening. That's why it's always showing initial content as it was when the page was rendered for the first time or when the dialog was closed for the last time.
Do so accordingly:
<p:commandButton ... update=":Update_Entry">


text:
Q: gem install nmatrix failed When I type in the command gem install matrix. It report an "fatal" error that the stdio.h is missing! why? and how to fix it? Thank you! The bug report below:
Building native extensions.  This could take a while...

ERROR:  Error installing nmatrix:
ERROR: Failed to build gem native extension.

/Users/apple/.rvm/rubies/ruby-2.2.2/bin/ruby -r ./siteconf20151212-6597-v5fw6g.rb extconf.rb

/Users/apple/.rvm/rubies/ruby-2.2.2/include/ruby-2.2.0/ruby/defines.h:26:19: fatal error: stdio.h: No such file or directory

checking for apparent GNU g++ binary with C++0x/C++11 support... 4.9
using C++ standard... c++11
g++ reports version... gcc
creating nmatrix_config.h
creating Makefile

make "DESTDIR=" clean

make "DESTDIR="
compiling nmatrix.cpp
In file included from /Users/apple/.rvm/rubies/ruby-2.2.2/include/ruby-2.2.0/ruby/ruby.h:29:0,
                 from /Users/apple/.rvm/rubies/ruby-2.2.2/include/ruby-2.2.0/ruby.h:33,
                 from nmatrix.cpp:34:
/Users/apple/.rvm/rubies/ruby-2.2.2/include/ruby-2.2.0/ruby/defines.h:26:19: fatal error: stdio.h: No such file or directory
 #include <stdio.h>
                   ^
compilation terminated.
make: *** [nmatrix.o] Error 1

make failed, exit code 2

A: The error is similar to a bunch other questions, for them this seemed to fix it.
xcode-select --install


text:
Q: how to show login error if i type a wrong password that was not saved in my mysql database? how to show login error if i type a wrong password that was not saved in my mysql database?
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/" + sdbName,"root","");
stmt = con.createStatement();
session.putValue("CONN",con);
session.putValue("STMT",stmt);

rsT = stmt.executeQuery("select count from users1 where pword='" + spword + "' and uname='"+suname+"'");
if(rsT.next())
{

String result = rsT.getString(1);
}
rsT.close();

if(errFlag)
{
%> <%=str%> <%
return;
}
stmt = null;
con = null;
rsT = null;
}
catch(SQLException sqle)
{
str = "
Error : " + sqle + "
";
errFlag = true;
}
%>

how to show login error if i type a wrong password that was not saved in my mysql database?
I would like to display the alert message when the error user id and password was typed in textbox

A: Few pointers:
(1) Normally, you don't want to save the passwords in the DB.
You want to save their only a hashcode produced from the password.
For example every time you get the password you convert it to sha256 or something like that and then you work with that 'sha256 password'.
Java has digest api and can do the sha encoding for you.
Example: https://www.geeksforgeeks.org/sha-256-hash-in-java/
(2) You don't want to have code like that:
rsT = stmt.executeQuery("select count from users1 where pword='" + spword + "' and uname='"+suname+"'");

The code above is very susceptive to injection attacks. You want to leverage the java prepared statements and inject the parameters into it and make your query look like that:
 "select count from users1 where pword=? and uname=?"

Example: https://www.javatpoint.com/PreparedStatement-interface
I hope all that helps you and good luck in you efforts


text:
Q: Cant load data onto Jupyter docker This is probably a obvious question, but i cant find a direct answer anywhere.
I installed, docker and docker machine, no problems so far.
After that, i pulled this imaged based on jupyter/datascience-notebook docker. Supposedly, the only diffences is that it has Open CV installed.
Now, this is my first time using docker. I run the jupyter notebook using this command on bash:
docker run -d -p 8888:8888 -v $(pwd)/WD:/notebook dash00/datascience-notebook-opencv

This succeed in loading the jupyter notebook, it loads packages and works for every python command i try. For example, if a define functions and try them, they work.
The problem is that when i try to load data, for example:
Import pandas as pd
data=pd.read_csv("/home/mario/WD/test.csv")

i get the following error: "OSError: File b'/home/mario/WD/train.csv' does not exist"
the same happens when i try to load any kind of file using any kind of package, including images using cv2
Am i referencing the path wrong? do i have to refer to a host machine?

A: From your docker command, you mounted /home/mario/WD into the container as /notebook (as a host volume). Therefore inside your container, you would use:
Import pandas as pd
data=pd.read_csv("/notebook/test.csv")

A: The -v $(pwd)/WD:/notebook argument is mounting the $(pwd)/WD directory on your host to /notebook in your container. If the directory that you issued docker run … from is /home/mario, then you would find /home/mario/WD/test.csv at /notebook/test.csv in the container.
Import pandas as pd
data=pd.read_csv("/notebook/test.csv")

You can also mount more directories from your host into the container as appropriate.


text:
Q: How to Save the optins in a text file without disturbing the email notif I am using a custom optin page with a form , I want to tweak it a little bit,

*

*I want to save all the optins on a txt file on the server without
disturbing the other functions of the form.

*2nd thing I want is to show a custom Page after the optin form is
submitted.
Currently the form works like this
USER SUBMITS > PAGE REFRESHES FOR HIM > I GET AN EMAIL WITH THE SUBMITTED DATA.
Here is the form code

Fill This Out and See Your
Timeshare Report

                    <form name="contactform" action="mail-script.php" method="POST">
                        First Name:
                            <input type="text" name="fname" id="fname" />

                        Last Name:
                            <input type="text" name="lname" id="lname" />

                        Email Address:
                            <input type="text" name="email" id="email" />

                        Phone Number:
                            <input type="text" name="phone" id="phone" />

                        Alternate Phone:
                            <input type="text" name="phone" id="aphone" />

                        Resort Name:
                            <input type="text" name="resort" id="resort" />

                        Amount Owed? $:
                            <input type="number" name="amount" id="amount" />

                            If Paid Off Leave Zero, Else Put Amount

I'm Considering To

                                <input type="checkbox" name="call" id="" value="sell"/> Sell It

                                <input type="checkbox" name="call" id="" value="buy"/> Buy It

                                <input type="checkbox" name="call" id="" value="rent "/> Rent  It

                                <input type="checkbox" name="call" id="" value="cancel"/> Cancel Mortgage

                                <input type="checkbox" name="call" id="" value="ownership"/> End Ownership

                                <input type="checkbox" name="call" id="" value="give"/> Give It Back

                            <img src="captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' >

                            Enter the code above here :

                            <input id="6_letters_code" name="6_letters_code" type="text">

                            Can't read the image? click here to refresh

                        <input id="submit" type="submit" value="" />

Ensure all fields are completed and correct, allowing you more benefits, while preventing abuse of our data.

                    </form>

This is the mail script which sends me the email
<?php
/* Set e-mail recipient */

$myemail  = "**MYEMAIL**";

/* Check all form inputs using check_input function */
$fname    = check_input($_POST['fname'], "Enter your first name");
$lname    = check_input($_POST['lname'], "Enter your last name");
$email    = check_input($_POST['email']);
$phone    = check_input($_POST['phone']);
$resort   = check_input($_POST['resort']);
$amount   = check_input($_POST['amount']);
$call     = check_input($_POST['call']);

/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
    show_error("E-mail address not valid");
}

/* If URL is not valid set $website to empty */
if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i", $website))
{
    $website = '';
}

/* Let's prepare the message for the e-mail */
$message = "Hello!

Your contact form has been submitted by:

First Name : $fname
Last Name : $lname
E-mail: $email
Phone : $phone
Resort: $resort
Amount: $amount
Call  : $call

End of message
";

/* Send the message using mail() function */
mail($myemail, $subject, $message);

/* Redirect visitor to the thank you page */
header('Location: index.html');
exit();

/* Functions we used */
function check_input($data, $problem='')
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    if ($problem && strlen($data) == 0)
    {
        show_error($problem);
    }
    return $data;
}

function show_error($myError)
{
?>
if (strtolower($_POST['code']) != 'mycode') {die('Wrong access code');}

    Please correct the following error:

    <?php echo $myError; ?>

<?php
exit();
}
?>

Here is the online url of the page http://timesharesgroup.com/sell/index.html

A: you can add this code to your script after all the validation is done:
$text = "$fname\n$lname\n$email\n$phone\n$resort\n$amount\n$call\n\n";
file_put_contents('file.txt', $text, FILE_APPEND);

OR even better csv file:
$fields = array($fname,$lname,$email,$phone,$resort,$amount,$call);

$fp = fopen('file.csv', 'a');
fputcsv($fp, $fields);
fclose($fp);


text:
Q: a simple function is approximated by a step function with respect to $L^p$. (proof verification)

This proposition tells that there exists a step function that can approximate a simple function. But, I don't understand one step in this proof:
$||\chi_A - \chi_{\mathcal{U}}||_p = [m(A \Delta \mathcal{U})]^{1/p}$.
I think $||\chi_A - \chi_{\mathcal{U}}||_p = (\int |\chi_A - \chi_{\mathcal{U}}|^p)^{1/p}.$ But, how can $\int |\chi_A - \chi_{\mathcal{U}}|^p = m(A \Delta \mathcal{U})$?

A: Think about what $\chi_A - \chi_U$ is. We have
$$\chi_A(x) - \chi_U(x) = \begin{cases} 0 & x \in A \cap U \text{ or } x \notin A \cup U \\
      1 & x \in A \setminus U \\
      -1 & x \in U \setminus A
   \end{cases}$$
So $\int |\chi_A - \chi_U|^p = \int_{A \setminus U} 1 + \int_{U \setminus A} 1 = m(A \setminus U) + m(U \setminus A) = m([A \setminus U] \cup [U \setminus A]) = m(A \Delta U)$.


text:
Q: Missing lines in OpenGL tesselation shader I am learning tesselation shaders and followed a link from the OpenGL wiki to:
http://voxels.blogspot.de/2011/09/tesselation-shader-tutorial-with-source.html
I ported the quad tesselation example to Mac OS X but it only renders half of the lines at the outer level. If I change ccw to cw in the tesselation evaluation shader it renders the other half, but not both at once.
Expected (simplified):
---------
|\|\|/|/|
---------
|/|/|\|\|
---------

Actual (ccw):
     ----
|\|\|/|/
---------
 /|/|\|\|
-----

Actual (cw):
-----
 \|\|/|/|
---------
|/|/|\|\
    -----

Here is the source code (Please let me know if it doesn't compile):
#define GLFW_INCLUDE_GLCOREARB
#include <GLFW/glfw3.h>

#include <iostream>
#include <string>

static GLuint program;
static GLuint vbo;
static GLuint vao;

GLuint compileShader (const std::string& source, GLenum type)
{
  const GLchar*const src = source.c_str ();

  const GLuint shader = glCreateShader (type);
  glShaderSource (shader, 1, &src, NULL);
  glCompileShader (shader);

  return shader;
}

void initializeShaders ()
{
  const std::string vert_source =
      "#version 410 core\n"

      "layout(location = 0) in vec4 vertex;"

      "void main(void)"
      "{"
      "  gl_Position = vertex;"
      "}";

  const std::string tesc_source =
      "#version 410 core\n"

      "layout(vertices = 4) out;"

      "void main(void)"
      "{"
      "  gl_TessLevelOuter[0] = 2.0;"
      "  gl_TessLevelOuter[1] = 4.0;"
      "  gl_TessLevelOuter[2] = 6.0;"
      "  gl_TessLevelOuter[3] = 8.0;"

      "  gl_TessLevelInner[0] = 8.0;"
      "  gl_TessLevelInner[1] = 8.0;"

      "  gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;"
      "}";

  const std::string tese_source =
      "#version 410 core\n"

      "layout(quads, equal_spacing, ccw) in;"

      "vec4 interpolate(in vec4 v0, in vec4 v1, in vec4 v2, in vec4 v3)"
      "{"
      "  vec4 a = mix(v0, v1, gl_TessCoord.x);"
      "  vec4 b = mix(v3, v2, gl_TessCoord.x);"
      "  return mix(a, b, gl_TessCoord.y);"
      "}"

      "void main()"
      "{"
      "  gl_Position = interpolate("
      "    gl_in[0].gl_Position,"
      "    gl_in[1].gl_Position,"
      "    gl_in[2].gl_Position,"
      "    gl_in[3].gl_Position);"
      "}";

  const std::string geom_source =
      "#version 410 core\n"

      "layout(triangles, invocations = 1) in;"
      "layout(line_strip, max_vertices = 3) out;"

      "void main(void)"
      "{"
      "  gl_Position = gl_in[0].gl_Position;"
      "  EmitVertex();"
      "  gl_Position = gl_in[1].gl_Position;"
      "  EmitVertex();"
      "  gl_Position = gl_in[2].gl_Position;"
      "  EmitVertex();"

      "  EndPrimitive();"
      "}";

  const std::string frag_source =
      "#version 410 core\n"

      "layout(location = 0, index = 0) out vec4 fragColor;"

      "void main(void)"
      "{"
      "  fragColor = vec4(1.0,0.0,0.0,1.0);"
      "}";

  const GLuint vert = compileShader (vert_source, GL_VERTEX_SHADER);
  const GLuint tesc = compileShader (tesc_source, GL_TESS_CONTROL_SHADER);
  const GLuint tese = compileShader (tese_source, GL_TESS_EVALUATION_SHADER);
  const GLuint geom = compileShader (geom_source, GL_GEOMETRY_SHADER);
  const GLuint frag = compileShader (frag_source, GL_FRAGMENT_SHADER);

  program = glCreateProgram ();

  glAttachShader (program, vert);
  glAttachShader (program, tesc);
  glAttachShader (program, tese);
  glAttachShader (program, geom);
  glAttachShader (program, frag);

  glLinkProgram (program);

  glDetachShader (program, vert);
  glDetachShader (program, tesc);
  glDetachShader (program, tese);
  glDetachShader (program, geom);
  glDetachShader (program, frag);

  glDeleteShader (vert);
  glDeleteShader (tesc);
  glDeleteShader (tese);
  glDeleteShader (geom);
  glDeleteShader (frag);
}

void deinitializeShaders ()
{
  glDeleteProgram (program);
}

void initializeVBOandVAO ()
{
  glGenBuffers (1, &vbo);
  glGenVertexArrays (1, &vao);

  glBindVertexArray (vao);
  glBindBuffer (GL_ARRAY_BUFFER, vbo);
  glEnableVertexAttribArray (0);
  glVertexAttribPointer (0, 4, GL_FLOAT, GL_FALSE, 0, NULL);
  glBindVertexArray (0);
}

void deinitializeVBOandVAO ()
{
  glDeleteVertexArrays (1, &vao);
  glDeleteBuffers (1, &vbo);
}

void uploadVertices ()
{
  const int n_vert = 16;
  const float vert [n_vert] =
  {
    -0.9f , -0.9f , 0.0f , 1.0f,
     0.9f , -0.9f , 0.0f , 1.0f,
     0.9f ,  0.9f , 0.0f , 1.0f,
    -0.9f ,  0.9f , 0.0f , 1.0f
  };

  glBindBuffer (GL_ARRAY_BUFFER, vbo);
  glBufferData (GL_ARRAY_BUFFER, n_vert * sizeof (float), vert, GL_STATIC_DRAW);
  glBindBuffer (GL_ARRAY_BUFFER, 0);
}

void draw (GLFWwindow* window)
{
  glClearColor (0.0f, 0.0f, 0.0f, 1.0f);
  glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  glUseProgram (program);
  glBindVertexArray (vao);

  glPatchParameteri (GL_PATCH_VERTICES, 4);
  glDrawArrays (GL_PATCHES, 0, 4);

  glBindVertexArray (0);
  glUseProgram (0);

  glfwSwapBuffers (window);
}

void error_callback (int error, const char* description)
{
  std::cerr << "Error " << error << ": " << description << std::endl;
}

int main ()
{
  glfwSetErrorCallback (error_callback);
  if (!glfwInit ())
  {
    return 1;
  }

  glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 4);
  glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 1);
  glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  GLFWwindow* window = glfwCreateWindow (480, 360, "Tesselation", NULL, NULL);
  if (!window)
  {
    glfwTerminate ();
    return 1;
  }

  glfwMakeContextCurrent (window);

  initializeShaders ();
  initializeVBOandVAO ();
  uploadVertices ();

  int width = -1, height = -1;
  glfwGetFramebufferSize (window, &width, &height);
  glViewport (0, 0, width, height);

  while (!glfwWindowShouldClose (window))
  {
    draw (window);
    glfwWaitEvents ();
  }

  deinitializeShaders ();
  deinitializeVBOandVAO ();

  glfwDestroyWindow (window);
  glfwTerminate ();

  return 0;
}

I am using GLFW 3.1 from macports (glfw @20150106).


text:
Q: Question about the range of a norm preserving extension. Consider the subspace $Y =\{(x, x): x\in \mathbb{C}\}$ of the normed linear space $(\mathbb{C}^2, \|\ \|_{\infty})$.
If $\phi$ is a bounded linear functional on  $Y$,  defined by $\phi(x, x)=x$, then which one of the following sets is equal to
$$\big\{\psi(1, 0): \psi \ \text{is a norm preserving extension of}\ \phi\ \text{to}\ (\mathbb{C}^2, \|\ \|_{\infty})\big\}, \ \|(x, y)\|_{\infty}= \sup\{|x|, |y|\} $$

*

*$\{1\}$

*$[0, 1]$
My attempt: It can be easily shown that $\|\phi\|_{\infty}=1$. Since $\psi$ is a norm preserving extension, so $$\|\psi\|_{\infty}= \|\phi\|_{\infty}=1$$ Now as $\|(1, 0)\|_{\infty}= 1$, so this means $\psi(1, 0)\leq 1$. How to conclude further?

A: Any linear functional on $\mathbb C^2$ is of the form $\psi((x,y)) = a x + b y$ for some constants $a$ and $b$.  This is easily seen to have norm $|a|+|b|$.  Now you want
$ax + b x = x$, i.e. $a+b=1$, and $|a|+|b|=1$, and you want to know what can $a$ be.  If $a \in [0,1]$, what should you take for $b$?


text:
Q: Simplify this expansion : $\omega=(28+(\frac{5290}{3})^{\frac{3}{2}})^{\frac{1}{3}}+(28-(\frac{5290}{3})^{\frac{3}{2}})^{\frac{1}{3}}$ Find a simple closed form of :
$\omega=(28+(\frac{5290}{3})^{\frac{3}{2}})^{\frac{1}{3}}+(28-(\frac{5290}{3})^{\frac{3}{2}})^{\frac{1}{3}}$
My try :
Let :
$A=(28+(\frac{5290}{3})^{\frac{3}{2}})^{\frac{1}{3}}$
And
$B=(28-(\frac{5290}{3})^{\frac{3}{2}})^{\frac{1}{3}}$
Now :
$A^{3}+B^{3}=56$
But how I can now find $A$ and $B$ ?

A: I would write
$$(28+x)^{1/3}+(28-x)^{1/3}=s$$ and now raise this to the power three.

A: Given
$$\omega=\sqrt[3]{28+(\frac{5290}{3})^{\frac{3}{2}}}+\sqrt[3]{28-(\frac{5290}{3})^{\frac{3}{2}}}$$
Let $A=\sqrt[3]{28+(\frac{5290}{3})^{\frac{3}{2}}}\Rightarrow A^3=28+(\frac{5290}{3})^{\frac{3}{2}}$
and $B=\sqrt[3]{28-(\frac{5290}{3})^{\frac{3}{2}}}\Rightarrow B^3=28-(\frac{5290}{3})^{\frac{3}{2}}$.
Notice that $A^3+B^3=56$.
Also, $AB=\sqrt[3]{\big(28+(\frac{5290}{3})^{\frac{3}{2}}\big)\big(28-(\frac{5290}{3})^{\frac{3}{2}}\big)}=\sqrt[3]{28^2-(\frac{5290}{3})^3}=-\frac23\sqrt[3]{18504483479}$.
So we can write
\begin{align}
\omega&=A+B\\
\omega^3&=A^3+3A^2B+3AB^2+B^3=A^3+B^3+3AB\cdot(A+B)\\
\omega^3&=56+3(-\frac23\sqrt[3]{18504483479})\ \omega\\
\omega^3&=56-2\sqrt[3]{18504483479}\ \omega\\
\end{align}
At the end of the day, you are solving the cubic equation
$$\omega^3+2\sqrt[3]{18504483479}\ \omega-56=0\\$$
There has got to be a typo somewhere.

A: As you did, let
$$ A=(28+(\frac{5290}{3})^{\frac{3}{2}})^{\frac{1}{3}}, B=(28-(\frac{5290}{3})^{\frac{3}{2}})^{\frac{1}{3}}. $$
Then
$$ A^3+B^3=56, AB=-\frac23 (18504483479)^{1/3}. $$
Let $z=A+B$ and then
$$ A^3+B^3=(A+B)[(A+B)^2-3AB]=z^3+2(18504483479)^{1/3}z=56. $$
So $z=A+B$ satisfies
$$ z^3+2(18504483479)^{1/3}z-56 = 0. $$


text:
Q: Setting Default value when Object mapping in Red-Gate Data Compare I am using Red-Gate Data Compare to synchronize two databases, lets call them DBSource and DBDestination.  DBDestination has a table, TableA which has a field which has a not null constraint.  TableA within DBSource has the same structure, apart from this new field.
When I synchronize using the Data Compare tool, it fails due to this particular not null field, since there's no object map I can set up for it.
I wanted to know if there is a way of setting a default on the tool, since I can't alter the schema of the destination table and the file is quite large to edit?

A: The best way to handle this is to alter the column in the database and put a default value on it. There isn't anything you can do in the SQL Data Compare settings to make it replace illegal NULL data with a default value.


text:
Q: search feature not work for certain words The problem I faced is when search word "anti" it will display the product but when search based words "anti wrinkle" mentioned no search result. Please refer below for the code and advice what do I missed.
$search_output = '';

if(isset($_POST['search'])) {
    $searchsql = $_POST['search'];
    $searchsql = preg_replace('#[^a-z 0-9?!@-]#i', '', $searchsql);

    $query = mysql_query("SELECT tb_spa_prd.*, tb_spa_prd_cat.spa_prd_cat FROM tb_spa_prd AS tb_spa_prd INNER JOIN tb_spa_prd_cat ON tb_spa_prd.spa_prd_cat_id = tb_spa_prd_cat.spa_prd_cat_id WHERE spa_prd_cat LIKE '%$searchsql%' or spa_prd_code LIKE '%$searchsql%' or spa_prd_name LIKE '%$searchsql%'")  or die ("Could no search!");
    $count = mysql_num_rows($query);
    if($count == 0) {
        $search_output .= '

                            There was no search results!

';
    } else {
        $row_no = 1;
        while($row = mysql_fetch_array($query,MYSQL_ASSOC)) {
            $spa_prd_id = $row["spa_prd_id"];
            $spa_prd_cat = $row["spa_prd_cat"];
            $spa_prd_code = $row["spa_prd_code"];
            $spa_prd_name = $row["spa_prd_name"];
            $spa_prd_vlm = $row["spa_prd_vlm"];
            $spa_prd_qty = $row["spa_prd_qty"];
            $spa_prd_crt_date = $row["spa_prd_crt_date"];
            $spa_prd_crt_usr = $row["spa_prd_crt_usr"];
            $search_output .= '

                                    '.$row_no++.'
                                    '.$spa_prd_cat.'
                                    '.$spa_prd_code.'
                                    '.$spa_prd_name.'
                                    '.$spa_prd_vlm.'
                                    '.$spa_prd_qty.'
                                    '.$spa_prd_crt_date.'
                                    '.$spa_prd_crt_usr.'
                            Edit | Delete

';
        } // close while loop
    }
}

A: You can try explicitly including a LIKE predicate for each search term like this:
$searchsql = $_POST['search'];
$terms = explode(" ", $searchsql);
$likecols = array("spa_prd_cat", "spa_prd_code, "spa_prd_name");
$likesql = "";
foreach ($likecols as $likecol) {
    for ($i = 0; $i < count($terms); ++$i) {
        if ($likecol == "spa_prd_cat" && $i == 0) {
            $likesql = "spa_prd_cat LIKE $terms[0]";
        }
        else {
            $likesql .= " OR $likecol LIKE $terms[$i]";
        }
    }
}

$querystr = "SELECT tb_spa_prd.*, tb_spa_prd_cat.spa_prd_cat FROM tb_spa_prd AS tb_spa_prd INNER JOIN tb_spa_prd_cat ON tb_spa_prd.spa_prd_cat_id = tb_spa_prd_cat.spa_prd_cat_id WHERE ";
$querystr .= $likesql;
$query = mysql_query($querystr) or die ("Could no search!");


text:
Q: Insure MBP against theft/breakage I don't have home contents cover. Anyone know of a good, reliable insurer for a MBP?
I've read up on AppleCare but it doesn't include theft cover (as far as I can tell?)... I'd need this sort of cover as it's my major concern aside dropping it.

A: AppleCare definitely doesn't cover theft. In fact, AppleCare doesn't even cover accidental damage like dropping it, spilling liquid on it, etc.
There are two companies that I hear about from other Mac users where the stories have been positive. Mind you I've never used either company so have no idea how their service is or anything.
For accidental damage plus the normal manufacturer's defect coverage provided by AppleCare I've heard good things about Square Trade. This is the company I've heard the most good about, but they don't provide theft coverage. Square Trade is available only in the United States and Canada.
For accidental damage plus theft (not clear if it covers standard warranty-type damage) I've heard some good about Safeware. I haven't heard as much about them, but a lot of folks have theft coverage through their homeowner's insurance or their renter's insurance, so not at many people need a separate policy. Safeware is available only in the United States.

A: Do you have renters or home owners insurance? your broker may be able to track down a rider you can attach to those policies to provide specific coverage for a laptop. You may have to dance a bit if the device is used entirely for work at the work premises, or if it is work related for your home business.


text:
Q: SQL Shift Timeseries (Get Following Row For Multiple Timestamps) I have a database which looks like this:
timestamp           | entity_id
--------------------+----------
2021-12-01 10:00:00 | A
2021-12-01 09:00:00 | A
2021-12-01 08:00:01 | A
2021-12-01 08:00:00 | B
2021-12-01 07:00:00 | A

timestamp is UNIQUE, but I don't know in advance how far different timestamps are apart. How can I write a statement that would get me the following result?
entity_id | following_entity_id | count
----------+---------------------+------
A         | A                   | 2
A         | B                   | 1
B         | A                   | 1

When using pandas I'd probably use its shift method, but I need to do this using raw SQL in this case.

A: You need LAG() window function to get the value of the previous (chronologically) entity_id (or LEAD() window function to get the following) and then aggregate:
SELECT entity_id, following_entity_id, COUNT(*) count
FROM (
  SELECT *, LAG(entity_id) OVER (ORDER BY timestamp) following_entity_id
  FROM tablename
)
WHERE following_entity_id IS NOT NULL
GROUP BY entity_id, following_entity_id;

See the demo.


text:
Q: How to migrate SQL 2005 to SQL 2008 R2 on new hardware with same server name We have a need to migrate from existing hardware that is running SQL 2005 to new hardware running SQL 2008 R2.
When all is said and done we want the same IP and hostname that was on the "old sql 2005" server to be on the new SQL 2008 R2 server hardware.
This is because we don't want to mess with client connection settings or things that are hardcoded in programming, etc.
We currently have the new 2008 R2 box built with a different name.
Is there a way to move the existing 2005 databases, SSIS jobs, SSAS cubes, SSRS reports, etc. (everything, security, etc.) over to the new hardware and then rename the new hardware to the same IP and hostname as the old.
BOTTOM LINE:  we are wanting to move sql 2005 from old hardware to new hardware running SQL 2008 R2 without messing with the clients.

A: If (as uSlackr points out) you are comfortable moving the content then do this:

*

*Bring up your new server, call it MyNewServer (or whatever) with a new IP.  Install SQL 2008 R2 on it.

*Migrate all of your content over (db's, jobs, logins, SSIS, SSRS, cubes, etc)

*When you're happy that it's good, shutdown the 2005 box

*Rename the new server with that of the old server, readdress to the old IP

*In SQL Server execute the following statements:
sp_dropserver MyNewServer
GO
sp_addserver MyOldServer, local
GO
(See this MSDN article for more information about renaming a host that runs SQL Server)
Note, there WILL be some anti-OCD remnants leftover in the local groups that get created by SQL Server installation.  Some groups get created with the name of the server as part of the group name, so you'll have some local groups with MyNewServer as part of their name.  This won't matter from a technical standpoint.
If you need some steps on how to do your content migration leave me a comment and I'll add some things you can do.

A: I can't speak to moving the content, but it sounds like you know how to do that.  As for not messing with the names, name the new server whatever you'd like and give it a new IP.  When it comes time for cut-over do the following:

*

*Update the DNS record for the old servername to point to the new server's address

*add the IP address of the old server to the NIC of the new server so it is serving both addresses.

Whether the client uses the server name or IP address, this will ensure the get to the new box.


text:
Q: Why operator precedence and associativity for increment and decrement in java not working properly? Operator precedence of ++ and -- is higher than + and has associativity right to left. So I think output of x should be (++i+4 then 5+4) 9 and output of y should be (i+++5 then 5+5) 10. For both it print 11 as output.
class First {
    public static void main(String[] args) {
        int i = 5;
        int x = ++i + --i;
        int y = i++ + i--;
        System.out.println("x="+x);
        System.out.println("y="+y);
    }
}

A: Let's translate this:
int i = 5;
int x = ++i + --i;
int y = i++ + i--;
System.out.println("x=" + x);
System.out.println("y=" + y);

Into (step by step):
int i = 5;
int x = ++i + --i;
//       ^
//   (i = i + 1) + --i
//   (i = 5 + 1) + --i
//   (i = 6)     + --i
//                   ^
//        6      + (i = i - 1)
//        6      + (i = 6 - 1)
//        6      + (i = 5)
//        6      + 5
// x = 11
int y = i++ + i--;
//       ^
//    (i = 5) + i--
//         5  + i--
//     i = i + 1 // post evaluation, after i was evaluated to 5, now i increments its value and it is 6
//         5 + (i = 6)
//         5 + 6
// y = 11
//     i = i - 1 // post evaluation, after i was evaluated to 6, now i decrements its value and it is 5
System.out.println("x=" + x); // x=11
System.out.println("y=" + y); // y=11

A: Associativity dictates how operators with the same precedence are parsed.
For example, the Unary Minus (- ...) and Unary Bitwise NOT (~ ...) operators have the same precedence and have right-to-left associativity. Therefore:
int i = ~-1; // == 0
int j = -~1; // == 2

A: Section 15.7 of the JLS is clear on this:

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
It is recommended that code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect, as its outermost operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.

Whenever assignment operators and other binary operators are mixed in with increment or decrement operators, evaluating the expression is not intuitive, and one should never write such confusing code.
Even if the increment and decrement unary operators are right-to-left associative, the values of an expression are evaluated left-to-right.
int x = ++i + --i;

Here, ++i increments i to 6 and returns 6, then --i decrements i to 5 and returns 5, and the sum of 6 and 5 is 11.
int y = i++ + i--;

Here, i++ returns 5 and increments i to 6, then i-- returns 6 and decrements i to 5, and the sum of 5 and 6 is 11.
With these expressions, the right-to-left associativity does not figure into the order of operations, because associativity only controls which operations are executed first among operators of the same precedence.  You have a + operator of lower precedence between them, so the associativity doesn't matter here.


text:
Q: Cloning DIVs and setting parameters around children I'm working with a function that duplicates a text input field and it's containing div when the return key is hit. The div clones correctly with the input element, but does anyone have suggestions on how to clear the contents of that input element and focus on it?
JavaScript:
if (event.keyCode == 13) {
        var currentInput = $(this).parent("div");
        currentInput.clone().val('').insertAfter(currentInput).focus();
        return false;
}

HTML:
    <div id="item_container">
        <input type="text" class="data-entry">
    </div>

A: try this;
if (event.keyCode == 13) {
    var currentInput = $(this).parent("div");
    currentInput.clone().insertAfter(currentInput).find('.data-entry').val('').focus();
    return false;
}


text:
Q: ERROR: (gcloud.builds.submit) HTTPError 403: The account for bucket "project name" has not enabled billing I am trying do deploy application to google cloud. I've just created account with free tier, registered but when I run
gcloud builds submit --tag gcr.io/project-id/nest-angular-ssr

It says:
ERROR: (gcloud.builds.submit) HTTPError 403: The account for bucket "project name" has not enabled billing.

I've just started with this topic so any hint about enabling billing will be appreciated.

A: Google recently changed it policy to require a valid billing account before you can use Cloud Build. The first 120 minutes per day are free. Read the details here.
The solution is to create a Google billing account and assign the billing account to your project.
Go to the billing account page and create a billing account link.
Assign the billing account

*

*Go to IAM & admin.

*Select Manage resources.

*To the left of each project is an ellipsis menu (three vertical dots). Click and select billing.


text:
Q: I want to update 7 progress bars in C# list view at the same time I put the progress bar in the list view and implemented each update.
I want to run the 7 progress bars inserted in the list view at the same time using a background worker.
Help me how to do it
private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1 = new BackgroundWorker();
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true;

    backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
    backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
    backgroundWorker1.RunWorkerCompleted += new
        RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
    backgroundWorker1.RunWorkerAsync();
}

I want to update the program bar of a total of 7 columns through the background worker.
The purpose is to express file copying and completion status at the same time
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    int N = 7;
    ListView listview1 = null;
    this.Invoke(new MethodInvoker(delegate { listview1 = listview1; }));
    ListViewItem lvi;
    ProgressBar pb;

    for (int i = 0; i < 100; i++)
    {
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            return;
        }

        UpdateItemValue(i.ToString(), i);
        backgroundWorker1.ReportProgress(i * 100 / listView1.Items.Count, i);
    }
    e.Result = N;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    listView1.Items[0].SubItems[3].Text = "Done";
}

private void UpdateItemValue(string key, int value)
{
    //There is also a cross-thread problem in the UpdateItemValue method[enter image description
    //here][1]
    ListViewItem lvi;
    ProgressBar pb;

    lvi = listView1.Items.Cast<ListViewItem>().FirstOrDefault(q => q.SubItems[0].Text == key);
    if (lvi != null)
        lvi.SubItems[2].Text = value.ToString();

    pb = listView1.Controls.OfType<ProgressBar>().FirstOrDefault(q => q.Name == key);
    if (pb != null)
        pb.Value = value;
}

This method adds a column to the list view and adds a progress bar.
private void Additem_Click(object sender, EventArgs e)
{
    ListViewItem lvi = new ListViewItem();

    if (listView1.Items.Count > 0)
    {
        listView1.BeginUpdate();

        lvi.Text = listView1.Items.Count.ToString();
        lvi.SubItems.Add("111");

        lvi.SubItems.Add("222");
        lvi.SubItems.Add("333");
        listView1.Items.Add(lvi);

        ProgressBar pb = new ProgressBar();
        Rectangle r = lvi.SubItems[2].Bounds;
        pb.SetBounds(r.X, r.Y, r.Width, r.Height);
        pb.Minimum = 0;
        pb.Maximum = 100;
        pb.Value = 0;
        pb.Name = listView1.Items.Count.ToString();                   // use the key as the name
        listView1.Controls.Add(pb);
        listView1.EndUpdate();
    }
}

What I want to do with this code
When you insert 7 progress bars in the list view and click the update button
At the same time, you are moving the 7 progress bars in Lisview until they reach 100%.