text:
Q: bootstraping angular value provider My app.js, service.js, controller.js are declared as below. My problem is the controller only pickup the initial values {userId: -1, networkName: 'xyz'} set in the service.js, even though the values are changed to { userId: 129, networkName: 'mydomainaccoutname' } in myApp.run() block in the app.js. I have correctly injected the value provider to myApp.run() as well as the controller. How do I get the controller to pick up the updated values?  Thanks.
app.js

(function () {
    'use strict';

    //debugger;
    var myApp = angular.module('myApp', [
        // Angular modules
        'ngAnimate',        // animations
        //'ngRoute',          // routing
        'ngSanitize',       // sanitizes html bindings (ex: sidebar.js)
        'ui.router',        // state routing
        'ui.grid',
        'ui.grid.pagination',
        'ngResource',       // RESTful resource

        // Custom modules
        'common',           // common functions, logger, spinner
        'common.bootstrap', // bootstrap dialog wrapper functions

        // 3rd Party Modules
        'ui.bootstrap'      // ui-bootstrap (ex: carousel, pagination, dialog)
    ]);

    myApp.run(['$templateCache', '$rootScope', '$state', '$stateParams', 'currentUserAccount', 'userFactory',
    function ($templateCache, $rootScope, $state, $stateParams, currentUserAccount, userFactory) {
        //currentUserAccount is a value provider service
        currentUserAccount = { userId: 129, networkName: 'mydomainaccoutname' };
    }]);
})();

service.js

'use strict';

angular.module('myApp')

  .value('version', '5.0')

  .value('currentUserAccount', {
      userId: -1,
      networkName: 'xyz'
  });

controller.js

(function () {
    'use strict';

    //debugger;
    var controllerId = 'shellCtrl';
    angular.module('cmtApp').controller(controllerId,
        ['$rootScope', 'common', 'config', 'currentUserAccount', shell]);

    function shell($rootScope, common, config, currentUserAccount) {
        var vm = this;
        var logSuccess = common.logger.getLogFn(controllerId, 'success');
        var events = config.events;
        vm.busyMessage = 'Please wait ...';
        vm.isBusy = true;
        vm.isAdmin = false;
        vm.currentUser = currentUserAccount;
        vm.spinnerOptions = {
            radius: 40,
            lines: 7,
            length: 0,
            width: 30,
            speed: 1.7,
            corners: 1.0,
            trail: 100,
            color: '#F58A00'
        };

        activate();

        function activate() {
            logSuccess('CMT loaded!', null, true);
            common.activateController([], controllerId);
        }
      };
})();

A: Why not use a actual service instead? You can have your service like follows.
angular.module('app')
  .service('UserService', [function() {
     var currentUser = {
        userId: -1,
        networkName: 'xyz'
     };

     var getCurrentUser = function() {
        return currentUser;
     };

     var setCurrentUser = function(user) {
        currentUser = user;
     };

     // public functions
     return {
        getCurrentUser: getCurrentUser,
        setCurrentUser: setCurrentUser
     };

  }]);

Then in your controller, you can do something like this:
(function () {
    'use strict';

    //debugger;
    var controllerId = 'shellCtrl';
    angular.module('cmtApp').controller(controllerId,
        ['$rootScope', 'common', 'config', 'UserService', shell]);

    function shell($rootScope, common, config, UserService) {
        var vm = this;
        ....
        vm.currentUser = UserService.getCurrentUser();
       ...
      };
})();

Then in your app runner:
myApp.run(['$templateCache', '$rootScope', '$state', '$stateParams', 'UserService', 'userFactory',
function ($templateCache, $rootScope, $state, $stateParams, currentUserAccount, userFactory) {
    //currentUserAccount is a value provider service
    UserService.setCurrentUser({ userId: 129, networkName: 'mydomainaccoutname' });
}]);


text:
Q: Save a pandas dataframe with a column with 2d arrays as a parquet file in python I'm trying to save a pandas dataframe to a parquet file using pd.to_parquet(df).df is a dataframe with multiple columns and one of the columns is filled with 2d arrays in each row. As I do this, I receive an error from pyarrow complaining that only 1-d arrays are supported. I googled and it seems there is no solution. I just wanted to confirm that in fact there is no solution to this and I have to somehow represent my 2-d array with a 1-d array.

A: It's correct that pyarrow / parquet has this limitation of not storing 2D arrays.
But, parquet (and arrow) support nested lists, and you could represent a 2D array as a list of lists (or in python an array of arrays or list of arrays is also fine). So one option could be to convert your 2D arrays to such format.
Example that such nested lists/arrays work:
In [2]: df = pd.DataFrame(
   ...:      {'a': [[np.array([1, 2, 3]), np.array([4, 5, 6])],
   ...:             [np.array([3, 4, 5]), np.array([6, 7, 8])]]})

In [3]: df.to_parquet('test_nested_list.parquet')

In [4]: res = pd.read_parquet('test_nested_list.parquet')

In [5]: res['a']
Out[5]:
0    [[1, 2, 3], [4, 5]]
1    [[1, 2], [3, 4, 5]]
Name: a, dtype: object

In [6]: res['a'].values
Out[6]:
array([array([array([1, 2, 3]), array([4, 5, 6])], dtype=object),
       array([array([3, 4, 5]), array([6, 7, 8])], dtype=object)],
      dtype=object)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does the Arrow function work in ECMAScript6 I am working on mathematical program and ready to implement new feature of ECMAScript6 Arrow.
Which is very similar to Lambda expression in C#.
let square = y => y * y;
console.log(square(4));

I achieved my goal after using Arrow function but still confuse how the Arrow function is works.
Is it work like Lambda expression.Can anyone guide me on that.
Thanks

A: It's essentially doing this:
var square = function(y) {
  return y * y;
}.bind(this);

where this is bound to the outer scope.


text:
Q: Retrieving part of a string which has many scenarios using T-SQL I need a T-SQL query to get an output (specified below under expected) covering all the cases. I tried doing that but was unsuccessful:
select
    code,
    substring(code, patindex('%[0-9]%', code),
                    case
                       when patindex('%[. ,/-]%', substring(code, patindex('%[0-9]%', code), len(code))) <> 0
                          then patindex('%[. ,/-]%', substring(code, patindex('%[0-9]%', code), len(code))) - 1
                          else patindex('%[. ,/-]%', substring(code, patindex('%[0-9]%', code), len(code)))
                     end)
from
    table

This is expected output
input                           output
------------------------------------------------------
AB 123456.123                   123456
AB 123456/123                   123456
AB 123456-123                   123456
AB B0-23456.123                 0-23456
AB 1234 5678 9545 3214.123      1234 5678 9545 3214
AB 123456 123                   123456
AB.123456 123                   123456
AB..123456 123                  123456
AB..1C23456 123                 1C23456

Rules

*

*Starts with the first occurrence of the number

*Slice the string after special characters (, /.-) valid case
2.1 if string has - after 3 numbers valid, eg: AB B0-23456.123 ----  0-23456
2.2 if string has more than 3 numbers after a space valid, eg:AB 1234 5678 9545 3214.123 ---- 1234 5678 9545 3214

A: I believe this will meet all of your criteria, but do check it against edge cases not presented here to insure it does what you expect.
DECLARE @table as TABLE (code VARCHAR(40))

INSERT INTO @table
(code)
Values
('AB 123456.123'),
('AB 123456/123'),
('AB 123456-123'),
('AB B0-23456.123'),
('AB 1234 5678 954 3214.123'),
('AB 1234 5678 9545/3214.123'),
('AB 123456 123'),
('AB.123456 123'),
('AB..123456 123'),
('AB..1C23456 123')

SELECT
code as [input],
SUBSTRING(code,PATINDEX('%[0-9]%', code),
CASE WHEN PATINDEX('%[ -][0-9][0-9][0-9][0-9]%',SUBSTRING(code,PATINDEX('%[0-9]%', code),LEN(code))) <> 0
THEN
    CASE WHEN PATINDEX('%[.,/]%',SUBSTRING(code,PATINDEX('%[0-9]%', code),LEN(code))) < ISNULL(NULLIF(PATINDEX('%[ -][0-9][0-9][0-9][^0-9]%',SUBSTRING(code,PATINDEX('%[0-9]%', code),LEN(code))),0),LEN(code))
    THEN PATINDEX('%[.,/]%',SUBSTRING(code,PATINDEX('%[0-9]%', code),LEN(code)))-1
    ELSE ISNULL(NULLIF(PATINDEX('%[ -][0-9][0-9][0-9][^0-9]%',SUBSTRING(code,PATINDEX('%[0-9]%', code),LEN(code))),0),LEN(code))
    END
ELSE PATINDEX('%[. ,/-]%', SUBSTRING(code,PATINDEX('%[0-9]%', code),LEN(code)))-1
END
) as [output]
FROM @table

EDIT: Modification to inner case statement to correct for edge case mentioned in comments, just to prove that this could be done without using a CTE. :)

A: To be honest: This is a nightmare. T-SQL is absolutely the wrong tool for this!
Just because I placed an insufficient (due to your insufficient question) answer, I'm urged to solve this somehow. That's a matter of sportsmanship...
DECLARE @mockup TABLE(ID INT IDENTITY, YourString VARCHAR(1000));
INSERT INTO @mockup VALUES
 ('AB 123456.123')
,('AB 123456/123')
,('AB 123456-123')
,('AB B0-23456.123')
,('AB 1234 5678 9545 3214.123')
,('AB 123456 123')
,('AB.123456 123')
,('AB..123456 123')
,('AB..1C23456 123')
,('AB 1234 5678 954 3214-12345.123');

--The nightmare
WITH CutForRules AS
(
    SELECT t.ID
          ,t.YourString
          ,ROW_NUMBER() OVER(PARTITION BY t.ID ORDER BY (SELECT (NULL))) FragmentIndex
          ,c AsXml
          ,d.value('text()[1]','varchar(100)') Fragment
          ,ISNUMERIC(d.value('text()[1]','varchar(100)')) FragmentIsNum
          ,LEN(d.value('text()[1]','varchar(100)')) FragmentLength
          ,d.value('@dlmt','varchar(10)') Delimiter
    FROM @mockup t
    CROSS APPLY(SELECT REVERSE(SUBSTRING(t.YourString,PATINDEX('%[0-9]%',t.YourString),1000))) A(a)
    CROSS APPLY(SELECT REVERSE(SUBSTRING(a,PATINDEX('%[ /.-]%',a)+1,1000))) B(b)
    CROSS APPLY(SELECT CAST('<x>' + REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(b,'/','|'),' ','</x><x dlmt=" ">'),'.','</x><x dlmt=".">'),'-','</x><x dlmt="-">'),'|','</x><x dlmt="/">') + '</x>' AS XML)) C(c)
    CROSS APPLY c.nodes('/x') D(d)
)
SELECT t1.ID
      ,t1.YourString
      ,(
        SELECT CONCAT(t2.Delimiter,t2.Fragment)
        FROM CutForRules t2
        WHERE t1.ID=t2.ID
          AND (t2.FragmentIndex<(SELECT MIN(t3.FragmentIndex)
                                 FROM CutForRules t3
                                 WHERE t3.ID=t1.ID
                                   AND t3.FragmentIndex>t2.FragmentIndex
                                   AND t3.Delimiter=' '
                                   AND t3.FragmentLength<4
                                   AND t3.FragmentIsNum=1)
               OR NOT EXISTS(SELECT 1 FROM CutForRules t4 WHERE t4.ID=t1.ID AND t4.Delimiter=' ' AND t4.FragmentLength<4)
              )
        ORDER BY t2.FragmentIndex
        FOR XML PATH('')
       )
FROM CutForRules t1
GROUP BY t1.ID,t1.YourString
ORDER BY t1.ID;

You might place a SELECT * FROM CutForRules to see the intermediate resultset I use for this.
But I'm pretty sure, that you'll come up with Oh yeah, that's working, but there is one more case...
Just to get this clear: I'm out at this point ;-)
UPDATE: Some explanation
The cte CutForRules will return this set for my test-data:
+----+---------------------------------+---------+---+---+------+
|    | YourString                      |Fragment | N | L | Delm |
+----+---------------------------------+---------+---+---+------+
| 1  | AB 123456.123                   | 123456  | 1 | 6 | NULL |
+----+---------------------------------+---------+---+---+------+
| 2  | AB 123456/123                   | 123456  | 1 | 6 | NULL |
+----+---------------------------------+---------+---+---+------+
| 3  | AB 123456-123                   | 123456  | 1 | 6 | NULL |
+----+---------------------------------+---------+---+---+------+
| 4  | AB B0-23456.123                 | 0       | 1 | 1 | NULL |
+----+---------------------------------+---------+---+---+------+
| 4  | AB B0-23456.123                 | 23456   | 1 | 5 | -    |
+----+---------------------------------+---------+---+---+------+
| 5  | AB 1234 5678 9545 3214.123      | 1234    | 1 | 4 | NULL |
+----+---------------------------------+---------+---+---+------+
| 5  | AB 1234 5678 9545 3214.123      | 5678    | 1 | 4 |      |
+----+---------------------------------+---------+---+---+------+
| 5  | AB 1234 5678 9545 3214.123      | 9545    | 1 | 4 |      |
+----+---------------------------------+---------+---+---+------+
| 5  | AB 1234 5678 9545 3214.123      | 3214    | 1 | 4 |      |
+----+---------------------------------+---------+---+---+------+
| 6  | AB 123456 123                   | 123456  | 1 | 6 | NULL |
+----+---------------------------------+---------+---+---+------+
| 7  | AB.123456 123                   | 123456  | 1 | 6 | NULL |
+----+---------------------------------+---------+---+---+------+
| 8  | AB..123456 123                  | 123456  | 1 | 6 | NULL |
+----+---------------------------------+---------+---+---+------+
| 9  | AB..1C23456 123                 | 1C23456 | 0 | 7 | NULL |
+----+---------------------------------+---------+---+---+------+
| 10 | AB 1234 5678 954 3214-12345.123 | 1234    | 1 | 4 | NULL |
+----+---------------------------------+---------+---+---+------+
| 10 | AB 1234 5678 954 3214-12345.123 | 5678    | 1 | 4 |      |
+----+---------------------------------+---------+---+---+------+
| 10 | AB 1234 5678 954 3214-12345.123 | 954     | 1 | 3 |      |
+----+---------------------------------+---------+---+---+------+
| 10 | AB 1234 5678 954 3214-12345.123 | 3214    | 1 | 4 |      |
+----+---------------------------------+---------+---+---+------+
| 10 | AB 1234 5678 954 3214-12345.123 | 12345   | 1 | 5 | -    |
+----+---------------------------------+---------+---+---+------+

The provided SELECT will group this by ID,YourString. That means: 1 row per ID.
The returned columns are the grouping columns plus a big computed one.
This is a correlated sub-query. It will fetch all rows for the current ID and process them. And its result is returned FOR XML PATH, which is a trick to concatenate all the results.
The tricky part is in the WHERE: If there is at least one numeric fragment after a blank with a length <4, the string will not include this and all following fragments.
How do I get the element before the current element?
This is again a correlated sub-query fetching the element within the ID-group with a FragmentIndex bigger than the current one.


text:
Q: C# LINQ Zipping 2 list of lists based on uniqueness of objects I am trying to zip 2 lists of lists of objects - only where the resulting zipped list would contain lists of distinct objects (list 2's lists sometimes have duplicate objects when compared to list 1). The count of objects in the resultant list must be maintained, meaning we can't have lists of differing sizes. The number of lists in list 1 is greater the number in list 2. Which would mean repeatedly going through list 2 when zipping.
The above is represented using loops below. Is this possible using only linq?
//this list of list contains the larger number of elements to which the 2nd list of list needs to be joined
List<List<object>> FullList = new List<List<object>>(); //is not empty - instantiated with some list

//2nd list of list - contains duplicates of the 1st list in terms of the objects in the underlying list
List<List<object>> comboBaseList = new List<List<object>>(); //is not empty - instantiated with some list
List<List<object>> comboList = comboBaseList;

//need to zip lists where there are no duplicate objects in the 2nd list's list, the count of the 1st list of list remains the same as FullList
List<List<object>> finalList = new List<List<object>>(); //empty - meant to hold final combined list

int i = 0;

foreach iList in FullList
{
    if (i < comboList.count)
    {
        while (iList.Select(x => x.Id).Contains(comboList[i].Select(y => y.Id)))
        {
            i += 1;
        }
        finalList.Add(iList.Zip(comboList[i], (x, y) => x.Union(y))); //**CAN WE BYPASS THE LOOPS AND JUST USE LINQ?
        comboList.RemoveAt(i);
        i = 0;
    }
    else
    {
        comboList = comboBaseList;
        i = 0;
    }
}

To simplify the data I'll use lists of lists of integers - which could be the Id's of the objects in my case
FullList =
(
{1,2,3},
{2,5,6},
{7,8,9}
)

comboList =
(
{2,5},
{8,9}
)

I want to zip the above lists to yield the resultant as below - Note that there are 3 results as per FullList and the undelying lists have distinct integers
finalList =
{
 {1,2,3,8,9},
 {2,5,6,8,9},
 {7,8,9,2,5}
}

A: Okay, it sounds like you might want something like:
var result = fullList
    .Select(original =>
       // We want the original sublist...
       original
           // concatenated with...
           .Concat(
           // ... any comboList element
           comboList
               // which is completely distinct from "original"
               .Where(cl => !original.Intersect(cl).Any())
               // ... flattening all such comboLists
               .SelectMany(cl => cl))
           .ToList())
    .ToList();

Here's a complete example:
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var fullList = new[]
        {
            new[] { 1, 2, 3 },
            new[] { 2, 5, 6 },
            new[] { 7, 8, 9 }
        };

        var comboList = new[]
        {
            new[] { 2, 5 },
            new[] { 8, 9 }
        };

        var result = MergeCombinations(fullList, comboList);
        foreach (var item in result)
        {
            Console.WriteLine(string.Join(", ", item));
        }
    }

    static List<List<T>> MergeCombinations<T>(
        IEnumerable<IEnumerable<T>> fullList,
        IEnumerable<IEnumerable<T>> comboList)
    {
        var result = fullList
            .Select(original =>
                // We want the original sublist...
                original
                    // concatenated with...
                    .Concat(
                    // ... any comboList element
                       comboList
                           // which is completely distinct from "original"
                           .Where(cl => !original.Intersect(cl).Any())
                           // ... flattening all such comboLists
                          .SelectMany(cl => cl))
                   .ToList())
             .ToList();
        return result;
    }
}

A: var fullList = new List<List<int>>()
        {
            new List<int>() {1,2,3},
            new List<int>() {2,5,6},
            new List<int>() {7,8,9}
        };

 var comboList = new List<List<int>>()
        {
            new List<int>() {2,5},
            new List<int>() {8,9},
        };

fullList.ForEach(i =>
        {
            comboList.ForEach(j =>
            {
                if (i.All(x => !j.Contains(x)))
                {
                    i.AddRange(j);
                    return;
                };
            });
        });


text:
Q: MIME type error for local CSS or JS prevents loading custom styles when working with NodeJs I am racking my brain the whole week on this error now!
My plan was to create a simple 'send email from nodejs' application. The problem that I ran into was, a mime-type error for my style.css. The error says it's is in a text/html format.
I started as usual with 'npm init -y' and 'npm install express nodemailer nodemailer-mailgun-transport -S'.
I also created a 'server.js', 'index.html' and 'style.css' (See code below).
And that's it. The application works as expected and linking bootstrap cdn also works. It is only my custom css that gives me a hard time. So to simplify it I even took a copy/paste html template from w3schools
index.html
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="style.css" />

This is a heading

This is a paragraph.

style.css
body {
  background-color: powderblue;
}
h1 {
  color: blue;
}
p {
  color: red;
}

server.js
const express = require('express');
const app = express();
const PORT = 8080;
const path = require('path');

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'views', 'index.html'));
})

app.listen(PORT);

package.json
{
  "name": "SendMail",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "nodemailer": "^6.4.15",
    "nodemailer-mailgun-transport": "^2.0.1"
  },
  "style": "style.css"
}

The error in Chrome:

What I've tried:

*

*Isolating the html/css part to make sure the code is alright. Yes, it is!

*experimenting around with the style link. Including this workaround: https://stackoverflow.com/a/45119502/12272930

*Change the mime-type via javascript like: Style and javascript files not applied to page that is serving HTML in Node.js

*Attaching a style section in package.json as shown above

Edit: Inline styling and JS works as expected. I am guessing that it has something to do with express.
Is there anything else that I could try?
Let me know if you need additional info. Thanks in advance!

A: When serving static files (like images, css, etc.) it is usually best practice to place those files in a dedicated directory called public or static, or whatever you like. Then you need explicitly tell your express app to serve files from there like so:
app.use(express.static(__dirname + '/public'));

So your server.js becomes:
const express = require('express');
const app = express();
const PORT = 8080;
const path = require('path');

app.use(express.static(__dirname + '/public'));

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'views', 'index.html'));
})

app.listen(PORT);

And then you can call your CSS file like this in your index.html:
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="public/style.css" />

This is a heading

This is a paragraph.

A: Good evening) Just make your folder with html/css is public.
const express = require('express');
const app = express();
const PORT = 3000;
const path = require('path');

app.use(express.static(__dirname + '/public'));

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'views', 'index.html'));
})

app.listen(PORT);


text:
Q: SQL Server query for related products I am trying to get related products but the issue which I'm facing is that there is product photos table which has one-to-many relationship with products table, so when I get products by matching category Id it also returns multiple product photos with that product which i do not want. I want only one product photo from product photos table of specific product. Is there any way to use distinct in joins or any other way? what I have done so far....
 SELECT [Product].[ID],
  ,[Thumbnail]
  ,[ProductName]
  ,[Model]
  ,[SKU]
  ,[Price]
  ,[IsExclusive]
  ,[DiscountPercentage]
  ,[DiscountFixed]
  ,[NetPrice]
  ,[Url]
  FROM [dbo].[Product]
  INNER JOIN [ProductPhotos] ON [ProductPhotos].[ProductID]=[Product].[ID]
  INNER JOIN [ProductCategories] ON [ProductCategories].[ProductID]=
  [Product].[ID]
  WHERE [ProductCategories].[CategoryID]=4

And the result I am getting is...

Product Photos table has

Is there any way to use distinct or group by on product Id column in product photos table to return only one row from photos table.

A: Instead of using inner join, use cross apply:
SELECT . . .
FROM dbo.Product p CROSS APPLY
     (SELECT TOP (1) pp.*
      FROM ProductPhotos pp
      WHERE pp.ProductID = p.id
      ORDER BY NEW_ID()
     ) pp INNER JOIN
     ProductCategories pc
     ON pc.ProductID = p.id
WHERE pc.CategoryID = 4;

Notes:

*

*The ORDER BY NEWID() chooses a random photo.  You can order by specific columns to get the earliest, latest, biggest, or whatever.

*Note that I added table aliases.  These make the query easier to write and to read.

*You should qualify all column names in your query, so it is clear which tables they come from.

*I removed the superfluous square braces.  They just make the query harder to write and to read.

A: You can use ROW_NUMBER() to return one row for ProductID, like this:
JOIN (SELECT *,
             ROW_NUMBER() OVER (PARTITION BY ProductID ORDER BY PhotoID) rn
      FROM [ProductPhotos]) [ProductPhotos]
ON [ProductPhotos].[ProductID]=[Product].[ID] AND [ProductPhotos].rn = 1

Instead of this:
JOIN [ProductPhotos] ON [ProductPhotos].[ProductID]=[Product].[ID]

A: you can use sub query in join with distinct instead of joining table directly.
you can create alias and use that column as distinct in select statement, but it will create performance issues when having loads of data inside.
if you have 3 different photos for same product Id (like 2). you can use sub-query with top 1 order by PK desc to get latest picture.


text:
Q: Can't get the Hash password to save with bcrypt I am trying to persist a hashed password using sequelize, bcrypt and express. The hash does generate but it looks like the db entry happend before the hash value is generated. I am new to NodeJS, so my knowledge is not as good on this yet.
user.js
var bcrypt = require('bcrypt');

module.exports = function(sequelize, DataType){

  var User = sequelize.define('User', {
    name: DataType.STRING,
    localPassword: DataType.STRING,
    lastName: DataType.STRING,
    localEmail: DataType.STRING,
    cellNumber: DataType.INTEGER
  },
      {
        instanceMethods: {
          validPassword: function(password){
              return bcrypt.compareSync(password, this.password);
          }
        },
          classMethods: {
              generateHash: function (password) {
                  return bcrypt.hash(password, 8, function(err, hash){
                      if(err){
                          console.log('error'+err)
                      }else{
                          return hash;
                      }
                  });
              }
          }
      }

  );

    return User;
};

routes/index.js
router.post('/register', function(req, res){
  var name = req.body.name;
  var lastName = req.body.lastName;
  var email = req.body.email;
  var cellNumber = req.body.cellNumber;
  var password = model.User.generateHash(req.body.password);
  model.User.build({name: name, lastName: lastName, localEmail: email, cellNumber: cellNumber, localPassword: password}).save();

});

All the values persist in the db except the hashed password. Any help would be greatly appreciated.

A: The problem here is that you are using an asynchronous bcrypt.hash and model.User.build executes before bcrypt hashed the password. You have several options here, you can use a synchronous bcrypt.hashSync; or perform model.User.build call as a promise
model.User.generateHash(req.body.password).then(function(data){
   ...
})

You can use bcrypt-then for that.
npm install bcrypt-then


text:
Q: Writing sanitizer function in Typescript to check for null, undefined and empty strings and getting error inside function I'm writing a generic function in Typescript to take a string value and check to see if it is null, undefined or an empty string and return null or if it's an actual value return it trimmed.
The issue I'm running into ironically, is that inside the function on the second line at return stringValue.trim(); I'm getting the error Object is possibly null or undefined and I'm not sure what kind of check I can do to fix that.
This is my function currently:
  const sanitize = (stringValue: string | undefined | null) => {
    let emptyString = '';
    let nullValue = null;
    let undefinedValue = undefined;

    if(typeof stringValue === emptyString || typeof stringValue === nullValue || typeof stringValue === undefinedValue){
      return null
    } else {
      return stringValue.trim();
    }
  }

A: There's no need to use typeof here, simply compare the variables directly so that TypeScript knows you have already excluded those possible types, which guarantees that stringValue will not be null or undefined:
if(stringValue === '' || stringValue === null || stringValue === undefined)
Or, as @DBS mentioned, make use of falsy values and simplify your statement to
if (!stringValue)
If you wanted to also have strings which contain only whitespace return as null, you could change your return statement to return stringValue.trim() || null to check if the trimmed value becomes ''
As @DBS also mentioned, typeof returns the type as a string. Also typeof on a null object will return 'object', not 'null', making this even less applicable for this scenario. In general I've never really found myself needing to use typeof, except for some dynamic input validation

A: instead of the using the extra variables and to increase code readability, your working sanitize function can be written as
 const sanitize = (stringValue: string | undefined | null) => {
    if(typeof stringValue === "string"){
        return stringValue.trim();
    } else {
        return null
    }
  }

typeof stringValue  will return string if the type is string, and the if block will return the trimmed string. If the type is other than a string, we simply return null.
As @DBS mentioned, the above will not return null for empty strings. If you want to return null for empty strings as well, use the following version:
 const sanitize = (stringValue: string | undefined | null) => {
    if(typeof stringValue === "string" && stringValue.trim().length>0){
        return stringValue.trim();
    } else {
        return null
    }
  }


text:
Q: Add description to table cell I have a table that has three columns. In one of these columns (in the photo it is in the middle), I would like to add a small description below (for example, the operation system of the device).
I tried several options with Grid, but nothing worked for me. Perhaps you can help me?
For a better idea, I marked the desired result in the photo in green

return (
    <TableRow sx={TableRowStyle}>
        <TableCell size='medium' align='left' sx={TableCellIdStyle}>
            {
                (props.id === '-')
                    ? ""
                    : <DeleteHidePacketButtonGroup packetReference={null} isHidden={null} />
            }

        </TableCell>
            <TableCell size='medium' align='left' sx={TableCellIdStyle}>{props.id}</TableCell> /*This TableCell is responsible for the central column */
            <TableCell size='medium' align='right' sx={TableCellIdStyle}>
                {
                    nextPage !== undefined ? List of {nextPage} : null
                }
        </TableCell>
    </TableRow>
);

A: I don't know what UI framework you are using, but generally, a TableCell should not be inside another TableCell directly. For your issue, you can create a div inside your center table cell. Set it to display: flex; flex-direction: column. And put your content inside that div.

A: You can try title attribute in HTML element,
Basically, the title attribute gives you the default description box from the browser's end

    {...}

in your case,you can even try this by targeting element
cell.setAttribute('title', "This is discription");

And yes,
you can not add another <Tablecell/> inside <Tablecell/>

A: Here is a quick snippet that hope it helps (based on some sample code from MUI). Column 2 has what you probably need:
const addTextInCell = () => (

Device 1

Android

);

const rows = [
  { id: 1, col1: "Hello", col2: "World", col3: "Column 1" },
  { id: 2, col1: "MUI X", col2: "is awesome", col3: "Column 2" },
  { id: 3, col1: "Material UI", col2: "is amazing", col3: "Column 3" }
];

const columns = [
  { field: "id", hide: true },
  { field: "col1", headerName: "Column 1", width: 150 },
  {
    field: "col2",
    headerName: "Column 2",
    width: 150,
    renderCell: () => addTextInCell()
  },
  { field: "col3", headerName: "Column 3", width: 150 }
];

const TestTable = () => (

    <DataGrid rows={rows} columns={columns} />

);

export default TestTable;

I am using the renderCell method where you can specify what your cell will render. In the 'addTextInCell' function you can have you HTML which in this case is just a simple
 containing two more
 which will give you the desired result (you can replace it with anything you want).


text:
Q: i want to make my shoppingcart local so every time i refresh the page my stuff still needs to be in there but i just dont find the right way to do it This is my code but I don't know where to start to add localstorage.
I am really trying every website for help because I just can't find it.
var _currentArr;
var _ItemsInCart = [];
var _totalPayment = 0;
function getArticle(item, addDetails) {
  var article = document.createElement("article");
  var h3 = document.createElement("H3");
  h3.appendChild(document.createTextNode(item.title));

  article.appendChild(h3);

  var figure = document.createElement("FIGURE");
  var img = document.createElement('img');
  img.src =  'images/'+item.img;
  var figcaption = document.createElement('figcaption');
  figcaption.textContent = 'Meal by: '+item.cook;
  figure.appendChild(img);
  figure.appendChild(figcaption);

  article.appendChild(figure);

  // if need details
  if (addDetails) {
    var dl = document.createElement("dl");
    var dt1 = document.createElement("dt");
    var dd1 = document.createElement("dd");
    dt1.textContent = 'calories:';
    dd1.textContent = item.calories;
    dl.appendChild(dt1);
    dl.appendChild(dd1);
    var dt2 = document.createElement("dt");
    var dd2 = document.createElement("dd");
    dt2.textContent = 'servings:';
    dd2.textContent = item.servings;
    dl.appendChild(dt2);
    dl.appendChild(dd2);
    var dt3 = document.createElement("dt");
    var dd3 = document.createElement("dd");
    dt3.textContent = 'days to book in advance:';
    dd3.textContent = item.book;
    dl.appendChild(dt3);
    dl.appendChild(dd3);
    var dt4 = document.createElement("dt");
    var dd4 = document.createElement("dd");
    dt4.textContent = 'type:';
    dd4.textContent = item.type;
    dl.appendChild(dt4);
    dl.appendChild(dd4);
    article.appendChild(dl);
  }

  // info div
  var div = document.createElement("DIV");
  div.setAttribute("class", "info");
  var p = document.createElement("P");
  p.textContent = '€'+item.price+'/pp';
  var a = document.createElement("A");
  a.setAttribute("href", '#');
  a.textContent = 'order';
  a.setAttribute("id", item.id);
  if (addDetails) {
    a.setAttribute("data-item", JSON.stringify(item));
    a.className = "order placeOrderInCart";
  } else {
    a.className = "order orderBtn";
  }

  // in div
  div.appendChild(p);
  div.appendChild(a);
  article.appendChild(div);

  return article;
}

function makeTemplateFromArray(arr) {
  _currentArr = [];
  _currentArr = arr;
  var container = document.getElementById('dynamicContent');
  container.innerHTML = '';
  if (arr && arr.length) {
    arr.forEach(function (item, index) {
      // append article
      container.appendChild(getArticle(item, false));
    });
  }
}

function makeTemplateFromItem(item) {
  if (item) {
    var container = document.getElementById('popupContentWrapper');
    container.innerHTML = '';
    container.appendChild(getArticle(item, true));
  }
}

function showModal(id) {
  // find item by id
  if (_MEALS && id) {
    var found = _MEALS.find(function(item) {
      if (item.id === parseInt(id)) {
        return true;
      }
    });
    if (found) {
      makeTemplateFromItem(found);
    }
  }
  // open modal
  document.getElementById('popup').style.display = "block";
}

// sorting
function sortItems() {
  var a = _MEALS.slice(0, _MEALS.length);
  var k = event.target.value;
  makeTemplateFromArray(doSortData(k, a));
}

function doSortData(key, arr) {
  var compare = function ( a, b) {
    if ( a[key]  b[key] ){
      return 1;
    }
    return 0;
  };
  return arr.sort( compare );
}

// change direction
function changeDirection() {
  var val = event.target.value;
  var a = _currentArr.slice(0, _currentArr.length);
  if (val === 'desc') {
    makeTemplateFromArray(a.reverse());
  } else {
    makeTemplateFromArray(_MEALS);
  }
}

// search on input
function searchInArray() {
  var val = event.target.value;
  if (val && val.length > 1) {
    val = val.toLowerCase();
    var arr = _MEALS.filter(function (item) {
      if (item.title.toLowerCase().includes(val)) {
        return true;
      }
    });
    makeTemplateFromArray(arr);
  } else {
    makeTemplateFromArray(_MEALS);
  }
}

// prepare options
function prepareOptions(obj) {
  var select = document.getElementById('sortby');
  Object.keys(obj).forEach(function (key) {
    var opt = document.createElement('option');
    opt.value = key;
    opt.innerHTML = key;
    select.appendChild(opt);
  });
}

// add item in cart
function addItemInCart(item) {
  _ItemsInCart.push(item);
  var elem = document.getElementById('cartCounter');
  elem.innerHTML = _ItemsInCart.length;
}

// show cart
function showCart() {
  // prepare template
  var container = document.getElementById('cartItems');
  var table = document.createElement("table");
  var thead = document.createElement("thead");
  var tbody = document.createElement("tbody");
  var tfoot = document.createElement("tfoot");
  container.innerHTML = '';
  var thBody = '
Meal	Price
';
  thead.innerHTML = thBody;
  // tbody
  _totalPayment = 0;
  _ItemsInCart.forEach(function(item) {
    _totalPayment += parseInt(item.price);
    var tBodyTemp = '
'+item.title+'	€ '+item.price+'
';
    tbody.innerHTML += tBodyTemp;
  });

  // tfoot
  var tfootBody = '
Total	€ '+_totalPayment+'
';
  tfoot.innerHTML = tfootBody;

  table.appendChild(thead);
  table.appendChild(tbody);
  table.appendChild(tfoot);
  container.appendChild(table);
  // open modal
  document.getElementById('cart').style.display = "block";
}

// proceed to checkout
function proceedToCheckout() {
  document.getElementById('cartoverview').classList.add('hidden');
  document.getElementById('personalinformation').classList.remove('hidden');
}

// validate form submit
function validatepersonalInfoForm() {
  document.getElementById('personalinformation').classList.add('hidden');
  document.getElementById('confirmation').classList.remove('hidden');

  // set values
  var val = document.querySelector('input[name="paymentmethod"]:checked').value;
  document.getElementById('price').innerHTML = '€ '+_totalPayment;
  document.getElementById('paymentmethod').innerHTML = 'in '+val;
}

function setRandomItem() {
  var max = _MEALS.length;
  var min = 0;
  var number = Math.floor(Math.random() * (max - min + 1)) + min;
  var item = _MEALS[number];
  document.getElementById('mealofthedayimg').src = 'images/'+item.img;
}

// listen on click event for order button
document.body.addEventListener("click", function (event) {
  // close modal box
  if (event.target.classList.contains("close")) {
    document.getElementById('cart').removeAttribute('style');
    document.getElementById('popup').removeAttribute('style');

    // remove classes from element
    document.getElementById('cartoverview').classList.remove('hidden');
    document.getElementById('personalinformation').classList.add('hidden');
    document.getElementById('confirmation').classList.add('hidden');
  }
  // open modal box
  if (event.target.classList.contains("orderBtn")) {
    event.preventDefault();
    showModal(event.target.getAttribute("id"));
  }

  // add item in cart
  if (event.target.classList.contains("placeOrderInCart")) {
    event.preventDefault();
    var item = JSON.parse(event.target.getAttribute("data-item"));
    if (item) {
      addItemInCart(item);
    }
  }
});

setTimeout( function() {
  // console.log(_MEALS);
  makeTemplateFromArray(_MEALS);
  prepareOptions(_MEALS[0]);

  setRandomItem();
}, 100);

A: *

*After you add something into _ItemsInCart, set _ItemsInCart as data in localstorage.

*Before you want to get something from _ItemsInCart, get data from localstorage first and set it to _ItemsInCart.
_ItemsInCart should always sync with your data in localstorage.
How to use localstorage:
https://www.w3schools.com/html/html5_webstorage.asp

Advice: If possible, separate your DOM manipulating code with your logic code.


text:
Q: Lektor command-line installation fails on OS X 10.11.6 I've just installed Lektor desktop app for OS X on two computers, and when I select "Install Shell Command", it prompts for admin credentials (my default user account is not admin in either case) and after I've entered the admin details it then responds with:

Error
  Failed to install shell commands

A search for 'lektor' in the console revealed no log entries.
Both machines have XCode 8.0 installed (don't know if this makes a difference).
(FYI, but not part of this question, subsequent attempts to install the Command Line App via the bash script succeeded on one and failed on the other computer.)

A: didn't work for me either. So I looked at the shell script for command line installation and saw that it is basically only a wrapper around a python script.
Solution:
I copy/pasted the python code from the shell script into a file and then ran it on the command line. Installation worked fine then.
Steps I've taken:

*

*Environment: macOS 10.12.1 with python 2.7.12_2 installed via homebrew, fish shell (just a bash replacement)

*used the "curl ..." link from getlektor.com to download the script -
you need to modify it to get the file without
immediately installing:
curl -sf https://www.getlektor.com/install.sh > getlektor.txt

*open getlektor.txt in an editor and copy the python code into a new which named "install_lektor.py". The python code starts with the line
"import os" and ends with the line "main()"

*run the new python script with "python install_lektor.py"

Hope this helps!


text:
Q: Calculating and comparing histograms of complex numbers If I have a 1D sequence of complex numbers with real and imaginary parts, how can I compute the histogram of this sequence?  Do I separately compute the histogram of both the real and imaginary parts?
Moreover, if I get a 2D histogram of a sequence of complex numbers, how do I apply goodness of fit tests (such as the $\chi^2$ test) to compare two histograms of complex numbers?
Is there a good reference book on the computation of histograms of complex numbers?
How would such a histogram of complex numbers be visually represented?

A:
If I have a 1D sequence of complex numbers with real and imaginary parts, how can I compute the histogram of this sequence? Do I separately compute the histogram of both the real and imaginary parts?

A complex number is just an ordered pair of real numbers (i.e., a two-element vector of real numbers) with extended definitions of arithmetic operators like addition, multiplication, etc.  Visualisation of a data set of complex numbers can be done just like any other data-set consisting of bivariate vectors of real numbers.  It is important to treat the values as bivariate values, to retain any statistical relationships between the parts, so it is not generally a good idea to construct separate histograms of the real and imaginary parts.
The best way to visualise a vector of complex numbers is to generate the kernel density estimator (KDE) of this data and then visualise this using either a surface plot, a contour plot, or a heat plot, taken over the two-dimensions of the complex numbers.  (A histogram is just a clunky version of a KDE; you are better off using a KDE with a smooth kernel that does not depend on arbitrary bin choices.)  If you use a contour plot or heat plot you can easily superimpose a scatterplot of the data values, which allows you to see the raw data, plus the estimated density of that data.  This is what I would recommend.
Here is an example of what this looks like when implemented in R.  In this code we generate some random complex data, and plot a scatterplot of the data with contours from the KDE using the ggalt package.  This gives a clear visualisation of the raw data, plus giving an outline of the contours of its estimated density.
#Generate random vector X consisting of n complex values
set.seed(1)
n   <- 100;
ARG <- 2*pi*runif(n);
MOD <- rgamma(n, shape = 2, scale = 10) + rgamma(n, shape = 5, scale = 12);
X   <- complex(modulus = MOD, argument = ARG);

#Generate scatterplot with KDE contours
library(ggplot2);
library(ggalt);
DATA <- data.frame(Real = Re(X), Imaginary = Im(X));
THEME <- theme(plot.title    = element_text(hjust = 0.5, size = 14, face = 'bold'),
               plot.subtitle = element_text(hjust = 0.5, face = 'bold'),
               axis.title.x  = element_text(hjust = 0.5, face = 'bold'),
               axis.title.y  = element_text(hjust = 0.5, face = 'bold'));
ggplot(DATA, aes(x = Real, y = Imaginary)) + THEME +
       geom_point(size = 4, alpha = 0.4) + geom_bkde2d(bandwidth = c(20, 20)) +
       ggtitle('Scatterplot of complex data values with kernel density contours');


text:
Q: How to get list files matching name in Python I am trying to get a list of files in a directory which match a certain name e.g in Bash the Code would be :

BASH

 FOLDER="MainProject"
 FILES=`find "$FOLDER" -name "Localizations*swift"`

Python

import os

def read_files():
    path = 'MainProject/'
    folders = []
    for r, d, f in os.walk(path):
        for folder in d:
            folders.append(os.path.join(r, folder))
    for f in folders:
        print(f)

Please note I am new to python hence I am struggling with this.

A: If you only need files in a single directory (no depth):
from glob import glob
import os

def read_files():
    path = 'MainProject/'
    print(list(glob(os.path.join(path, "Localizations*swift"))))

If you only need file names (and not directory names) recursively:
from fnmatch import fnmatch
import os

def read_files():
    path = 'MainProject/'
    for r, d, f in os.walk(path):
        if fnmatch(f, "Localizations*swift"):
            print(os.path.join(r, f))

A: If You want to look at the current dir:
path = 'MainProject/'
f_name = 'Localizations*swift'
all_files = os.listdir(path)
matching_files = [file for file in all_files if file==f_name]

if You want to 'walk' through the current and all subdirs, make use of the os.walk function.
Also You can use some regex, to match file names
import os
for root, dirs, files in os.walk(path, topdown=False):
   for name in files:
       # if name.find(f_name)>-1: # name contains f_name
       if name==f_name:
           print(os.path.join(root, name))


text:
Q: Calling a function in an if-else statement I'm trying to get the add() function to calculate in the if-else statement and not the line commented out for part of an assignment but I'm not sure how to get it to show the result in a new window.

function add(){
   return +num1 + +num2
};

const num1 = window.prompt("Enter a number: ");
const operatorInput = window.prompt("Do you want to add, subtract, multiply, or divide?");
let num2;

if (operatorInput === "add" || operatorInput === "Add") {
    num2 = window.prompt("Second Number: ");
    // add()
    // let sum= parseInt(num1) + parseInt(num2)
    // alert(num1 + " " + "+" + " " + num2 + " " + "=" + " " + add());
    alert(`${num1} + ${num2} = ${add()}`);
};

A: Not sure if that's what you need.
var num1 = parseFloat(window.prompt("Enter a number: "));
var operatorInput = window.prompt(
    "Do you want to add, subtract, multiply, or divide?"
);
while (
    operatorInput.toLowerCase() != "add" &&
    operatorInput.toLowerCase() != "multiply" &&
    operatorInput.toLowerCase() != "divide" &&
    operatorInput.toLowerCase() != "subtract"
) {
    alert("Invalid Input! Please try again");
    operatorInput = window.prompt(
        "Do you want to add, subtract, multiply, or divide?"
    );
}
var num2 = parseFloat(window.prompt("Second Number: "));
var resultWindow = window.open("", "Result Window", "width=200,height=200");
if (operatorInput.toLowerCase() == "add")
    resultWindow.document.write(
        `
${num1 + " " + "+" + " " + num2 + " " + "=" + " " + (num1 + num2)
        }
`
    );
else if (operatorInput.toLowerCase() == "multiply")
    resultWindow.document.write(
        `
${num1 + " " + "*" + " " + num2 + " " + "=" + " " + num1 * num2
        }
`
    );
else if (operatorInput.toLowerCase() == "divide")
    resultWindow.document.write(
        `
${num1 + " " + "/" + " " + num2 + " " + "=" + " " + num1 / num2
        }
`
    );
else
    resultWindow.document.write(
        `
${num1 + " " + "-" + " " + num2 + " " + "=" + " " + (num1 - num2)
        }
`
    );

You should be careful with using new windows to display information, it's not recommended and many browsers now adays automatically blocks these actions and consider them as spam popup windows if they're directly invoked by javascript. If the results are not being shown for you make sure to allow your browser to allow popups from the link you're displaying it from.


text:
Q: AZCopy - using /XO parameter from filesystem to blob storage? My goal is to copy from the filesystem to blob storage, skipping any files that are newer or equal on blob storage. From the documentation, this appears to be possible by using the /XO parameter.

/XO
Excludes an older source resource. The resource will not be copied if the last modified time of the source is the same or older than destination.

However, this does not appear to work for me. Is it because the source is a local filesystem and not another storage account?
I've run the following command to test.
AzCopy /Source:"D:\files" /Dest:https://myaccount.blob.core.windows.net/files /destkey:** /L /S /XO /V:files.txt

A: The command above works. I had moved the source files via FTP, thus rewriting the last modified date, making the filesystem files appear newer.


text:
Q: Modifying object's property results in read-only error I have this problem: I'm trying to modify one of the object's properties with the value from the input form (<el-input> in the example). Our company stack utilizes VueJs + TS + ElementUI. Unfortunately, it seems that objects' properties cannot be reactive and are in read-only mode. How can I make object properties reactive?
HTML/CSS
<el-input v-model="group.groupDescription" type="textarea"></el-input>

JS:
interface ViewGroupResult {
  id: string;
  groupDescription: string;
}

import Vue from 'vue';
import {Component, Watch} from 'vue-property-decorator';
@Component
apollo: {

  group: {
    query() {
          group(groupId: $groupIdOrSlug) { ... }
        }
    },
    variables() {
      groupId: this.id
    },
    fetchPolicy: 'network-only',
    loadingKey: 'groupLoading'
  },

export default class ViewGroupPage extends Vue implements
    group: ViewGroupResult | null = null;

When I try to type something in the text area above, the value is never updated for the group object's property group.groupDescription even though it's bound with v-model directive.
Error in event handler for "input": "TypeError: Cannot assign to read only property 'groupDescription' of object '#<Object>'"
Do I misunderstand the way getters/setters are bound to data properties in VueJs, or is this a TypeScript specific problem? Thanks in advance!

A: In VueJS there is strict parameters blocking developers from modifying props directly. The workaround is to set a data property to the initial value given by the corresponding prop. I.E. given a prop of initialUser we would set a data property of user with it's value set to this.initialUser with this method you'll be able to modify the user variable while still getting the initial value passed to the component via the initialUser prop. Please let me know if you have any questions.
    props: {
        initialUser: {
            type: Object,
            required: true
        }
    },
    data() {
        return {
            user: this.initialUser
        }
    },


text:
Q: Gemfire get the error from cqEvent I have a registered cqListener on a region. How can i get the actual error why onError had occured from the parameter of the method const gemfire::CqEvent& cqEvent?
I checked the documentation but it seems they don't have any method on the CqEvent class that can acctually retrieve a possible error.

A: @Alex
Hi Alex,
See what documentation says:
/**
   * This method is invoked when there is an error during CQ processing.
   * The error can appear while applying query condition on the event.
   * e.g if the event doesn't has attributes as specified in the CQ query.
   * This event does contain an error. The newValue may or may not be
   * available, and will be NULLPTR if not available.
   */
  virtual void onError(const CqEvent& aCqEvent);

It explicitly mentions "This event does contain an error". and CqEvent also does not contain method to get the error.


text:
Q: fullscreen for vlc in Awesome wm is there a way to let awesome set vlc in full screen without displaying the menu and progress-bar? I already tried to do this using dbus, but this won´t work for vlc.
P.S.: the code I used for dbus is:
qdbus org.mpris.MediaPlayer2.banshee \
      /org/mpris/MediaPlayer2        \
      org.mpris.MediaPlayer2.Fullscreen True

But it seams to be a problem with mpris, I tested it with other players and it does not work. (CanSetFullscreen gives True)

A: 1. Add a rule in your rc.lua file by adding to the awful.rules.rules table:
awful.rules.rules = {
    { rule={ class='Vlc' }, properties={ fullscreen=true } },
    -- more rules ....
}

2.  In VLC go to Tools > Preferences, check "Start in minimal view mode", and click "Save".
3. Reload awesome
Now when you startup VLC, it will start in full screen with no interface showing.


text:
Q: Icon bar burger not working and displaying only one horizontal line I'm trying to create a responsive layout button that looks like this:

But the problem is that I'm not being able to create the three horizontal lines, only one of them. Staying this way:

My code:
HTML
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

</button>

CSS
.navbar-toggler {
  position: relative;
  float: right;
  width: 40px;
  height: 40px;
  margin-top: 5px;
  margin-right: 5px;
  cursor: pointer;
  z-index: 99999;
}

.navbar-toggler span {
  height: 4px;
  background: #545454;
  transition: 0.2s all;
}

.navbar-toggler span:before, .navbar-toggler span:after {
  content: "";
  display: block;
}

A: You can use the HTML unicode ☰ for hamburger icon
You can find more at here: https://www.w3schools.com/charsets/ref_utf_symbols.asp

.navbar-toggle
{
font-size:25px;
background:none;
border:none;
}
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">☰
</button>

You can also animate the icon see: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_menu_icon_js


text:
Q: ValueError: Found unknown categories ['Off', 'On'] in column 0 during fit This is my code I do not know where the error is.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels
from sklearn.preprocessing import OrdinalEncoder,OneHotEncoder

Light = ['On','Off']
Watering = ['Low','High']
# create combinations for all parameters
experiments = [(x,y) for x in Light for y in Watering]
exp_df = pd.DataFrame(experiments,columns=['A','B'])
print(exp_df)
OHE_model = OneHotEncoder(handle_unknown = 'ignore')
enc = OrdinalEncoder(categories=[['A','B'],['Low','High']])

encoded_df = pd.DataFrame(enc.fit_transform(exp_df[['A','B']]),columns=['A','B'])
#define the experiments order which must be random
encoded_df['exp_order'] = np.random.choice(np.arange(4),4,replace=False)
encoded_df['outcome'] = [25,37,55,65]

and this is the error
ValueError: Found unknown categories ['Off', 'On'] in column 0 during fit

A: The error indicates that On and Off are expected in place off A and B.
Use this code for your enc variable instead
enc = OrdinalEncoder(categories=[['On','Off'],['Low','High']])


text:
Q: Retrieve Windows Experience Rating I'm looking to retrieve a machine's windows experience rating in C#.  If possible I would also like to retrieve the numbers for each component (Graphics, RAM etc.)
Is this possible?

A: Every time the user goes through control panel to calculate the Windows Experience Rating, the system creates a new file in %Windows%\Performance\WinSAT\DataStore\
You need to find the most recent file (they are named with the most significant date first, so finding the latest file is trivial).
These files are xml files and are easy to parse with XmlReader or other xml parser.
The section you are interested in is WinSAT\WinSPR and contains all the scores in a single section. E.g.
<WinSAT>
    <WinSPR>
        <SystemScore>3.7</SystemScore>
        <MemoryScore>5.9</MemoryScore>
        <CpuScore>5.2</CpuScore>
        <CPUSubAggScore>5.1</CPUSubAggScore>
        <VideoEncodeScore>5.3</VideoEncodeScore>
        <GraphicsScore>3.9</GraphicsScore>
        <GamingScore>3.7</GamingScore>
        <DiskScore>5.2</DiskScore>
    </WinSPR>
...

A: Same with LINQ:
var dirName = Environment.ExpandEnvironmentVariables(@"%WinDir%\Performance\WinSAT\DataStore\");
var dirInfo = new DirectoryInfo(dirName);
var file = dirInfo.EnumerateFileSystemInfos("*Formal.Assessment*.xml")
    .OrderByDescending(fi => fi.LastWriteTime)
    .FirstOrDefault();

if (file == null)
    throw new FileNotFoundException("WEI assessment xml not found");

var doc = XDocument.Load(file.FullName);

Console.WriteLine("Processor: " + doc.Descendants("CpuScore").First().Value);
Console.WriteLine("Memory (RAM): " + doc.Descendants("MemoryScore").First().Value);
Console.WriteLine("Graphics: " + doc.Descendants("GraphicsScore").First().Value);
Console.WriteLine("Gaming graphics: " + doc.Descendants("GamingScore").First().Value);
Console.WriteLine("Primary hard disk: " + doc.Descendants("DiskScore").First().Value);
Console.WriteLine("Base score: " + doc.Descendants("SystemScore").First().Value);

A: Here is a snippet for VB.NET. Converted to C# (using this, I haven't actually tested the code yet, though it looks to be fine).
/// <summary>
/// Gets the base score of a computer running Windows Vista or higher.
/// </summary>
/// <returns>The String Representation of Score, or False.</returns>
/// <remarks></remarks>
public string GetBaseScore()
{
    // Check if the computer has a \WinSAT dir.
    if (System.IO.Directory.Exists("C:\\Windows\\Performance\\WinSAT\\DataStore"))
    {
        // Our method to get the most recently updated score.
        // Because the program makes a new XML file on every update of the score,
        // we need to calculate the most recent, just incase the owner has upgraded.
        System.IO.DirectoryInfo Dir = new System.IO.DirectoryInfo("C:\\Windows\\Performance\\WinSAT\\DataStore");
        System.IO.FileInfo[] fileDir = null;
        System.IO.FileInfo fileMostRecent = default(IO.FileInfo);
        System.DateTime LastAccessTime = default(System.DateTime);
        string LastAccessPath = string.Empty;
        fileDir = Dir.GetFiles;

        // Loop through the files in the \WinSAT dir to find the newest one.
        foreach (var fileMostRecent in fileDir)
        {
            if (fileMostRecent.LastAccessTime >= LastAccessTime)
            {
                LastAccessTime = fileMostRecent.LastAccessTime;
                LastAccessPath = fileMostRecent.FullName;
            }
        }

        // Create an XmlTextReader instance.
        System.Xml.XmlTextReader xmlReadScore = new System.Xml.XmlTextReader(LastAccessPath);

        // Disable whitespace handling so we don't read over them
        xmlReadScore.WhitespaceHandling = System.Xml.WhitespaceHandling.None;

        // We need to get to the 25th tag, "WinSPR".
        for (int i = 0; i <= 26; i++)
        {
            xmlReadScore.Read();
        }

        // Create a string variable, so we can clean up without any mishaps.
        string SystemScore = xmlReadScore.ReadElementString("SystemScore");

        // Clean up.
        xmlReadScore.Close();

        return SystemScore;
    }

    // Unsuccessful.
    return false;
}

I guess it only returns the overall rating, but hopefully it should get you started at least. It may only be a matter of changing a filename/parameter to get the individual ratings.


text:
Q: Do we need to remove fabric after migrating the firebase in iOS swift? While creating a new project using pod FirebaseCrashlytics, I am able to get new crashes and the existing crash count also increases when same crashes occur.
pod 'FirebaseCrashlytics', '4.5.0'
pod 'FirebaseAnalytics', '6.8.0'
pod 'FirebaseCore', '6.10.1'
pod 'FirebaseMessaging', '4.6.2'

For initializing the crashlytics I have added the script in the build phases:
"${PODS_ROOT}/FirebaseCrashlytics/run"
Input Files:

${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/Contents/Resources/DWARF/${TARGET_NAME} $(SRCROOT)/$(BUILT_PRODUCTS_DIR)/$(INFOPLIST_PATH)
NOTE:

*

*While forcing a crash in the existing project that we migrated from Fabric to Firebase, the crashlytics are not logged, if we removed the fabric functionalities from the plist/build phase and entire code and followed the above steps.

*While forcing a crash in the existing project that we migrated from Fabric to Firebase, the crashlytics are logged, if we are not removing the fabric functionalities from the plist/build phase and entire code and followed the above steps.
Is there any additional settings that need to be done so that the crashes are logged in the migrated project itself?

A: If you have migrated your app from Fabric, you cannot simply delete your Fabric API key and Fabric dependencies, this will cause issues for your app. Make sure you follow this guide entirely for your migrated app, and it should resolve any of your crash reporting issues.


text:
Q: Dynamic SQL isn't updating table So I need to basically get the count of every table in a database daily and insert those counts into a separate database for analysis and reporting purposes. The table the counts need to be inserted into has a column named after each table in the first database. For some reason, the columns aren't being updated with the counts for their respective tables. If I change the @TableName variable to the a single table name, the count for the last table is correctly updated, so it appears to be an issue with that specific variable. My SQL is below. I have another table with all the table names and an auto increment column that the table names are selected from. If I print the @TableName and @row_count variables instead of trying to update the table, they appear to print the correct table and row counts. Ideas?
DECLARE @Count int;
DECLARE @TableCount int;
DECLARE @TableName varchar(255);
DECLARE @row_count int;
DECLARE @SQLString nvarchar(MAX);
DECLARE @ParmDefinition nvarchar(MAX);

SET @TableCount = 1;

SELECT @Count = COUNT(*) FROM db1.INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG = 'db1';

INSERT INTO db2.[dbo].[row_counts] ([type])
VALUES('total');

WHILE @TableCount <= @Count
BEGIN

SELECT @TableName = [TableName] FROM db2.[dbo].[ListofTables] WHERE TableNumber = @TableCount;

SELECT @SQLString = N'SELECT @CountOUT = COUNT(*) FROM db1.[dbo].[' + @TableName + ']';
SET @ParmDefinition = N'@CountOut int OUTPUT';

EXEC sp_executesql @SQLString, @ParmDefinition, @CountOUT=@row_count OUTPUT;

UPDATE [db2].[dbo].[row_counts]

SET @TableName = @row_count

WHERE creation_time = (SELECT MAX(creation_time) FROM [db2].[dbo].[row_counts]);

SET @TableCount = @TableCount + 1;
END;

A: I didn't attempt to follow your logic, but the following caught my eye:
   ... UPDATE [db2].[dbo].[row_counts] SET @TableName = @row_count...

This is only updating @TableName variable.
To update the table, you need to SET one of the table columns, not a variable.
HTH

A: Counting the rows in all the tables is expensive and complicated.  How about
select schema_name(o.schema_id) schemaName, object_name(o.object_id) tableName , p.rows
from
sys.objects o
join sys.partitions p
  on o.object_id = p.object_id
where index_id in (0,1)
  and o.is_ms_shipped = 0


text:
Q: Can the login screen be a fragment? I create an application that will have a home screen, a login screen for one of the functions and a screen for this function. Should I only take the main screen as aсtivity, and the login and function screen as fragments, or everything as activity? And if more than one aсtivity, can I use nav graph?
At first, I wanted to create only one activity, but I'm not sure if the login screen can be a fragment?

A: As a best practice, you should use single activity. You could have many fragments and navigate between them using the navigation component.


text:
Q: Monitor a java file for execution I have a .jar file that I would like to check if it gets called/executed. The program that is supposed to access it is visual studio post build events, but I have no idea if it gets executed.
My OS is Windows 7.

A: Process Monitor can also monitor file access
http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx
.

A: Depending on exactly how Visual Studio is running the JAR, you might be able to simply rename the JAR and see if the build breaks.
It's one thing to detect if the JAR file is opened (try Process Monitor), but to see if the specified Main-Class is actually loaded and its byte code executed, you'd need to hook into the JVM with a debugger or instrumentation. That requires some switches passed to the JVM at startup.
As a post-build task, I'd guess the process runs without intervention, and perhaps very quickly, so you'd need to suspend on startup (also possible with startup switches) in order to hook into it.
A lower-tech approach would be to replace the JAR with something that does something very obvious, like display a message or leave a file. You could even take the existing JAR, and modify it slightly so that it runs the "Hello, Obvious" class first, then calls the original class to do what it is supposed to.


text:
Q: Cross-compile with Terry Guo's gcc-arm-none-eabi I'm trying to test a cross compile using Terry Guo's gcc-arm-none-eabi. In a nutshell, here are the steps to install on Ubuntu:

*

*sudo add-apt-repository ppa:terry.guo/gcc-arm-embedded

*sudo apt-get update

*sudo apt-get install gcc-arm-none-eabi

The problem I am having is I can't find the documentation (or I'm doing something wrong). I know I can't ask for documentation or other off-site resources, so I'll cut right to the chase:

*

*What is the name of the compiler?

*Where is the compiler located?

*Where are the arm-eabi headers located?

*Where are the arm-eabi libs located?

*Where is the arm-eabi sysroot located?

$ find /usr -iname *arm-eabi*
$ find /usr -iname *gcc-arm*
/usr/share/lintian/overrides/gcc-arm-none-eabi
/usr/share/doc/gcc-arm-none-eabi
$ info gcc-arm-none-eabi
No menu item `gcc-arm-none-eabi' in node `(dir)Top'.
$ man gcc-arm-none-eabi
No manual entry for gcc-arm-none-eabi

A: The problem was I got Debian's anemic arm embedded tools on Ubuntu 14; and not Terry Guo's tools even though I added Guo's PPA. This can be fixed with:

*

*sudo apt-get remove binutils-arm-none-eabi gcc-arm-none-eabi

*sudo apt-get autoremove

*sudo add-apt-repository ppa:terry.guo/gcc-arm-embedded

*sudo apt-get update

*sudo apt-get install gcc-arm-none-eabi=4-8-2014q2-0trusty10

With the proper package in place:

What is the name of the compiler?
  Where is the compiler located?

/usr/bin/arm-none-eabi-gcc and friends.

Where are the arm-eabi headers located?
  Where are the arm-eabi libs located?
  Where is the arm-eabi sysroot located?

SYSROOT is /usr/lib/gcc/arm-none-eabi/4.8.2/armv7-m.
I also needed to compile with -mcpu=cortex-m3, -mthumb and --specs=nosys.specs.

Related: Ubuntu will attempt to upgrade Guo's packages during a upgrade or dist-upgrade. The behavior can be modified by pinning Guo's package. To pin Guo's package, add the following to /etc/apt/preferences:
Package: binutils-arm-none-eabi
Pin: origin ppa.launchpad.net
Pin-Priority: 900

Package: gcc-arm-none-eabi
Pin: origin ppa.launchpad.net
Pin-Priority: 900

Thanks to grawity on Super User for the information. See Permanently block distro package installation?.


text:
Q: PDO query encoding with MSSQL I have terrible problem getting me sick :) Here is my simple example of my problem:
$driver="SQL Server; TDS_Version=7.2; Port=1433";
$dbh = new PDO("odbc:Driver=$driver;Server=$server;Database=$database;charset=utf-8;Uid=$username;Pwd=$password;");
$query="select * from table where f_name like '%aleš%'";
$sth = $dbh->prepare($query);
$sth->execute();
$result = $sth->fetchAll();

I have problem with encoding of czech names (aleš). However this query should return some results, it won't. When I do same query with name witch doesn't contain any czech-specific letter (petr), it works perfectly.
I've found some comment on MS-website, that mssql server accept only ucs-2 encoded vartext queries. I've tried that somehow as well, but without luck. Any ideas? Thank you very much! (Sorry - this is my 1st time with mssql).

A: I have approximately the same setup as you (SQL Server, PDO) and had the same problem.
Now I send the form data to PHP via jQuery AJAX call and when I construct the GET string I do 'encodeURIComponent' and it encodes the special characters (ščžýáí) correctly.
var formdata = $('#test_form').serializeArray();
req = '';
$.each(formdata, function(i,element){
    req += element.name + "=" + encodeURIComponent(element.value) + "&";
});


text:
Q: Is it possible to merge raster base maps with a DTM? In ArcMap 10.1
I have two raster layer 1) a raster base map and 2) a DEM raster.
Is it possible to merge the two to create an attractive visual showing the background map and terrain?  i.e. in Global Mapper there is an option to multiply layers together.
I have tried putting the base map on top making it slightly transparent so the underlying DTM is visible underneath.  But the result is quite faint thereby missing off base map detail.

A: Try creating a hillshade of the DEM and laying that, semi-transparent, over the basemap.  They will not be "merged" per se, but it should give the visual effect you are seeking.


text:
Q: difference from date from sql and current date using LocalDate returns 0 when setting text in a jTextField I'm trying to subtract date from sql database to current date. I tried the output in console and it works fine. The years between works properly. But when i tried to show the output in a text field it always return 0. Here is my code.
    public void checkDate() {
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    String date1 = ((JTextField)
    jDateChooser1.getDateEditor().getUiComponent()).getText();
    LocalDate birthdate = LocalDate.parse(date1, dtf);
    LocalDate ld = LocalDate.now();
    int rt = Period.between(birthdate, ld).normalized().getYears();
    System.out.println(rt);
    age.setText("" + rt);
    }

I create a event mouseClicked to jTextField age. It always return 0. Please help


text:
Q: Webmail client with google imap Im developing a webmail client using Zend framework and gmail IMAP.
Features like moving email from one folder to another ,Flagging,
mail composing,Drafts etc.
Simply it should reflect the same way as you see in the Gmail.
Technically Can any body point me towards right direction.? I mean the zend library supports REST ,JSON,IMAP,
As far as database is concerned im fine and im able to get all the data around 100 MB of data im able to store.
How should my approach be as far as architecture is concerned.Does REST & GMAIL IMAP combinedly can be used to perform manipulations ?
because always the server should always get new mail instantly may be at 5-10 min gap .
PLEASE Advise.
Also does gmail provide REST support to get new emails? OR we have to develop REST SERVER and consume the Rest client?
Also i would appreciate good hyper links to point over for kind of architecture.
Thanks
Mark

A:
Technically Can any body point me towards right direction.? I mean the zend library supports REST ,JSON,IMAP,

These three acronyms have nothing do to with each other.

*

*REST is an architectural  philosophy.

*JSON is a data encoding format.

*IMAP is a protocol for accessing mailboxes.

Yes, Zend Framework has components that deal with all of these things, but that doesn't mean you have to use all of them.
If you want to access your Gmail account through IMAP, then use one of the Zend_Mail_Storage classes.

Does REST & GMAIL IMAP combinedly can be used to perform manipulations ?

If by that you mean "Can I write a RESTful application that uses IMAP to communicate to Gmail?", then the answer is yes, yes you can.

the server should always get new mail instantly may be at 5-10 min gap

It sounds like you want a cron job running to continuously poll the server for mail, instead of using an active IMAP connection live whenever the user is making requests.

Also does gmail provide REST support to get new emails?

It took them years to give us just basic IMAP support, I don't think we're going to see a RESTful API out of them any time soon.  Keep in mind that they earn money based off of ad views.  You aren't viewing ads when you use IMAP.

Also i would appreciate good hyper links to point over for kind of architecture.

Are you kidding?  No, really, look at what you're doing. You're building a webmail client designed to access another webmail client.  Do you realize how incredibly silly that is, my friend?  You're re-inventing a re-invented wheel.
I don't know of a single worthwhile webmail client outside of Gmail.  If you want to study the architecture of other webmail clients in PHP, then take a look at IMP (designed for PHP 4, and therefore ancient), Roundcube, or SquirrelMail.  I am not responsible for any brain damage you suffer from reading the source.


text:
Q: SQL Join with Sub Query I'm trying to create a query that gets the most recent record with the status for each user and displays it, the required data is over three tables on a Microsoft SQL Server.
Tables:

*

*tblUser

*tblStatusName

*tblStatusLog

My SQL so far:
SELECT x.LatestTime AS 'Last Activity', FName + ' ' + LName AS 'User'
FROM tblUser,
    (SELECT UserID, MAX(ServerTime) As LatestTime
    FROM tblStatusLog
    GROUP BY UserID) AS x
WHERE tblUser.ID = x.UserID

I now need to join tblStatusName so I can link the StatusID column in tblStatusLog to the ID column in tblStatusName so I can get the Status Description, but I can't work out how to do this due to the aggregate function preventing me from doing so. The query will be ran often - every few seconds by multiple people so efficiency is desired.
I've tried something like the below, but this doesnt work due to the sub-query.
INNER JOIN tblStatusName
ON X.StatusID = tblStatusName.ID

The desired output would be
Last Activity Time | User | Latest Status

Sorry if this is relatively basic, my SQL is a little rusty since my uni days.
I should add that tblStatusLog is a table that has the following columns:

*

*ServerTime (Server timestamp of status change)

*UserID  (FK to tblUser)

*StatusID (FK to tblStatusName)

A: SELECT
  x.LatestTime AS 'Last Activity',
  FName + ' ' + LName AS 'User',
  tblStatusName.Status
FROM tblUser
CROSS APPLY
    (SELECT TOP (1) UserID, ServerTime As LatestTime, StatusID
    FROM tblStatusLog
    WHERE tblStatusLog.UserID = tblUser.ID
    ORDER BY ServerTime DESC) AS x
INNER JOIN tblStatusName
ON x.StatusID = tblStatusName.ID
WHERE tblUser.ID = x.UserID;

A: The CROSS APPLY is a great approach.   An alternative older method is to use virtual tables (inline view).  A sample setup and query is below.
-- tblStatusName
drop table [tblStatusName]
GO
CREATE TABLE [dbo].[tblStatusName](
    [ID] [int] NULL,
    [Status] [nchar](30) NULL
) ON [PRIMARY]
GO
insert into tblStatusName values ('10', 'LOGON');
insert into tblStatusName values ('20', 'LOGOFF');

-- tblStatusLog
drop table [tblStatusLog]
GO
CREATE TABLE [dbo].[tblStatusLog](
    [ServerTime] [date] NULL,
    [UserID] [int] NULL,
    [StatusID] [int] NULL
) ON [PRIMARY]
GO
insert into tblStatusLog values ('01 FEB 2020', 1, 10);
insert into tblStatusLog values ('02 FEB 2020', 1, 20);
insert into tblStatusLog values ('03 FEB 2020', 1, 10);
insert into tblStatusLog values ('01 FEB 2020', 2, 10);
insert into tblStatusLog values ('02 FEB 2020', 2, 20);
insert into tblStatusLog values ('03 FEB 2020', 3, 10);

-- tblUser
drop table [tblUser]
GO
CREATE TABLE [dbo].[tblUser](
    [ID] [int] NULL,
    [FName] [nchar](10) NULL,
    [LName] [nchar](10) NULL
) ON [PRIMARY]
GO
insert into tblUser values (1,'FName 1',' LName 1');
insert into tblUser values (2,'FName 2',' LName 2');
insert into tblUser values (3,'FName 3',' LName 3');
GO

SELECT A.LatestTime, B.FName + ' ' + B.LName AS 'User', B.Status
FROM (
    SELECT UserID, MAX(ServerTime) As LatestTime
    FROM tblStatusLog
    GROUP BY UserID
    ) AS A,
    (
    SELECT tblStatusLog.UserID, tblUser.ID, tblUser.FName, tblUser.LName, tblStatusLog.ServerTime, tblStatusLog.StatusID, tblStatusName.Status
    FROM tblStatusLog,
         tblStatusName,
         tblUser
    WHERE tblStatusLog.StatusID = tblStatusName.ID
      AND tblStatusLog.UserID = tblUser.ID
    ) AS B
WHERE A.UserID = B.UserID
  AND A.LatestTime = B.ServerTime
ORDER BY A.LatestTime DESC
GO


text:
Q: currentText() doesn't collect data from field My program is currently divided into 2 files: one with GUI and second with code. In GUI, there's button I want to use to collect the data from text fields and put them into variables:
self.dodaj.clicked.connect(Dodaj_Ksiazke.pobierz_dane)

It's supposed to call the function "pobierz_dane". Inside the code there is class "Main" where above function is defined:
def pobierz_dane(self):
    print("Pobieranie danych z formularza do zmiennych")
    print(self.ui.isbn.currentText())
    isbn = self.ui.isbn.currentText()
    print(isbn)

As you can see I tried various ways to confirm it's working. When I start the program and click the button the first print gets displayed but not the 2nd or 3rd one, this is where program crashes with error:
Process finished with exit code -1073740791 (0xC0000409)

Text field I'm trying to get the text from is defined like this:
    self.isbn = QtWidgets.QLineEdit(self.centralwidget)
    self.isbn.setObjectName("isbn")
    self.gridLayout_2.addWidget(self.isbn, 1, 2, 1, 1)

This is the beginning of GUI deifnition:
class Ui_Dodaj_Ksiazke(object):
    def setupUi(self, Dodaj_Ksiazke):

And Main class from file with code:
class Main(QtWidgets.QMainWindow,Ui_Dodaj_Ksiazke):
    def __init__(self):
       QtWidgets.QMainWindow.__init__(self)
       self.ui= Ui_Dodaj_Ksiazke()
       self.ui.setupUi(self)

Since the first print is working I guess the button correctly calls the function. But I can't nail why it's not working for the text field as I don't get any errors when running the program.

A: Problem was fixed by switching from currentText() to displayText() as there is no attribute 'currentText' in QLineEdit.
isbn = self.ui.isbn.displayText()

Text is taken from text field stored correctly in variable, displayed by print() and program doesn't crash.


text:
Q: What is the core difference between an intially assigned variable and a initially unassigned variable? C# The Microsoft documentation describes it as:

Variables are either initially assigned or initially unassigned. An initially assigned variable has a well-defined initial value and is always considered definitely assigned. An initially unassigned variable has no initial value.

But what does this actually mean?
Is it simply stating when a variable is declared it's either assigned a value (i.e., such a variable is an initially assigned a value) or not (i.e., such a variable is initially unassigned).
Is my assumption correct?

A: Yes it is just a statement. There are not any major differences between the two. Unassigned variables are initialized with the default value for the data type when the program runs. The only time you will run into an issue with unassigned variables is if you assign it in if blocks and don't have an else statement and then attempt to use the variable outside the scope of the if block. The compiler will throw an error saying that the variable is potentially unassigned in this case. Ex:
string testString;
if (some condition here)
    testString = "Success";

if (testString == "Success") //This line will throw an error because testString may be unassigned

string testString = "Failure";
if (condition)
    testString = "Success";

if (testString == "Success") //No error this time becuase testString was initialized with a value

string testString;
if (condition)
    testString = "Success";
else
    testString = "Failure";

if (testString == "Success") //No error here because all paths will assign a value to testString

Edit from Microsoft:
Initially assigned variables
The following categories of variables are classified as initially assigned:

*

*Static variables.

*Instance variables of class instances.

*Instance variables of initially assigned struct variables.

*Array elements.

*Value parameters.

*Reference parameters.

*Variables declared in a catch clause or a foreach statement.

Initially unassigned variables
The following categories of variables are classified as initially unassigned:

*

*Instance variables of initially unassigned struct variables.

*Output parameters, including the this variable of struct instance
constructors.

*Local variables, except those declared in a catch clause or a
foreach statement.

public static int globalId; //assigned
public class TestClass
{
    int Id; //Assigned
    public void TestMethod()
    {
        int methodId; //Not assigned
    }
}


text:
Q: "'Image' object is not callable" when posting API object Update 2, 13th Jan: After doing some bug searching and trying to post the object directly in the root API using json, I've come to the realisation that the image is what's giving me the posting error.
I used the HTML form to post an object and it gave me this error:
TypeError at /rats/

'Image' object is not callable

For context, I uploaded an image. Here are my serialisers for creating the object (rat) and for images:
class ImageSerializer(FlexFieldsModelSerializer):
    image = VersatileImageFieldSerializer(
        sizes='rat_headshot'
    )

    class Meta:
        model = Image
        fields = ['name', 'image']

class RatSerializer(FlexFieldsModelSerializer):
    user         = serializers.CharField(source='user.username', required=False)
    userid       = serializers.CharField(source='user.id', required=False)
    body_colour  = BodyColourSerializer()
    eye_colour   = EyeColourSerializer()
    image        = ImageSerializer(required=False)

    class Meta:
        model = rat
        exclude = ['bio']

    def create(self, data):
        request = self.context.get("request")
        print("I was here", data, request)
        return rat.objects.create(
            name = data["name"],
            body_colour = BodyColour(name=data["body_colour"]["name"]),
            eye_colour = EyeColour(name=data["eye_colour"]["name"]),
            # bio = data["bio"],
            image = Image(name=data["image"]["name"])(required=False),
            user = request.user,
        )

I've updated the title. Original title was "Can't manage to post an object via axios to django - possibly due to AnonymousUser object?", now it's " "'Image' object is not callable" when posting API object "

Update 8th Jan: I fixed the AnonymousUser error. Django wanted an ID but was instead getting the user class, I fixed it by changing user = request.user into user = request.user.id
However, I'm still unable to post the object. I'm getting the same res.data error as below. So now I'm not sure what's causing the error.

I'm trying to add a button in React which posts an object to django via axios when a user clicks on it. However, it seems like something's wrong backend.
Here's the button:
<button
            id="add-rat"
            type="button"
            className="btn homeButton"
            onClick={
              (e) => submit(e)
            }
          >
            Add rat
          </button>

And here's the axios, in the same page:
  const submit = (e) => {
    const name = "namee";
    const eyeColour = "Red";
    const bodyColour = "White";
    const bio = "hfff";
    const image = "lineart.PNG";
    const data = {
      name: name,
      eye_colour: eyeColour,
      body_colour: bodyColour,
      bio: bio,
      image: image,
    };
    e.preventDefault();
    console.log(data);
    const token = localStorage.getItem("token");
    axios
      .post("http://127.0.0.1:8000/api/addObject", data, {
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
      })
      .then((res) => {
        console.log(res.data);
      })
      .catch((err) => console.log(err));
  };

This is my console output:
{name: 'namee',

 eye_colour: 'Red', body_colour: 'White', bio: 'hfff', image: 'lineart.PNG'}
myRats.js:86 {res: 'Error Accured'}

(myRats.js:86 btw, is console.log(res.data); )
Here's my view for the object:
class AddRat(APIView):
def post(self,request):
    data = request.data
    user = request.user
    print(data)
    try:
        user = rat( name = data['name'] , body_colour = data['bodyColour'] , eye_colour = data['eyeColour'],user= user,  bio = data['bio'] , image = data['image'])
        user.save()
        return Response({'res':"Rat Saved Successfully"})
    except:
        return Response({'res':"Error Accured"})

def get(self,request):
    user = request.user
    data = rat.objects.filter(user = user)
    data = RatSerializer(data, many = True)
    return Response({'data':data.data})

When I go to the url it's posting to, I get this error:
TypeError at /api/addObject
Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x0000014641FD85B0>.

Could it possibly be due to that? What could be wrong?

A: The Anonymous User issue was solved by changing user = request.user into user = request.user.id
And my second issue, "'Image' object is not callable" was due to me putting (required=False) in another set of parenthesis, as if I was calling an Image as a function.
So I changed
image = Image(name=data["image"]["name"])(required=False)

into
image = Image(name=data["image"]["name"], required=False)


text:
Q: Empty table rows with ng-repeat, AngularJS I have input fields that you can submit, and the data that you entered is inserted into an database. This data is then looped out in a table with ng-repeat:

                Sträcka
                Tid
                Jämför

{{info.stracka}}	{{info.tid}}	<input type="checkbox" id="{{info.id}}" class="checkboxfisk" ng-click="testa(info.id)">

The problem is that, When the database table is empty, and you are submiting data for the first time, 3 empty TR's rows are printed out, after you have hit submit. I used firebug to debug this, and the HTML look like this when I hover on the empty TR-rows:

Sträcka
Tid
Jämför

<input id="" class="checkboxfisk" type="checkbox" ng-click="testa(info.id)">

<form class="ng-pristine ng-invalid ng-invalid-required" novalidate="" ng-submit="submitForm(userForm.$valid)" name="userForm">

As you can see, there are td's with classname of ng-binding. What is this? Can anyone help me?
Here is my controller:
as.controller('Test', function($scope, $http, $rootScope, testFactory)
{
    $http.get($rootScope.appUrl + '/nao/test/test')
        .success(function(data, status, headers, config) {
            $scope.test = data.data;
    });

    $scope.form = {};
    $scope.checkboxes = [];

    $scope.testa = function(id) {
        $scope.checkboxes.push(id);
    };

    $scope.submitForm = function(isValid) {
        if(isValid)
        {
            $http.post($rootScope.appUrl + '/nao/test', $scope.form)
            .success(function(data, status, headers, config) {
                console.log(data);
                console.log($scope.form);
            }).error(function(data, status) {

            });
        }
    };
});

EDIT: The problem was in my backend. I've have forgotten to add a parameter that is returned after that the mysql query is executed.

A: I see two possibilities.
In first, you should initialize your test scope variable before the $http call (to ensure it is initialized even if http request fails). And then create a method updateTest which will be called on succes of the submit form (to update test variable).
Your code should be like that:
as.controller('Test', function($scope, $http, $rootScope, testFactory)
{
    // METHOD to update test items
    updateTest = function() {
        $http.get($rootScope.appUrl + '/nao/test/test')
            .success(function(data, status, headers, config) {
                $scope.test = data.data;
        });
    };

    // init variables
    $scope.form = {};
    $scope.checkboxes = [];
    $scope.test = [];

    $scope.testa = function(id) {
        $scope.checkboxes.push(id);
    };

    $scope.submitForm = function(isValid) {
        if(isValid)
        {
            $http.post($rootScope.appUrl + '/nao/test', $scope.form)
            .success(function(data, status, headers, config) {
                console.log(data);
                console.log($scope.form);
                // update test item (to get back newly created one)
                updateTest();
            }).error(function(data, status) {

            });
        }
    };

    // first test items update
    updateTest();
});


text:
Q: Django SyntaxError at / Non-ASCII character '\xe6' in file I am getting this error:
SyntaxError at /
Non-ASCII character '\xe6' in file

pointed to my forms.py file which has some chinese characters
I have to put # -*- coding: utf-8 -*- at the start the forms.py file before it would work
I thought Django handles everything in unicode? What's wrong?

A: Nothing is wrong. You have done the correct thing. If you want to use non-ASCII characters in your code, you need to tell Python what encoding you are using.
This has nothing to do with Django, or Unicode.


text:
Q: Where can I find more diamonds or champagne? I need a bunch of diamonds to make a mod, and the only way I know of is to turn in champagne as exchange, but so far I've only found one bottle (I forgot where).  Where can I get more champagne and diamonds?

A: *

*Multiple fridges in the kitchen area of the Hotel.  (This is a one time event, you cannot go back to the kitchen after the quest there is complete)

*Two refrigerators in the abandoned house also known as the Square near the southern edge of the Moresby map. You can fast travel to and from here to farm them.

*Refrigeration units inside the Supermarket.

*Three refrigerators in the Laboratory, two in the room where Dr. West is standing, and one fridge in the corner room down the hall through the two double doors.

*Two refrigerators within the hut on the Eastern edge of the River Village, at the top of the hill.

The fridges in the Hotel was where I found the most. I think I got about half a dozen bottles of champagne from there the first time I went through.
The best way to get champagne is to fast travel between the Abandoned House and the Laboratory, checking the fridges at each location every time.
Source

A: You can find about 3-7 Bottles of Champagne in the Supermarket in the City Of Moresby, remember the path when you visit(-ed?) it. make multiple runs as needed.

A: With the kitchen (if you have the patience), you can run back and forth to the security room and the fridges will respawn, although this doesn't happen every time.
To me it was worth it. Just remember that you will not be able to come back and with a chance to get anywhere between 6-12 champagne bottles each go.

A: When I did the kitchen I found 1 or 2 champagne bottles in the first room, then when you get close to that dead body with his arm cut off next too a extra snack, the guy says there's a mob of them in there... I went in there and got like 8 9 more champagne bottles.


text:
Q: Finding what string comes last alphabetically out of three strings String wordOne = "Hello";
String wordTwo = "Bye";
String wordThree = "What";

Assuming that these are strings that the user has entered. While not being case-sensitive, how would I go about finding which word/string comes last alphabetically using only if-statements? I have started by using the .toUpperCase to try and use ASCII values but I am lost. Also, the user would be able to enter words that are the same. Any help would be very much appreciated.

A: Use the compareToIgnoreCase() function,
   int result= wordOne.compareToIgnoreCase(wordTwo);
   if(result < 0){
        //wordOne precedes wordTwo alphabetically
   }
   else if(result > 0){
         //wordOne is after wordTwo alphabetically
   }
   else{
         //they are the same
   }

Documentation here:
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#compareTo%28java.lang.String%29


text:
Q: Progress DB charindex syntax error I'm trying to create a query in progress DB that gets the name portion off the email address.  This is what I have so far:
substring("PUB"."NAME"."INTERNET-ADDRESS", 1, CHARINDEX('@', "PUB"."NAME"."INTERNET-ADDRESS") ) as Name

However, I'm getting a syntax error around the CHARINDEX(...
I'm not a progress guy and knowing SQL is just enough to get me into trouble...
Do you see the error in my ways?

A: Try this:
substring("PUB"."NAME"."INTERNET-ADDRESS", 1, INSTR("PUB"."NAME"."INTERNET-ADDRESS",'@') ).
Here you have the entire suite of documentation:
https://community.progress.com/community_groups/openedge_general/w/openedgegeneral/1329.openedge-product-documentation-overview


text:
Q: Kotling :: Android :: java.lang.ClassCastException: java.lang.Class cannot be cast to androidx.lifecycle.ViewModel I am getting an exception in the first line of the code below
viewModel.homeLiveData.observe(this, Observer { list ->

        list?.let {
            mList.addAll(list)
            adapter.notifyDataSetChanged()
        }
    })

java.lang.ClassCastException: java.lang.Class cannot be cast to androidx.lifecycle.ViewModel

The Whole code is Below
what is wrong with the cast ? is there anything wrong of I am creating my ViewModel?
My BaseActivity
  abstract class BaseActivity<V : ViewModel> : DaggerAppCompatActivity(), HasSupportFragmentInjector {

    @Inject
    lateinit var fragmentAndroidInjector: DispatchingAndroidInjector<Fragment>

    @Inject
    lateinit var viewModelFactory: ViewModelProvider.Factory

    @LayoutRes
    abstract fun layoutRes(): Int

    protected lateinit var viewModel : V

    protected abstract fun getViewModel() : Class<V>

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val id = item.itemId
        if (id == android.R.id.home)
            onBackPressed()

        return super.onOptionsItemSelected(item)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(layoutRes())
        viewModel = ViewModelProviders.of(this, viewModelFactory).get(getViewModel())
    }

    override fun supportFragmentInjector(): AndroidInjector<Fragment> = fragmentAndroidInjector
}

then My Activity
class MainActivity : BaseActivity<MainViewModel>() {

override fun layoutRes(): Int = R.layout.activity_main

override fun getViewModel(): Class<MainViewModel> = MainViewModel::class.java

private val mList = mutableListOf<Any>()

private lateinit var adapter: DataAdapter

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

   // setSupportActionBar(toolbar)

    recyclerView.apply {
        layoutManager = GridLayoutManager(applicationContext, 2)
        adapter = DataAdapter(context, mList)

    }

    viewModel.homeLiveData.observe(this, Observer { list ->

        list?.let {
            mList.addAll(list)
            adapter.notifyDataSetChanged()
        }
    })

    viewModel.getHomeItems()

}

and this is my ViewModel
class MainViewModel @Inject constructor() : ViewModel() {

val homeLiveData: MutableLiveData<List<HomeScreenModel>> = MutableLiveData()

fun getHomeItems() {

    Handler().post {

        val homeModleList = listOf(
            HomeScreenModel(R.drawable.ic_launcher_background, MyApplication.instance.getString(R.string.settings))
        )

        homeLiveData.setValue(homeModleList)
    }
}

}

A: In my opinion, your viewModel property, which you try to access in viewModel.homeLiveData is shadowed by getViewModel() abstract function that you declare in BaseActivity. This is because Kotlin thinks that getXyZ() is a getter for the field xyZ and thus when you access viewModel, the compiler thinks you want to call getViewModel, which is of type Class<V>. I suggest renaming either the function or the property and it should work then.

A: Check your viewModel factory if you implemented it correctly


text:
Q: How to run DotNet Core applications in Azure Batch Jobs I have followed Azure Batch ffmpeg tutorial and it works as expected. The problem that I have at this point is that my executable that i want to run as a batch is a dotnet core application and images that are available when creating a Pool do not have dot net core installed. In the task command line I need to run something like dotnet myApp.dll myParam but dotnet is not available.
How do I go about having an image that has dotnet core installed. Do I need to create a custom image? Is there a tutorial for doing that. I tried using Docker with dotnetcore runtime image at some point for running the same application locally and that seems to work. Do I need to export this image to Azure somehow? Or can I push the core installation into an image in another way?
Thanks.

A: If I am understanding your issue correctly, the simplest solution I see would be create your own custom image to provision a batch pool. We have a document on achieving that here:
https://learn.microsoft.com/en-us/azure/batch/batch-custom-images
This way you can preconfigure an image that has all the needed programs and languages installed right away.