text:
Q: Why a liquibase migration works on mysql and not in h2 I'm creating a jhipster based project and I'm having some problems in integration tests. I've removed login column from t_user table and did some changes to use e-mail as login. The liquibase migration works fine in MySQL, however I'm getting this error when I'm running some tests:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:94)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:72)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:200)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:252)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:217)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:77)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:195)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(org.springframework.security.config.annotation.ObjectPostProcessor,java.util.List) throws java.lang.Exception; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.security.core.userdetails.UserDetailsService com.brevleq.consami.config.SecurityConfiguration.userDetailsService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDetailsService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.brevleq.consami.repository.UserRepository com.brevleq.consami.security.UserDetailsService.userRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Cannot create inner bean '(inner bean)#1f481ec3' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1f481ec3': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'liquibase' defined in class path resource [com/brevleq/consami/config/DatabaseConfiguration.class]: Invocation of init method failed; nested exception is liquibase.exception.MigrationFailedException: Migration failed for change set classpath:config/liquibase/changelog/20150328154659_changelog.xml::1427568441617-1::hudson (generated):
 Reason: liquibase.exception.DatabaseException: org.h2.jdbc.JdbcSQLException: Constraint "IDX_USER_LOGIN" not found; SQL statement:
ALTER TABLE PUBLIC.t_user DROP CONSTRAINT idx_user_login [90057-183]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:474)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:321)
at org.springframework.boot.test.SpringApplicationContextLoader.loadContext(SpringApplicationContextLoader.java:98)
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:68)
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:86)
... 28 more

As you can see, the error is that it can't find 'idx_user_login' so, it stops the test in the database migration.
The specified migration file is this:
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.3.xsd">
  <changeSet author="hudson (generated)" id="1427568441617-1">
    <dropUniqueConstraint constraintName="idx_user_login" tableName="t_user"/>
  </changeSet>
  <changeSet author="hudson (generated)" id="1427568441617-2">
    <dropUniqueConstraint constraintName="login" tableName="t_user"/>
  </changeSet>
  <changeSet author="hudson (generated)" id="1427568441617-3">
    <dropColumn columnName="login" tableName="t_user"/>
  </changeSet>
  <changeSet author="hudson (generated)" id="1427568441617-4">
    <addNotNullConstraint columnDataType="varchar(50)" columnName="email" tableName="T_USER"/>
  </changeSet>
</databaseChangeLog>

As I told, this migration is running correctly in MySQL. This file was generated using

mvn compile liquibase:diff

Is there something I can do to make this migration work in my tests?

A: Here is my solution, how to run liquibase before the text execution on H2:
Simply copy the src/main/resources/liquibase/master.xml to src/test/resources/liquibase/master.xml.
After you have made a copy of the master.xml under src/test, liquibase would magically also run before tests and apply all changesets. Because the H2 test database is normally not persistet, liquibase would spread its changesets everytime on a clean database.
However you have to copy the master.xml everytime you create changesets. I have found no way (till now) how to setup JHipster to automatically apply changesets to the test database.

A: I had the same problem: removing a unique contstraint in PostgreSQL was working fine, bun when I ran the integration tests against a H2 database, it complained not finding the constraint I wanted to drop.
I figured out that, when creating the constraint, no specific constraintName was configured.
Apparently PostgreSQL and H2 do not generated the same constraint name. This is why it worked in only one of them.
My solution was to fix the previous script, where the constraint was created, by adding a specific name.
<column name="report_id" type="bigint">
    <constraints unique="true" uniqueConstraintName="visit_report_id_key"/>
</column>

This way, there is no difference between PostgreSQL and H2

A: I had the same issue working with mysql for production and H2 for test
Solved it by disabling liquibase for tests, and enabling schema creation by hibernate.
In test/resources/application.properties
spring.datasource.url = jdbc:h2:mem:test;MODE=Mysql
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create #Replace validate !Here!
#Liquibase
spring.liquibase.enabled=false #Replace true by false !Here!

A: I had just the same issue but it turns out H2 is only being used as a test DB for some tests that do require a Spring Context to be configured (such tests are run with "test" profile enabled). The solution in our case was to simply deleting the data.* files (the data files for H2) given they were in a inconsistent state with the incoming changes.
If your case is for local dev database, then losing your data is no big issue and this solution may work for you.


text:
Q: How to save/rotate x amount of logs using logger i must say the documenation of BaseRotatingHandler or TimedRotatingFileHandler is horrible
I want to keep up logs for 30 days or 30 copies
i am trying to understand how to do it with TimedRotatingFileHandler
why there is so out of the box code for that?
each rotated log need to have date.
each log will be rotated when running the script every time

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add and remove pagination .active class when I click in next and prev arrows I add this pagination.js script when you change page 1,2,3,4,5
$(document).ready(function(){
  var $listItems = $('.pagination li');

  $listItems.click(function(){
    $listItems.removeClass('active');
    $(this).addClass('active');

  });
});

I want add a function to prev and next arrow of carrousel, when your click on the arrow, the function remove class .active of the previous page and add the .class active in the next page.
Arrow controls code:

My english is not very good, you can see this screenshot:

Thanks a lot.
EDIT:

$(document).ready(function(){
  var $listItems = $('.pagination li');
  var $arrowItems = $('.arrowPosition2 a');

  $listItems.click(function(){
    $listItems.removeClass('active');
    $(this).addClass('active');
    var activeLink=$(this);
  });

     $('#arrowPrev').on('click',function(){
    var $activeLi=$('.pagination').find("li.active");
    $activeLi.removeClass('active');

    if($activeLi.prev()!=null && $activeLi.prev()!=undefined ){
    $activeLi.prev().addClass('active');
    }else{
    $('.pagination').find("li:last").addClass("active")
    }
    });

     $('#arrowNext').on('click',function(){
    var $activeLi=$('.pagination').find("li.active");
    $activeLi.removeClass('active');

    if($activeLi.next()!=null && $activeLi.next()!=undefined ){
    $activeLi.next().addClass('active');
    }else{
    $('.pagination').find("li:last").addClass("active")
    }
    });

});

A: Plz change if condition
if($activeLi.next().length>0 ){
$activeLi.next().addClass('active');
}else{
$('.pagination').find("li:first").addClass("active")
}

A: i think this will help you
var activeLink;

$(document).ready(function(){
  var $listItems = $('.pagination li');

  $listItems.click(function(){
  $listItems.removeClass('active');
  $(this).addClass('active');
  var activeLink=$(this);////  store in variable and do work on pev next btn
  });
});

A: $('#Arrow').on('click',function(){
var $activeLi=$('.pagination').find("li.active");
$activeLi.removeClass('active');

if($activeLi.prev()!=null && $activeLi.prev()!=undefined ){
$activeLi.prev()..addClass('active');
}else{
$('.pagination').find("li:last").addClass("active")
}
});

A: $('#NEXT_ARROW_ID').on('click',function(){
var $activeLi=$('.pagination').find("li.active");
$activeLi.removeClass('active');

if($activeLi.next()!=null && $activeLi.next()!=undefined ){
$activeLi.next().addClass('active');
}else{
$('.pagination').find("li:first").addClass("active")
}
});

A: this is your : pagination.js
$(document).ready(function(){
  var $listItems = $('.pagination li');
var $arrowItems = $('.arrowPosition2 a');

 $listItems.click(function(){
$listItems.removeClass('active');
$(this).addClass('active');
var activeLink=$(this);
});

 $('#arrowPrev').on('click',function(){
var $activeLi=$('.pagination').find("li.active");
$activeLi.removeClass('active');

if($activeLi.prev().length>0 ){
$activeLi.prev().addClass('active');
}else{
$('.pagination').find("li:last").addClass("active")
}
});

$('#arrowNext').on('click',function(){
var $activeLi=$('.pagination').find("li.active");
$activeLi.removeClass('active');

if($activeLi.next().length>0){
$activeLi.next().addClass('active');
 }else{
$('.pagination').find("li:first").addClass("active")
}
});

});


text:
Q: Slider in Modal does not show until I resize the screen I have a slider inside of a modal. However, on modal show, the slider does not show on the screen. When I resize the window manually, it would appear.
I've attempted to do some research regarding this issue and individuals have stated that the problem is because the modal is hidden at the start and there are issues with the size calculations.
I have tried to do a manual resize of the screen when the modal is opened but it does not work.

There are no error messages but its just a visual glitch.
Edit: This is the code for my modal

Title

Subtitle

Description 1

Description 2

Date: July 13 - August 11

Category: Events

Partners: THD

<button class="btn btn-primary" data-dismiss="modal" type="button">

              Close Project</button>

A: Public album gallery decorator using Google closure, and this event is fired only if the screen is really resized. Look at the source code of ViewportSizeMonitor:
if (!goog.math.Size.equals(size, this.size_)) {... at line ~160.
You will need block automatic decorator, by changing the name of class, add an element ID and decorate the widget manually with the following code:
var widget = new GalleryPlayerWidget();
widget.decorate(document.getElementById('widget1'));
Check the last update information about widgets and demo:
https://www.publicalbum.org/blog/carousel-slideshow-gallery-widget-july-update#tiny-widget-api.


text:
Q: Excel - calculating durations of time data I'd like to find the duration of each transaction.
      A        B        C        D       E    F

2015-01-02  08:05:34  DEBUG:  operation  C1  begin
2015-01-02  08:06:35  DEBUG:  operation  C1  end
2015-01-02  08:01:35  DEBUG:  operation  C2  begin
2015-01-02  08:08:36  DEBUG:  operation  C2  end
2015-01-02  08:09:36  DEBUG:  operation  C3  begin
2015-01-02  08:10:36  DEBUG:  operation  C3  end

assume my raw data is in columns A, B, C, D, E and F, with headings in row 1, and data starting in row 2 I want to produce a result set as follows:
Operation Title, Duration
operation C1 , 00:01:01
operation C2, 00:07:01
operation C3, 00:01:00

After I Add a new column, G , titled Duration with a formula that like this :
=IFERROR(IF(LEFT(F1)="B",INDEX(B2:B6,MATCH(F1,F2:F6,0))-B1,""),"")

But I have an error invalid function.
thank you in advance.

A: Here is an easy alternative.
In G2 enter:
=IF(MOD(ROW(),2)=0,B2-B1,"")

and format G2 as h:mm:ss.  Then copy G2 downwards:


text:
Q: Basic sql query fails on MySQL 8 Have fresh install of MySQL 8.0.
Trying to understand why the following fails (Error Code 1064: You have an error in your SQL syntax):
select name from table_A;

But this one works:
select a.name from table_A a;

Any ideas how to fix that?

A: According to the docs name is a reserved word. Try putting back ticks around it.
select `name` from table_A;

A: I stumbled upon similar error case (due to identifier function which became reserved in MySQL 8.x) and the solution is adding backticks, as mentioned above [1] (sorry I can't put comments yet to the appropriate answer).
[1] https://stackoverflow.com/a/50391599/10765325


text:
Q: Ordenar por número com DataTables Estou com um problema com o plugin DataTables na ordem de números. Tenho uma lista de números:
1
2
3
4
...
10
11
12

O Problema acontece por causa dos digitos. Ele ordena tipo
1
10
11
12
2
3
4
...

A ordem correta seria do 1 ao 12, mas por causa que não tem o 0 na frente dos números com 1 dígito ele ordena errado. Tem alguma forma de arrumar isso nesse plugin ?
Script
var table = $('#sample_1');

        /* Table tools samples: https://www.datatables.net/release-datatables/extras/TableTools/ */

        /* Set tabletools buttons and button container */

        $.extend(true, $.fn.DataTable.TableTools.classes, {
            "container": "btn-group tabletools-dropdown-on-portlet",
            "buttons": {
                "normal": "btn btn-sm default",
                "disabled": "btn btn-sm default disabled"
            },
            "collection": {
                "container": "DTTT_dropdown dropdown-menu tabletools-dropdown-menu"
            }
        });

        var oTable = table.dataTable({

            // Internationalisation. For more info refer to http://datatables.net/manual/i18n
            "language": {
                "aria": {
                    "sortAscending": ": activate to sort column ascending",
                    "sortDescending": ": activate to sort column descending"
                },
                "emptyTable": "Nenhum registro encontrado",
                "info": "Mostrando _START_ de _END_ de um total de _TOTAL_ registros",
                "infoEmpty": "Nenhum registro encontrado",
                "infoFiltered": "Nenhum registro encontrado (pesquisado em _MAX_ registros)",
                "lengthMenu": "Mostrar _MENU_ registros",
                "search": "Pesquisar:",
                "zeroRecords": "Nenhum registro encontrado com os termos digitados"
            },

            "order": [
                [0, 'desc']
            ],

            "lengthMenu": [
                [5, 15, 20, -1],
                [5, 15, 20, "Todos"] // change per page values here
            ],

            // set the initial value
            "pageLength": 10,

            "dom": "<'row' <'col-md-12'T>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable

            // Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout
            // setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js).
            // So when dropdowns used the scrollable div should be removed.
            //"dom": "<'row' <'col-md-12'T>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",

            "tableTools": {
                "sSwfPath": "../../assets/global/plugins/datatables/extensions/TableTools/swf/copy_csv_xls_pdf.swf",
                "aButtons": [{
                    "sExtends": "print",
                    "sButtonText": "Imprimir",
                    "sInfo": 'Pressione "CTR+P" para imprimir ou "ESC" para sair',
                    "sMessage": "Gerado por DataTables"
                }]
            }
        });

        var tableWrapper = $('#sample_1_wrapper'); // datatable creates the table wrapper by adding with id {your_table_jd}_wrapper

        tableWrapper.find('.dataTables_length select').select2(); // initialize select2 dropdown

A: Tente adicionar isso ao seu dataTable
aoColumns: [{
    sSortDataType: 'dom-text',
    sType: 'numeric'
},
null]

Mas antes dele coloque isto:
$.fn.dataTableExt.afnSortData['dom-text'] = function (oSettings, iColumn) {
        var aData = [];
        oSettings.oApi._fnGetTrNodes(oSettings).forEach(function (nRow) {
        var oElem = $('td:eq(' + iColumn + ') input', nRow);
        aData.push(oElem.val());
     });
    return aData;
};

Não trabalho muito com dataTables, mas já tive um problema parecido com o seu e isso resolveu.


text:
Q: Year missing from post dates First, I love SO.
But, how can someone know how old a question is if the year is missing from all the dates?  It seems important to know how old a question is.  Am I missing it somehow? Thanks.

A: SO hasn't been around for a year yet. When it has been, the year will be visible in the dates. (It's actually already there in the mouseover text.)
See also Add year to question and answer dates.

A: it is implemented but dormant in the code until dates are >= 360 days from the original dates.


text:
Q: Correct way to insert elements with angular directive using angular.element() What is the correct way to insert element into the DOM using angular.element() ?
app.directive('validationTest', function(){
            return {
                restrict: 'A',
                replace: false,
                link: function(scope, element, attrs){
                    scope.call = function(){
                        console.log('Someone clicked it');
                    };

                    var newElement = angular.element('').text('Yo Yo');
                    element.append(newElement);
                }
            };
        });

In this code, I am trying to add a span element within the element on which directive has been applied. I am able to add this span element as the child of the parent div on which append mehtod is called.
However, as you can see in the code, a ng-click also has been associated with this span. I know it is not useful from any point of view, it is just for demo purpose. So, normally, clicking on this span, a line should be printed in the console. However, it doesn't happen.
What am I missing here ? Have I used wrong approach for this append or there is some error in my code ?

A: If the HTML that you dynamically append to the DOM has directives, then you'll want to $compile and link it before appending it to the DOM:
 var newElement = angular.element('').text('Yo Yo');
 $compile(newElement)(scope);
 element.append(newElement);

An alternative approach that is less error prone is to move your DOM manipulation to the compile function.  By inserting the new element during the compile phase, the new HTML will be automatically linked during the linking phase (no manual compile /link required):
app.directive('myDirective', function() {
     return  {
         compile: function(element, attr) {
              var newElement = angular.element('').text('Yo Yo');
              element.append(newElement);
              return function(scope, element, attr) {
              }
         }
     }
});

A: You're missing angular compilation. The compilation traverses your DOM looking for directives and initializes them. Without calling compile, nothing will initialize your ngClick. Try this to use $compile:
app.directive('validationTest', ['$compile', function($compile){
        return {
            restrict: 'A',
            replace: false,
            link: function(scope, element, attrs){
                scope.call = function(){
                    console.log('Someone clicked it');
                };

                var newElement = angular.element('').text('Yo Yo');
                element.append(newElement);
                $compile(element)(scope);
            }
        };
    });

For further information: https://docs.angularjs.org/api/ng/service/$compile

A: It's better to use templateUrl or template.
View $compile docs.


text:
Q: Unique counting in SQL Server UPDATED:
I have data where QA team have records and QC team have records. Im trying to add how many attempts they do on each record they work on. This should count to the "Attempts" column and how how many times the RecordName for each team (QA/QC) was worked on.
This is what i have tried:
with counts as (
  select [GTNUM],[RecordName],[Type],[Status], COUNT(*) row_count
    from QATAT
    group by [GTNUM],[RecordName],[Type],[Status]
),
results as (
  select d.[RecordName],d.[Type], counts.row_count, ROW_NUMBER() over(partition by d.[RecordName] order by d.[RecordName] ) row_num
    from QATAT d
      inner join counts on counts.[RecordName] = d.[RecordName]
)
select [RecordName],[Type], row_count, max(row_num) AS Attempts
  from results
  group by [RecordName],[Type], row_count
  order by [RecordName];

This is how it should look:
+--------+------------+------+--------+----------+
| GTNUM  | RecordName | Type | Status | Attempts |
+--------+------------+------+--------+----------+
| 334455 | REC6456    | QA   | Fail   |        1 |
| 334455 | REC6456    | QC   | Fail   |        2 |
| 334455 | REC6456    | QC   | Pass   |        2 |
| 465456 | REC9872    | QA   | Pass   |        1 |
| 784158 | REC1111    | QC   | Fail   |        1 |
| 451248 | REC9634    | QC   | Fail   |        1 |
+--------+------------+------+--------+----------+

Nothing I am trying seems to work. Any help would be greatly appreciated.

A: It looks like a simple GROUP BY could solve your problem:
SELECT
    GTNUM
   ,RecordName
   ,Type
   ,Status
   ,COUNT(*) Attempts

FROM Tablename
GROUP BY
    GTNUM
   ,RecordName
   ,Type
   ,Status


text:
Q: How to use json values with React Chakra UI theme So I have been trying (without success) to use values stored in a json file to override the Chakra UI theme.
My data.json file looks like this
[
  {
    "radius": "1px",
    "color": "#5843F5",
    "font": "Arial"
  }
]

And my theme.js file looks like this
import { extendTheme } from "@chakra-ui/react"
import JsonData from 'data.json'

export const myNewTheme = extendTheme({
 JsonData.map(item => ({
  colors: {
   primary: item.color,
   secondary: "#FF6F91",
   highlight: "#00C9A7"
  },
 }))
});

The problems returned is as below
JS theme.js src (1)
 ',' expected. ts(1005) [Ln7, Col 11]

So within JsonData.map the "." is highlighted as an error.
Any idea what I'm doing wrong?
Thanks a lot for your help

A: It will depend on how you want to define and access your custom themes.
In case of having many themes stored, how would you want to select each theme?
If you want to keep an array in the json, you could add the id
[
  {themeId: '1111', color: 'xxx'},
  {themeId: '1112', color: 'xxx'},
...
]

However, I've seen more often the usage of objects for multiple themes like:
{
  darkTheme: {primaryColor:'', font:'',...},
  lightTheme: {primaryColor:'', font:'',...},
  ...
}

Then you can access each theme JsonData['darkTheme'] or JsonData['lightTheme']
Focusing on your code where you are only defining one theme, I can see in their docs
it expects an object, but your JSON is stored inside an array
you'd have two options:
get the element you one from the array, something like
const customTheme = JsonData[0];
extendTheme({
  colors: {
  secondary: "#FF6F91",
   highlight: "#00C9A7",
   primary: customTheme.color,
  }
})

or store the theme as an object in the .json file.
{
  "radius": "1px",
  "color": "#5843F5",
  "font": "Arial"
}

extra:
to make it completely dynamic, you can use a "spread operator" to overwrite all the values that match the same name inside the theme:
const customTheme = JsonData[0];
extendTheme({
 colors: {
   secondary: "#FF6F91",
   highlight: "#00C9A7",
   ...customTheme
  }
})


text:
Q: application.loadlevel not working I am having trouble using the Application.LoadLevel from inside an if statement
Here is the code:
using UnityEngine;
using System.Collections;

public class Ritch: MonoBehaviour {

public bool dragging = false;

void Update () {

    if (PreRitch.Deathritch == true)
    {

        transform.position = new Vector3(8f,6.89f,9f);

    }

    if (transform.position.x > 11.5 && dragging == false)
    {

        Application.LoadLevel(0);

    }

    else if (transform.position.x < 4.5 && dragging == false)
    {

        Application.LoadLevel(0);

    }

}

void OnMouseDown()
{

    dragging = true;

}

void OnMouseUp()
{

    dragging = false;

}
}

The program is not loading the required level and if I put a print statement inside of one of the if statements nothing is printed.

A: Try to change code to:
using UnityEngine;
using System.Collections;

public class Ritch: MonoBehaviour {

public bool dragging = false;

void Update () {

    if (PreRitch.Deathritch == true)
    {

        transform.position = new Vector3(8f,6.89f,9f);

    }

    //if (transform.position.x > 11.5 && dragging == false)
    if (transform.position.x > 11.5f && dragging == false)
    {
        //Application.LoadLevel(0);
        UnityEngine.SceneManagement.SceneManager.LoadScene(0);

    }
    //else if (transform.position.x < 4.5 && dragging == false)
    else if (transform.position.x < 4.5f && dragging == false)
    {
        //Application.LoadLevel(0);
        UnityEngine.SceneManagement.SceneManager.LoadScene(0);

    }

}

void OnMouseDown()
{

    dragging = true;

}

void OnMouseUp()
{

    dragging = false;

}
}

You can use floats instead of doubles by adding f or F char


text:
Q: I need help using cronjob I'm trying to write a cron job to run automatically a PHP file after 30 days. The PHP file has write permission 777.
Here is my code:
* * * */30 * php -f  /var/www/virtual/my_domain_name.com/htdocs/./file.php > /dev/null 2>&1

But this is not working, I got no errors.
When i try:
* * * * * php -f  /var/www/virtual/my_domain_name.com/htdocs/./file.php > /dev/null 2>&1

The script works, then it executes the file every second from.
Any ideas?

A: Putting */30 in the 4th field would cause the job to run only in the 30th month of the year, and every 30 months thereafter during the year -- i.e., never.
Putting */30 in the 3rd field (day of month) would cause it to run on the 30th day of each month (and on the 60th, 90th, ... day of the month if there were such a thing). And given the *s in the other fields, it would run once a minute on that day -- and never in February. I doubt that that's what you want.
If you want a job to run once a month, that's easy:
 0 0 12 * * php ...

This will run the job at midnight on the 12th day of each month. Adjust the first two fields to pick a different time and the third to pick a different day.
There is no syntax for running a job once every 30 days. If that's really what you want,  you can schedule the job to run once every day:
 0 0 * * * php ...

and then have the job itself determine whether the current day is a multiple of 30.


text:
Q: Firebug for ie7 Is there is any firebug for ie7. In firefox firebug reduces lot of my work while checking code. In a same way ie supports firebug.

A: It's not Firebug (but then, neither is Firebug Lite, really), but there's the free version of Visual Studio.Net, Visual Studio Express, which provides a full script debugger and DOM inspection tool that connects to IE7. Set breakpoints, walk through code, etc.

A: Firebug lite is Firebug for non Firefox browsers.
If you haven't already, you can also try IE developer toolbar.

A: You can use the IE Developer Toolbar in ie7


text:
Q: java.lang.NoSuchMethodError: No static method setOnApplyWindowInsetsListener My app is crashing when starting with this error:
 FATAL EXCEPTION: main
Process: com.shotguntheapp.android, PID: 32127
java.lang.NoSuchMethodError: No static method setOnApplyWindowInsetsListener(Landroid/view
at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImpl
at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImpl
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImpl
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:143)
at com.shotguntheapp.android.Activities.MainActivity.onCreate(MainActivity.java:45)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2446)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2576)
at android.app.ActivityThread.access$1000(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5539)

                                                                           at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

I've already done some research and found all bring me to the same answer: I have to upgrade all my dependencies. Unfortunately, my android dependencies are all in the latest version.
Here is my App Gradle script:
apply plugin: 'com.android.application'
//apply plugin: 'io.fabric'

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.1'
defaultConfig {
    applicationId "com.shotguntheapp.android"
    minSdkVersion 17
    targetSdkVersion 25
    versionCode 1
    versionName "6.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
productFlavors {
    staging {
        applicationId "com.shotguntheapp.android.staging"
        versionName "6.0-staging"
    }
    production {
        applicationId "com.shotguntheapp.android"
        versionName "6.0"
    }
}
}

//buildscript {
//    repositories {
//        jcenter()
//        mavenCentral()
//        maven { url 'https://maven.fabric.io/public' }
//    }
//    dependencies {
//        classpath 'com.android.tools.build:gradle:1.5.0'
//        // The Fabric Gradle plugin uses an open ended version to react
//        // quickly to Android tooling updates
//        classpath 'io.fabric.tools:gradle:1.+'
//    }
//}

repositories {
flatDir {
    dirs 'libs'
}
maven {
    url "https://jitpack.io"
}
mavenCentral()
maven { url 'https://maven.fabric.io/public' }
maven {
    url "http://maven.batch.com/release"
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile project('libs:paymentkit')
compile project('libs:materiallockview')
//    compile('com.crashlytics.sdk.android:crashlytics:2.6.5@aar') {
//        transitive = true;
//    }
compile 'com.android.support:appcompat-v7:25.0.1'
compile 'com.android.support:design:25.0.1'
compile 'com.android.support:support-v4:25.0.1'
compile 'com.android.support:support-annotations:25.0.1'
compile 'com.facebook.android:facebook-android-sdk:4.6.0'
compile 'com.daprlabs.aaron:swipedeck:2.0.6'
compile 'com.mcxiaoke.volley:library-aar:1.0.1'
compile 'com.facebook.rebound:rebound:0.3.8'
compile 'com.wefika:horizontal-picker:1.1.1'
compile 'com.mixpanel.android:mixpanel-android:4.6.4'
compile 'com.google.android.gms:play-services-auth:10.0.1'
compile 'com.google.android.gms:play-services-plus:10.0.1'
compile 'com.google.android.gms:play-services-maps:10.0.1'
compile 'com.google.android.gms:play-services-gcm:10.0.1'
compile 'com.google.firebase:firebase-core:10.0.1'
compile 'com.google.android.gms:play-services-location:10.0.1'
compile 'com.stripe:stripe-android:+'
compile 'com.orhanobut:dialogplus:1.11@aar'
compile 'com.facebook.fresco:fresco:0.14.1'
compile 'com.facebook.shimmer:shimmer:0.1.0@aar'
compile 'com.parse:parse-android:1.+'
compile 'com.google.code.gson:gson:2.4'
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'io.smooch:core:latest.release'
compile 'io.smooch:ui:latest.release'
compile 'jp.wasabeef:fresco-processors:2.0.0'
compile 'com.batch.android:batch-sdk:1.5.+'
compile 'io.branch.sdk.android:library:1.+'
compile 'io.card:android-sdk:5.3.0'
compile 'pl.droidsonroids.gif:android-gif-drawable:1.1.11'
compile 'cn.trinea.android.view.autoscrollviewpager:android-auto-scroll-view-pager:1.1.2'
compile 'com.google.code.gson:gson:2.4'
testCompile 'junit:junit:4.12'

}

apply plugin: 'com.google.gms.google-services'

Thank'you for your help!


text:
Q: Jquery ajax request failed I am trying to develop a web application and I have a little problem to send data to the server with Ajax
my goal is to do a double with ajax request
Except that the varible $ _GET['lang'] does not exist on the server side! (PHP)
here my code.js
Code:
jQuery.ajax ({
    type: "GET"
    url: URL,
    like: "json"
    success: function (response) {
        var jsonp = response;
        var obj =jQuery.parseJSON (jsonp).;
        jQuery.each (obj, function () {
            lang + = this ['value'] + ":" + this ['qualify'] split ('@') [4] split ('s') [1] + "\ n".. });
            alert (lang);
            jQuery.ajax({
                type:"GET"
                url:"SaveFileFromClient.php"
                data: "lang =" + lang,
                success: function (response) { }
            });
        }
});

A: I'm not sure:
jQuery.ajax ({
    type: "GET",
    url: URL,
    dataType : "json",
    success: function (data) {
        var l=data.length;
        for(i=0;i<l;i++){
            lang+=data[i]['value']+ ": "+ data[i]['qualify'].split('@')[4].split('s')[1]+"\n";
            alert (lang);
            jQuery.ajax({
                type:"GET",
                url:"SaveFileFromClient.php",
                data: {lang:lang},
                async : false,
                success: function (response) { }
            }
        }
});

Also pay attention to the max size of the string passed through GET


text:
Q: How can I change the labels of the x-axis of a seaborn violin plot without going back and changing the data? I have the following seaborn violin plot:
sns.violinplot( x=c1_census['Cluster Labels'], y=c1_census['Land Area (km2)'],palette=my_pal)
plt.show()

How can I change the labels of the x-axis without going back and changing the data.
For example:
Replacing
0 for A,
1 for B,
2 for C,
3 for D,
4 for E
Thanks in advance!

A: You can use ax.set_xticklabels:
ax = sns.violinplot( x=c1_census['Cluster Labels'], y=c1_census['Land Area (km2)'],palette=my_pal)
ax.set_xticklabels([*'ABCDE'])


text:
Q: Why strings does not compare references? I know it is special case but why == between strings returns if their value equals and not when their reference equals. Does it have something to do with overlloading operators?

A: Because strings are immutable and the runtime may choose to put any two strings with the same content together into the same reference. So reference-comparing strings doesn't really make any sense.

A: on a string, == compares by value
"Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references (7.9.7 String equality operators). This makes testing for string equality more intuitive."
In short, == on strings compares the strings by value, not by reference, because the C# specification says it should.

A: Yes. From .NET Reflector here is the equality operator overloading of String class:
public static bool operator ==(string a, string b)
{
    return Equals(a, b);
}

A: The equality operators (== and !=) are defined to compare the values of string objects, not references.
There was not any situation in which I had to compare the references but if you want to do so then you can use:
object.ReferenceEquals().

A: The == operator is overloaded in String to perform value equality instead of reference equality, indeed. The idea is to make strings more friendly to the programmer and to avoid errors that arise when using reference equality to compare them (not too uncommon in Java, especially for beginners).
So far I have never needed to compare strings by reference, to be honest. If you need to do it you can use object.ReferenceEquals().


text:
Q: Connect 30" Apple Cinema HD Display to 2018 Mac Mini I am trying to run an Apple Cinema HD Display (30") from a 2018 MacMini.
I have tried all kinds of HDMI- to DVI adaptors but so far no luck. I have also tried these connectors with a MacBook Pro with HDMI and although the computer recognises that there is a display attached (and gets the name of it etc) the display remains blank.
I've seen people doing this with USB-C, first converting to DisplayPort and then converting that to DualLink DVI... but I'm not sure if this same setup would work for HDMI, or what connectors are needed.
Maybe HDMI-DisplayPort then DisplayPort-DVI?

A: Re connecting a Mac mini 2018 to 30" Apple Cinema Display*:
* Apple Cinema Display 30" refers to TFT-LCD model (M9179LL/A) only! This does NOT work for the LED apple cinema displays.
You need the following:

*

*Power Adapter of the Apple Cinema Display

*The apple mini display port (mini DP) to Dual Link DVI adapter (sold second hand only, 30-150 USD) apple number MB571LL/A A1306
and

*USB-C to Mini Display Port adapter from LMP (https://lmp-adapter.com/?s=16138) (ca. 30 USD from new.)

This combination runs smoothly at 2560x1600


text:
Q: Introducing ENTITY into oXygen causes Xerces "Element type ... must be declared" error I have the following, very simple XML file (significantly cut back from the original for the purposes of this question):
    <?xml version="1.0"?>
    <!DOCTYPE root [
    <!ENTITY % entities SYSTEM "test.dtd">
    %entities;
    ]>

    <root>
    </root>

The file test.dtd exists but, again for the purposes of this question, is empty.
The trouble is that oXygen XML Editor throws the error:
E [Xerces] Element type "root" must be declared.

If I remove the %entities; line or the % symbol from the line above, no error is thrown because oXygen then is not actually parsing the entities file (so, obviously, when genuine entities are introduced the references to them fail). Unfortunately, the research I have done suggests that Xerces throws this error for a multitude of different reasons and I cannot narrow down what is wrong in this case.
Why is this error thrown when Entities are introduced, even when there are none there, and what can I do about it?
oXygen v10.3, if that matters (my company is only licensed for five-year old software :-( )

A:
The file test.dtd exists but, again for the purposes of this question, is empty.

Your simply get this error, because even if the file test.dtd is properly found, it does not contain anything, and in particular there is no declaration for the "root" element. Thus Xerces throws you the error:

E [Xerces] Element type "root" must be declared.

If you simply declare  <!DOCTYPE root SYSTEM "test.dtd"> (which is stricly equivalent to what you have done above), I bet you will obtain the same error.


text:
Q: Entity Framework - how to handle Nullable in entity I have an entity(EF) with property int? priority.
I want to work with the entity across my platform.
Dictionary<int, Task> tasks = new Dictionary<int,Task>();
tasks.Add(task.Priority, task);

in the second row, I want to get Priority out of task and fire it an int. but I get an error that int? is not int, which is true.
How to handle this situation
Thanks

A: You can use the Value Property witch gets the value of the current Nullable value.
But be aware to the HasValue Property so you can provide a default value in case its false.


text:
Q: Anime about half-human girls who fight monsters? I'm fairly sure this anime came out within the last 5 or 6 years. The version I saw was dubbed into English.
The premise is that the world has been overrun by nightmarish monsters - huge, dark, very Lovecraftian with tentacles and insect-like parts, and glowing red eyes. The main city, possibly used to be Tokyo or another major Japanese city, is protected by a ring of huge towers, the material of which repels the monsters. If a monster does manage to get past the towers - which is happening more and more often as the story starts - there are dedicated monster hunters to combat them.
The hunters are teams of two: one adult human and one half-human, a hybrid of human and the monsters. The hybrids are all females, and all are little girls (as the monster invasion only happened within the last ten years). The hybrids have superhuman strength and monster-related powers, but every time they use their powers it brings them closer and closer to a tipping point where their monster genes will take over, and they'll transform into full monsters. If I recall correctly, the hybrids have an animal "theme" - the main character relies on speed and so is rabbit themed, another relies on stealth and is mantis themed, and so on.
The main character, a young man, is keeping it a secret from his hybrid partner how close she is to transforming, to keep from upsetting her. He tries to give her as "normal" a life as possible for the time she has. Other hunters treat their hybrid partners more like tools, or dangerous beasts. Hybrids not controlled by human partners are barred from the city, and there is a small colony of them in the wasteland across a river, who are being tutored by an elderly man who is trying to raise them as humans.
The plot involves the towers being sabotaged, monster attacks becoming more frequent, and the various hunters forced to team up and form an army to defeat them, with side plots about how cruelly society treats the hybrids who defend them, because they fear the inevitable transformation.
The series was fairly short, 12 episodes I believe. No more than 24 at most.
I've tried looking for it but haven't been able to come up with any distinctive search terms.

A: This sounds like Black Bullet. This anime aired in 2014, and was a one-cours series, lasting 13 episodes. It takes place in a world devastated by the "Gastrea" entities, and the characters who fight the Gastrea are divided into pairs of a "Promoter", who leads their partner in their battles, and an "Initiator", who is a "Cursed Child". The Cursed Children are young women whose bodies were altered by the effects of the Gastrea before they were born. Since the series takes place about ten years after the Gastrea appeared, the Cursed Children are all around ten years old.
In Black Bullet, the "Tokyo Area" is isolated from the chaos outside by a ring of "Monoliths".

The Gastrea that the protagonists are fighting are quite Lovecraftian:


text:
Q: If I'm perpendicular to an object that is 1 mile long and traveling perpendicular to me If I know an objects real size and I get its apparent size by putting a ruler 1 foot from my eye and measuring it. If the object is perpendicular to my eye is that enough information to determine it's distance from me? What would the calculation be?

A: Let $m$ denote the $m$easured distance on the ruler, $l$ the $l$ength of the object, and $d$ the $d$istance from you and the object. Because of similar triangles:
$$\frac{m}{1}=\frac{l}{d}$$
Therefore:
$$d=\frac{l}{m}$$


text:
Q: Increase/Change Bootstrap3 column size? I've three col-md-4 in a row.

*

*Then I drop 2 columns with javascript

*Now 1 column left in that row.

*I would like to say this
column, because it is alone in the row that it should get more width
(or transform to a col-md-7).

Code:
.container
  .row
    .col-md-4#first 1. column
    .col-md-4#second 2. column
    .col-md-4#third 3. column

:javascript
  $("#first").remove();
  $("#third").remove();

My only idea is to copy the contents of the column, create a new column and insert the content there. Is there any smarter solution for that?

A: With help from Yang I found out that .removeClass and .addClass let the column grow in a dynamic behavoir.
$("#second").removeClass("col-md-4").addClass("col-md-7");


text:
Q: Increasing ubuntu partition space I have a laptop configured with dual boot (Ubuntu and win7). Partition in which Ubuntu in installed is running out of space(alloted only 15 GB space earlier).I want to use one of my empty partition for Ubuntu. As far as I know I think I have two option to do that to increase the Ubuntu partition size first is to merg that free partition using gparted into it, but that will take lots of time since that free partition is located to the left of Ubuntu partition (comes before on disk addressing space) so gparted will have to shift whole 15 GB of existing data in Ubuntu partition towards left. Other option is to export one of my root director like /usr(or other that consumes lots of space) to that partition.
So, I have following questions:

*

*Which option is safe, efficient and comfortable.

*If I were to export one of root dir(like /usr ) which one should I export and HOW. I think /usr should be the one since user programs are installed in it which constitute major portion of space.

*Any other better way of doing this??

A: You should move your /home directory to the other partition.  See How can I move my /home directory to another partition if it's already part of the / partition?.


text:
Q: Error: Cannot find module 'html' with Node.JS and Express I've been looking at responses on here for this question, but nothing has helped me.  Some solutions have given me even more errors, too.
What I am trying to do is route to different pages with Node.JS.  Having learnt a little bit on the MEAN stack, I decided to use Node, Express, and Angular (haven't gotten there yet).  If I try to to to any place that isn't the '/' route, I get an error saying 'Cannot find module 'html'.  Below is the code in question:
//dependencies
var express = require('express');
var path = require('path');
var engines = require('consolidate')

//variables
var RUN_PORT = 8080;
var VIDEO_IN_PORT = 45679;
var CONTROL_OUT = 45678;
var app = express();

app.use(express.static(path.join(__dirname, 'public')));

//index.html routing
app.get('/', function(req, res){
    res.render("index.html");
});

//robot_control.html routing
app.get('/robot_control', function(req, res){
    res.render("robot_control.html");
});

//error.html routing
app.get('/error', function(req, res){
    res.render("error.html");
});

//showing that the program is running on the RUN_PORT
app.listen(RUN_PORT, function(){
    console.log("Running on port " + RUN_PORT);
});

What am I not seeing here?  Everything seems to look fine.  All I have installed in my package.json is Express.  I am able to get to the index page just fine, but anything other than that causes that error.

A: The issue is caused by using res.render('SOMEFILE.html'), because you're not telling Express how to render files with a .html extension.
Since you're not using any templating (yet), you can use this:
// Somewhere at the top:
const path  = require('path');
const VIEWS = path.join(__dirname, 'views');
...

// In your route handlers:
res.sendFile('index.html', { root : VIEWS });

When you want to start using templating, look here: http://expressjs.com/en/guide/using-template-engines.html


text:
Q: Removing null values when concatenating columns in SQLAlchemy I am trying to implement a function to concatenate columns based on inputs provided by the user.
I have implemented it using a SQLAlchemy update statement:
update_statement = table.update().values({
        new_column_name: assignable
    })

where assignable is:
assignable = column_1 + column_2

where column_1 and column_2 are instances of sqlalchemy.sql.column.
It works fine but if one of the rows in column is empty i.e. has a None value it returns None as the result of concatenation.
I understand that's logical but is there a way I can convert None to '' (empty string) using this implementation?

A: I think you can maybe use the coaslesce function
http://docs.sqlalchemy.org/en/latest/core/functions.html
class sqlalchemy.sql.functions.coalesce(*args, **kwargs)

You can specify default values for null result :)
Try googling coalesce for more results about this feature
So your "convert None to '' (empty string)" can be done like this
coalesce(column1, '') + coalesce(column2, '')


text:
Q: How do I show that a continuous partial derivate makes the function differentiable? Given a function $\mathcal f$: $\mathbb R^2$ $\to$ $\mathbb R$ that admits the partial derivates $\frac {\partial f}{\partial x} $ and $\frac {\partial f}{\partial y} $ in $\mathbb R^2$, how can I show that $\mathcal f$ is differentiable if at least ONE of these partial derivates is continuous?
Been banging my head for a while now and would appreciate some help.
Thanks!

A: Suppose that $\frac{\partial f}{\partial x}$ is continuous. We have:
\begin{equation}
  \begin{split}
    &f(a_1+h_1, a_2+h_2)-f(a_1, a_2) = f(a_1+h_1, a_2+h_2)-f(a_1, a_2+h_2)+f(a_1, a_2+h_2) -f(a_1, a_2) \\
   &= \int_0^{h_1}  \frac{\partial f}{\partial x}(a_1+t, a_2+h_2)\mathrm{d}t + h_2\frac{\partial f}{\partial y}(a_1, a_2)+o(h_2) \\
   & = \int_0^{h_1} \left( \frac{\partial f}{\partial x}(a_1+t, a_2+h_2) -
 \frac{\partial f}{\partial x}(a_1, a_2) \right) \mathrm{d}t + h_1\frac{\partial f}{\partial x}(a_1,a_2)  + h_2\frac{\partial f}{\partial y}(a_1, a_2)+o(h_2)
  \end{split}
\end{equation}
The continuity of $\frac{\partial f}{\partial x}$ implies its uniform continuity on $[a_1, a_1+h_1]\times[a_2,a_2+h_2]$. So, for small enough $(h_1, h_2)$, we have:
\begin{equation}
  \bigg\vert \frac{\partial f}{\partial x}(a_1+t, a_2+h_2) -
 \frac{\partial f}{\partial x}(a_1, a_2) \bigg\vert < \epsilon, \mbox{ for } t \in [0, h_1]
\end{equation}
Finally:
\begin{equation}
  f(a_1+h_1, a_2+h_2)-f(a_1, a_2) = h_1\frac{\partial f}{\partial x}(a_1,a_2)  + h_2\frac{\partial f}{\partial y}(a_1, a_2)+ o(h_1) +o(h_2)
\end{equation}
And we conclude that $f$ is differentiable in $(a_1,a_2)$.


text:
Q: Замаскировать text вводимый в textField! Хотелось бы замаскировать text в textField, оставив видимым последний символ (желательно, но не обязательно). Как, я думаю, уже все догадались, для ввода пароля! (^_^)

A: Это делается так:
texfield.secureTextEntry = true

Или же поставить галочку в IB в поле Secure


text:
Q: Is this a correct way of implementing an enumeration? I am writing the answer to another question.
I am not sure if my implementation of enumeration is OK. I'll describe it in a moment. Please review it, and tell me if I could have done something better.
The small prototype in question (codepen here) involves drawing chess board and chess pieces. There are 6 white and 6 black chess pieces. For each of them, I need to keep its name (like "White Bishop") and Unicode code (something like "\u2654"). So, I defined variable pieces as follows: (There is also piece NONE that proved to be useful for empty squares on the board)
var pieces = {
    NONE :          {name: "None",          code: " "},
    WHITE_KING :    {name: "White King",    code: "\u2654"},
    WHITE_QUEEN :   {name: "White Queen",   code: "\u2655"},
    WHITE_ROOK :    {name: "White Rook",    code: "\u2656"},
    WHITE_BISHOP :  {name: "White Bishop",  code: "\u2657"},
    WHITE_KNIGHT :  {name: "White Knight",  code: "\u2658"},
    WHITE_POWN :    {name: "White Pown",    code: "\u2659"},
    BLACK_KING :    {name: "Black King",    code: "\u265A"},
    BLACK_QUEEN :   {name: "Black Queen",   code: "\u265B"},
    BLACK_ROOK :    {name: "Black Rook",    code: "\u265C"},
    BLACK_BISHOP :  {name: "Black Bishop",  code: "\u265D"},
    BLACK_KNIGHT :  {name: "Black Knight",  code: "\u265E"},
    BLACK_POWN :    {name: "Black Pown",    code: "\u265F"},
};

I keep data on the distribution of all pieces on the board in an array called board, a this is the initialization of that array:
   var board =[];

    for(var i = 0; i < boardDimension*boardDimension; i++) {
        board.push({
            x: i % boardDimension,
            y: Math.floor(i / boardDimension),
            piece: pieces.NONE
        });
    };

    board[0].piece = pieces.BLACK_ROOK
    board[1].piece = pieces.BLACK_KNIGHT
    board[2].piece = pieces.BLACK_BISHOP
    board[3].piece = pieces.BLACK_QUEEN
    board[4].piece = pieces.BLACK_KING
    board[5].piece = pieces.BLACK_BISHOP
    board[6].piece = pieces.BLACK_KNIGHT
    board[7].piece = pieces.BLACK_ROOK

    board[8].piece = pieces.BLACK_POWN
    board[9].piece = pieces.BLACK_POWN
    board[10].piece = pieces.BLACK_POWN
    board[11].piece = pieces.BLACK_POWN
    board[12].piece = pieces.BLACK_POWN
    board[13].piece = pieces.BLACK_POWN
    board[14].piece = pieces.BLACK_POWN
    board[15].piece = pieces.BLACK_POWN

    board[6*8 + 0].piece = pieces.WHITE_POWN
    board[6*8 + 1].piece = pieces.WHITE_POWN
    board[6*8 + 2].piece = pieces.WHITE_POWN
    board[6*8 + 3].piece = pieces.WHITE_POWN
    board[6*8 + 4].piece = pieces.WHITE_POWN
    board[6*8 + 5].piece = pieces.WHITE_POWN
    board[6*8 + 6].piece = pieces.WHITE_POWN
    board[6*8 + 7].piece = pieces.WHITE_POWN

    board[7*8 + 0].piece = pieces.WHITE_ROOK
    board[7*8 + 1].piece = pieces.WHITE_KNIGHT
    board[7*8 + 2].piece = pieces.WHITE_BISHOP
    board[7*8 + 3].piece = pieces.WHITE_QUEEN
    board[7*8 + 4].piece = pieces.WHITE_KING
    board[7*8 + 5].piece = pieces.WHITE_BISHOP
    board[7*8 + 6].piece = pieces.WHITE_KNIGHT
    board[7*8 + 7].piece = pieces.WHITE_ROOK

And, deep down in the code, this data is used in the following way:
svg.append("text")
    .attr("x", function (d) {
        return d.x*fieldSize;
    })
    .attr("y", function (d) {
        return d.y*fieldSize;
    })
    .style("font-size", "40")
    .attr("text-anchor", "middle")
    .attr("dy", "35px")
    .attr("dx", "20px")
    .text(function (d) {
        return d.piece.code;
     })
    .append("title")
    .text(function(d) {
        return d.piece.name;
    });

Did I define and use the enumeration in the right way?

A: Well, to start there's no Enum in Javascript, but you can implement it by your own, and looking at the work you have done, I think that's correct and it's a good try.
But if we focus on the logic of Enum, we should know that an Enum must be constant and its elements values should never change so we have to look for a more suitable solution because in Javascript we can overwrite any object.
After a search I've made, I found a Javascript method that can provide the solution, wich is the Object.freeze().
So after defining your Enum you should freeze it, so it'll never change:
var pieces = {
 NONE :          {name: "None",          code: " "},
 WHITE_KING :    {name: "White King",    code: "\u2654"},
 WHITE_QUEEN :   {name: "White Queen",   code: "\u2655"},
 WHITE_ROOK :    {name: "White Rook",    code: "\u2656"},
 WHITE_BISHOP :  {name: "White Bishop",  code: "\u2657"},
 WHITE_KNIGHT :  {name: "White Knight",  code: "\u2658"},
 WHITE_POWN :    {name: "White Pown",    code: "\u2659"},
 BLACK_KING :    {name: "Black King",    code: "\u265A"},
 BLACK_QUEEN :   {name: "Black Queen",   code: "\u265B"},
 BLACK_ROOK :    {name: "Black Rook",    code: "\u265C"},
 BLACK_BISHOP :  {name: "Black Bishop",  code: "\u265D"},
 BLACK_KNIGHT :  {name: "Black Knight",  code: "\u265E"},
 BLACK_POWN :    {name: "Black Pown",    code: "\u265F"},
};
var frozenpieces=Object.freeze(pieces);

In that case the frozenpieces Object will remain always the same, so we can assume that it's an Enum.


text:
Q: "gzip: stdin: invalid compressed data--format violated" error when extracting a tgz archive I have to open a tar file. I used the following command line on my Unix shell:
tar xfvz raw-GWA-data.tgz

I found the following error message:
gzip: stdin: invalid compressed data--format violated
tar: Child returned status 1
tar: Error is not recoverable: exiting now

Then, I tried the following command lines:
tar -xvzf raw-GWA-data.tgz
tar --extract --file raw-GWA-data.tgz
tar xzf raw-GWA-data.tgz
tar -xf raw-GWA-data.tgz

and I found the same error without the possibility of opening my tar file.
What's wrong? There're alternative ways to open my tar file?

A: If you look at the hexdump (here taken with hexdump -C) of that file,

00000000  1f 8b 08 00 cd b6 e3 4c  00 03 d4 bd 5f 8c 23 5b  |.......L...._.#[|
00000010  7a 1f 46 71 82 80 62 0f  66 0c 3f 04 86 0c 18 0c  |z.Fq..b.f.?.....|
00000020  47 50 68 b2 45 ce f6 ac  e4 36 39 26 05 09 01 12  |GPh.E....69&....|
00000030  19 88 83 20 79 c8 93 b1  92 15 3b 52 bc 57 90 64  |... y.....;R.W.d|
00000040  c4 d1 0d 0a 3b 0c 3b 0f  34 39 e8 16 f4 12 43 0b  |....;.;.49....C.|
00000050  e8 32 45 61 55 7b 8a 5b  67 d2 9d ec e5 d6 e1 ad  |.2EaU{.[g.......|
00000060  33 98 09 ac 0e 79 43 02  f1 9b ae 73 a7 4d 1a bb  |3....yC....s.M..|
00000070  54 15 55 67 d2 8c ef 70  eb 70 ce c9 77 4e 91 dd  |T.Ug...p.p..wN..|
00000080  ec 9e 9e bf 77 f6 1a aa  dd 3b cd 66 93 f5 ab df  |....w....;.f....|
00000090  f7 ef 7c df f9 fb 8f be  f6 9b ff f8 6b bf 79 e7  |..|.........k.y.|
000000a0  b7 76 fe fe 2f fd c7 ff  55 fe 97 fe 93 5f cc ff  |.v../...U...._..|
000000b0  f2 7f fe 5f e6 ff eb ff  e2 3f cd ff 37 1f fc 93  |..._.....?..7...|
000000c0  af ff 83 5f fb ad df ce  7f fd 83 9f fd da ef fc  |..._............|
000000d0  ec af fe c3 9f fd ed af  ff e6 6f e7 7f e5 d7 fe  |..........o.....|
000000e0  41 ec 2d af db 70 fd fc  57 bf 0d 0a 3f ef 7c 65  |A.-..p..W...?.|e|
000000f0  e7 e7 d5 cf db 3b 3b 5f  fd 0d 0a fc fc f9 af dc  |.....;;_........|

You'll notice that all the 0x0a bytes (which if interpreted as a character in ASCII would be the newline aka LF / linefeed / \n / ^J character) are preceded by the 0x0d byte (corresponds to carriage return aka CR / ^M / \r).
This kind of corruption can happen when a file is transferred from a Unix machine to a Microsoft machine over FTP without setting the mode to binary, then the line endings are converted from LF to CRLF on the fly.
Here, you could reverse that corruption by converting all the CRLFs back to LF with perl -pe 's/\r\n\z/\n/' for instance:
$ bsdtar tf Downloads/41596_2010_BFnprot2010116_MOESM396_ESM.zip
raw-GWA-data.tgz
$ bsdtar xOf Downloads/41596_2010_BFnprot2010116_MOESM396_ESM.zip | perl -pe 's/\r\n\z/\n/' | bsdtar tvvf -
-rw-r--r--  0 ca3    team152 103669932 Mar  9  2010 hapmap3r2_CEU.CHB.JPT.YRI.founders.no-at-cg-snps.bed
-rw-r--r--  0 ca3    team152  29166116 Mar  9  2010 hapmap3r2_CEU.CHB.JPT.YRI.founders.no-at-cg-snps.bim
-rw-r--r--  0 ca3    team152      8813 Mar  9  2010 hapmap3r2_CEU.CHB.JPT.YRI.founders.no-at-cg-snps.fam
-rw-r--r--  0 ca3    team152  10664954 Mar  8  2010 hapmap3r2_CEU.CHB.JPT.YRI.no-at-cg-snps.txt
-rw-r--r--  0 ca3    team152       417 Jan  7  2010 high-LD-regions.txt
-rw-r--r--  0 ca3    team152       718 Feb 16  2010 imiss-vs-het.Rscript
-rw-r--r--  0 ca3    team152         9 Mar  9  2010 pca-populations.txt
-rw-r--r--  0 ca3    team152       283 Mar  3  2010 plot-IBD.Rscript
-rw-r--r--  0 ca3    team152       776 Jun  4  2010 plot-pca-results.Rscript
-rwxr-xr-x  0 ca3    team152  11747611 Jan  6  2010 raw-GWA-data.map
-rw-r--r--  0 ca3    team152 2540057786 Jan 14  2010 raw-GWA-data.ped
-rw-r--r--  0 ca3    team152       1217 Mar  8  2010 run-IBD-QC.pl
-rw-r--r--  0 ca3    team152        327 Mar 11  2010 run-diffmiss-qc.pl
-rw-r--r--  0 ca3    team152     511429 Jan  7  2010 raw-GWA-data.prune.in
Archive Format: GNU tar format,  Compression: gzip


text:
Q: YouTube, onPlayerReady, use for loop to get the Video ID in the array that matches the click arrow position and play I have the following fiddle: http://jsfiddle.net/inkedraskal/cyhyjht5/3/
In the fiddle you'll see that you can play and pause individual videos by clicking on the them (play one, if you click on another it will stop that current video and play what you clicked on).
What i can't figure out is how to get the custom play button to work.  I have following for loop in the fiddle, but I'm guessing on click its not matching up the placement in the array.  If i'm clicking the 3rd "play" span, it should be playing the 3rd video:
function onPlayerReady(event) {
  for (var i = 0; i < players.length; i++) {
    // if (players[i].getVideoUrl() != temp) players[i].stopVideo();

    for (var q = 0; q < ytPlayButtons.length; q++) {
      playButton = document.getElementById(ytPlayButtons[q]);
      playButton.addEventListener("click", function() {
        console.log(playButton);
        players[i].playVideo();
      });
    }
  }
}

A: Hi i have edited you fiddle and remake the onPlayerReady() function:
fiddle
there the new code:
var videoCount = 1;
function onPlayerReady(event) {
  $("#play-"+videoCount).on("click", function() {
    console.log("play-"+videoCount);
    event.target.playVideo();
  });
  videoCount++;
}

this is the easy way to do.
you should take the id of the video and than link it to the button in some way.
The problem with your initial code is that event.target contains a single video and the function loop all the video in page, so you don't need to write more cycle inside.
from youtube api you can use even this function to works with videos:
function onYouTubePlayerReady(playerId) {
  ytplayer = document.getElementById("myytplayer");
}

than ytplayer will have the same property of event.target and you have the videoID for free to use


text:
Q: Checkbox marcada/desmarcada ao receber 0/-1 do servidor Eu tenho uma checkbox dentro de uma modal que passa para o servidor ao clicar em um botão o valor 0 se ela não estiver marcada ou o valor -1 se estiver marcada. Agora estou tentando fazer o processo inverso, se estiver gravado 0 quando a pagina carregar a checkbox deve estar desmarcada, se estiver gravado -1 ela deve estar marcada mas não estou conseguindo ter esse retorno, alguem pode me dar uma luz? Estou aprendendo javascript.
Um exemplo do JSON que é enviado para o servidor:
{
Cdgrupo: 2,
Grupos: "grupo 2",
Dtalter: "2019-05-28T14:49:03.000Z",
Inativo: -1
},
{
Cdgrupo: 3,
Grupos: "grupo 3",
Dtalter: "2019-05-28T13:58:04.000Z",
Inativo: 0
},

Essa é a checkbox:
<input type="checkbox"  class="check" id="checkfor" style="position:absolute; left:330px; top:170px;" ></input>

E esse é o javascript que eu tentei usar para fazer o retorno:
$('#checkfor').ready(function() {
    if ($(this).attr('value', '-1')){
                 $(this).prop('checked', true);
             }
             else
              if ($(this).attr('value', '0')){
                 $(this).prop('checked', false);
             }
});

O que eu fiz de errado?
Segue um modelo de como estou fazendo uma requisição em ajax para get:
//Get de grupo
    $.ajax({
        url: "http://localhost:8081/datasnap/rest/TCadastros/GetListaGrupos//100/" + pag,
        dataType: 'json',
        type: 'get',
        cache:false,
        success: function(data){

A: Ao meu ver você está utilizando o evento errado... utilizando o ready do Javascript você vai executar a função no momento em que o HTML for montado na tela. O problema é que nesse momento você ainda não possui os dados da sua requisição. O momento de atualizar esse checkbox seria no success da função AJAX.
Ficaria da seguinte forma:
$.ajax({
    url: "http://localhost:8081/datasnap/rest/TCadastros/GetListaGrupos//100/" + pag,
    dataType: 'json',
    type: 'get',
    cache:false,
    success: function(data) {
        var element = $('#checkfor');
        element.val(data.Inativo); // Aqui você configura o valor

        // Com o valor já atribuído, você faz as modificações
        if (element.val() == -1) {
            element.prop('checked', true);
        }
        else if (element.val() == 0) {
            element.prop('checked', false);
        }
    }
});

Segue abaixo um exemplo. No seu caso, você poderia chamar a função changeElement no success do AJAX.

// Begin mock
var data = {
    Cdgrupo: 2,
    Grupos: "grupo 2",
    Dtalter: "2019-05-28T14:49:03.000Z",
    Inativo: -1
};

changeElement(data);
// End mock

function changeElement(data) {
  var element = $('#checkfor');
  element.val(data.Inativo); // Aqui você configura o valor

  // Com o valor já atribuído, você faz as modificações
  if (element.val() == -1) {
      element.prop('checked', true);
  }
  else if (element.val() == 0) {
      element.prop('checked', false);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox"  class="check" id="checkfor" style="position:absolute; left:330px; top:170px;" ></input>


text:
Q: A set of points and vector field I have a set of points which display the velocity vectors on some coordinates of space. I want to have the vector field plot which visualize my datasets. Can you tell me how can I do it in MATLAB?

A: Assuming it's 2 dimensional measurements, you can start by plotting a dot at each coordinate you measured, with "scatter(x,y)". As we'll see soon, you won't be using your first and last measurement, so it should be:
scatter(x(2:end-1), y(2:end-1))

Next, you'll need the direction of each vector. If your measruements frequency is high enough, numerical derivative should give you the right results. "diff(vec)" will return a vector of the differences between adjacent points. so you can get right side derivative of each point by:
dy = diff(y)
dx = diff(x)
% to be able to differentiate even when dx=0, will replace 0 with a very small number
for i=(dx == 0)
    dx(i) = eps
der = dy/dx

However, you'll probably need the "average" derivative, which you can obtain by:
avg_der = (der(1:end-1) + der(2:end)) / 2

now, you can draw a line at each point you've drawn, with dx=dx/normalization_size, dy=der * dx / normalization_size. Lines can be plotted.
for i=1:length(avg_der)
    line([x(i+1) (x(i+1) + mean(dx(i:i+1))/NORMALIZATION)], [y(i+1) (y(i+1) + avg_der(i) * mean(dx(i:i+1))/NORMALIZATION)])


text:
Q: Flagging answers as 'not an answer'...what happens if the answer is then improved? Apologies if this has already been asked, I couldn't find anything using the search.
If I was to flag an answer as 'not an answer' because (obviously) it did not answer the question, and the answer was then improved and became credible, what happens in the flag review process? Would my flag weight be decreased because it would appear I've marked a perfectly reasonable answer as 'not an answer'?

A: Mods know that this sort of thing happens, and they do tend to look at flags in context. There have been proposals to make them automatically see flagged posts as they were when flagged, but they haven't been implemented. There have been a handful of mistakes, but the only damage is a few flag weight points, and those aren't hard to regain.


text:
Q: Pointer's elements saved as gibberish I have written code that attempts to solve the Missionary and Cannibal's problem and have implemented Node to save information in Node::arr and Node::parent. These, when returned by the function bfs, will give the states in the shortest path.
When bfs returns, it has the right number of parents. However, when I inspected Node last in the Visual Studio debugger, I noticed that its parents.arr contain garbage i.e. arr[0]=-858993460. but Node last has the correct arr (the final state of the problem {0,0,1,3,3,0}). How is this information lost?
node.h
#pragma once
#include <array>
class Node {
public:
    std::array<int, 6> arr;
    Node *parent;
    Node(std::array<int, 6> arr, Node *parent = NULL);
    Node();
};

node.cpp
#include "Node.h"

Node::Node(std::array<int, 6> arr, Node *parent) : arr(arr), parent(parent) {};
Node::Node(): parent(NULL) {};

main.cpp
void applyMoves(queue<Node> &q, Node current_node, array<int, 3> moves) {
  array<int, 6> arr = current_node.arr;
    array<int, 3> left, right;
    // apply valid moves to arr
    // copy the arr to left and right and check if the move applied are valid
    // if valid and no duplicates in the queue do proceed to the next lines below
    Node n = Node(arr, &current_node);
    q.push(n);

}

Node bfs(queue<Node> &q, array<array<int, 3>, 5> moves) {
    while (!q.empty()) {
        Node current = q.front();
        q.pop();

        if (achievedGoal(current.arr) == 1) {
            return current;
        }
        for (const auto& move : moves) {
            applyMoves(q, current, move);
        }
    }
    Node n;
    return n;
}

int main() {
    array<int, 6> init_state{ 3,3,1,0,0,0 };
    array<array<int, 3>, 5> moves{ { {1,0,1}, {0,1,1}, {1,1,1}, {2,0,1}, {0,2,1} } };
    Node n = Node(init_state);
    queue<Node> q;
    q.push(n);
    Node last = bfs(q, moves);
}

A: I believe the issue is in
void applyMoves(queue<Node> &q, Node current_node, array<int, 3> moves) {
  array<int, 6> arr = current_node.arr;
    array<int, 3> left, right;
    // apply valid moves to arr
    // copy the arr to left and right and check if the move applied are valid
    // if valid and no duplicates in the queue do line 31 and 32
    Node n = Node(arr, &current_node);
    q.push(n);

}

Here current_node is a copy and you are storing the address of it.  When the function ends that copy is destroyed and now you have a dangling pointer.  You should be able to fix it by taking current_node by reference.
Edit:
You also have this same behavior in
Node bfs(queue<Node> &q, array<array<int, 3>, 5> moves) {
    while (!q.empty()) {
        Node current = q.front();
        q.pop();

        if (achievedGoal(current.arr) == 1) {
            return current;
        }
        for (const auto& move : moves) {
            applyMoves(q, current, move);
        }
    }
    Node n;
    return n;
}

Here you create current which is a local automatic object and you copy the front of the queue into it and then you get pop() the front out of the queue.  So when you use this node for the parent everything is fine until you move to the next iteration of the while loop.  Once you do that current is destroyed which means everything that points to it is now dangling.  Then the loop starts back up and a new current is created.  If this object is created in the sample place which I think it is then all of the nodes you have made have their parent node now pointing to this new node.
They way you are currently doing this is not going to work.  I am not quite sure how you should change it to get the correct behavior.

A: Since I can't (yet) comment on posts made by others, I will build upon the previous answer with my own answer. Yes, the following function:
void applyMoves(queue<Node> &q, Node current_node, array<int, 3> moves) {
  array<int, 6> arr = current_node.arr;
    array<int, 3> left, right;
    // apply valid moves to arr
    // copy the arr to left and right and check if the move applied are valid
    // if valid and no duplicates in the queue do line 31 and 32
    Node n = Node(arr, &current_node);
    q.push(n);

}

Needs to take the current_node by reference, since, otherwise, you are storing a address to a local variable, which will be destroyed after the execution goes out of function scope.
But, not only that, but here:
    Node current = q.front();
    q.pop();

You are making a copy of the first element in the queue, and saving it to a local variable, and when you pass it into the function described above (even if it is done by reference), you are still running into the same problem, since you are storing the address of the local variable (local variable of different function, but still - the same problem). And, based on the logic posted, is not clear for me, what the correct solution would be, but at least you have "why?" answered.
Edit: Apparently the original poster beat me to an answer with his edit.


text:
Q: Get total of property when using pagedlist I have the following code defined below, what I am trying to do is get the total of the following properties (ItemsRequireingAttention, NumberOfUrgentItems).
Although Model.Count tells me how many view models I have in my view model, I want to be able to get the total count of the 2 aforementioned properties.
I've tried using Model.TotalCountFor and Model.Where but don't seem to be able to get them to work. My current code below, will only tell me the totals for the subset that is currently in view. Is this possible or am I going to have to look into using partials
PortalViewModel
public class PortalViewModel
{
    public Vehicle Vehicle { get; set; }
    public bool MotExpired { get; set; }
    public bool TaxExpired { get; set; }
    public bool MotWithin7Days { get; set; }
    public bool TaxWithin7Days { get; set; }
    public bool MotWithin30Days { get; set; }
    public bool TaxWithin30Days { get; set; }
    public bool MotNotRecorded { get; set; }
    public bool TaxNotRecorded { get; set; }
    public int NumberOfUrgentItems { get; set; }
    public int ItemsRequireingAttention { get; set; }

}

PortalController
public class PortalController : Controller
{
    public ActionResult Index(int? page)
    {
        var cookie = new HttpCookie("view", "admin");
        var portalViewModel = new List<PortalViewModel>();

        var vehicles = db.Vehicles.ToList();

        foreach (var vehicle in vehicles)
        {
            var vm = new PortalViewModel { Vehicle = vehicle };

            if (vehicle.MotDate == null)
            {
                vm.MotNotRecorded = true;
                vm.NumberOfUrgentItems++;
            }
            if (vehicle.TaxDate == null)
            {
                vm.TaxNotRecorded = true;
                vm.NumberOfUrgentItems++;
            }

            if (vehicle.MotDate <= DateTime.Now.AddYears(-1))
            {
                vm.MotExpired = true;
                vm.NumberOfUrgentItems++;
            }
            if (vehicle.TaxDate != null && DateTime.Now.Subtract((DateTime)vehicle.TaxDate).Days >= 7)
            {
                vm.TaxWithin7Days = true;
            }
            else if (vehicle.TaxDate != null && DateTime.Now.Subtract((DateTime)vehicle.TaxDate).Days >= 30)
            {
                vm.TaxWithin30Days = true;
            }
            portalViewModel.Add(vm);
        }
    }
}

View
@using Microsoft.Ajax.Utilities
@using PagedList
@using PagedList.Mvc;

@using WebApplication1.ViewModels
@model IPagedList<PortalViewModel>

@{
    ViewBag.Title = "Dashboard";
    var pagedList = (IPagedList)Model;
    var urgentItems = Model.Count(i => i.NumberOfUrgentItems >= 1); //(item => item.NumberOfUrgentItems >= 1);
    int flaggedItems = Model.Count(i => i.ItemsRequireingAttention >= 1);
    int vehicles = Model.Count();

}

Dashboard

    @if (urgentItems != 0)
    {

@urgentItems Items

Requiring immediate action

    }
    @if (flaggedItems != 0)
    {

@flaggedItems Items

Require attention

    }

@vehicles

Vehicles in fleet

                Current Fleet Details

                                    Click on the reference number to edit vehicle details

                                @Html.DisplayNameFor(m => m.First().Vehicle.RefNumber)
                                @Html.DisplayNameFor(m => m.First().Vehicle.Make)
                                @Html.DisplayNameFor(m => m.First().Vehicle.Model)
                                @Html.DisplayNameFor(m => m.First().Vehicle.Registration)
                                @Html.DisplayName("Dates")

                            @foreach (var item in Model)
                            {
                                <tr class='@if (item.MotNotRecorded || item.MotExpired || item.TaxNotRecorded || item.TaxExpired)
                                               {
                                                   @Html.Raw("danger")

                                               } else if (item.MotWithin30Days || item.MotWithin7Days || item.TaxWithin30Days || item.TaxWithin7Days)
                                               {
                                                   @Html.Raw("warning")
                                               }
                                               else
                                               {
                                                   @Html.Raw("success")
                                               }'>

                                        @if (!item.Vehicle.RefNumber.IsNullOrWhiteSpace() || !string.IsNullOrEmpty(item.Vehicle.RefNumber))
                                        {
                                            @Html.ActionLink(item.Vehicle.RefNumber, "Edit", "Portal", new { @ref = item.Vehicle.RefNumber }, null)
                                        }
                                        else
                                        {
                                            @item.Vehicle.RefNumber
                                        }

                                        @item.Vehicle.Make

                                        @item.Vehicle.Model

                                        @item.Vehicle.Registration

                                        @Html.LabelFor(modelItem => item.Vehicle.MotDate):
                                        @{
                                if (item.MotNotRecorded)
                                {

                                        @string.Format("Not yet recorded")

                                }
                                else
                                {

                                        @string.Format("{0:dd/MM/yyyy}", item.Vehicle.MotDate)

                                }
                                        }

                                        @Html.LabelFor(modelItem => item.Vehicle.TaxDate)
                                        @{
                                if (item.TaxNotRecorded)
                                {

                                        @string.Format("Not yet recorded")

                                }
                                else
                                {

                                        @string.Format("{0:dd/MM/yyyy}", item.Vehicle.TaxDate)

                                }
                                        }

                            }

                    Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount
                    @Html.PagedListPager(Model, page => Url.Action("Index", new { page }))

A: Your controller method is missing a return statement, but I'm assuming that you are returning your portalViewModel list.
I would recommend creating a ViewModel which has an IPagedList of PortalViewModel's and place the values you need in the containing ViewModel. Then you could use display templates in the view for each item.
However, you could also create two int variables and increment them in your foreach loop over the vehicles list, then put them into the ViewBag.
public ActionResult Index(int? page)
{
    var cookie = new HttpCookie("view", "admin");
    var portalViewModel = new List<PortalViewModel>();

    var vehicles = db.Vehicles.ToList();

    var totalNumberOfUrgentItems = 0; // first total
    var totalNumberOfItemsRequireingAttention = 0; // second total

    foreach (var vehicle in vehicles)
    {
        var vm = new PortalViewModel { Vehicle = vehicle };

        if (vehicle.MotDate == null)
        {
            vm.MotNotRecorded = true;
            vm.NumberOfUrgentItems++;
        }
        if (vehicle.TaxDate == null)
        {
            vm.TaxNotRecorded = true;
            vm.NumberOfUrgentItems++;
        }

        if (vehicle.MotDate <= DateTime.Now.AddYears(-1))
        {
            vm.MotExpired = true;
            vm.NumberOfUrgentItems++;
        }
        if (vehicle.TaxDate != null && DateTime.Now.Subtract((DateTime)vehicle.TaxDate).Days >= 7)
        {
            vm.TaxWithin7Days = true;
        }
        else if (vehicle.TaxDate != null && DateTime.Now.Subtract((DateTime)vehicle.TaxDate).Days >= 30)
        {
            vm.TaxWithin30Days = true;
        }

        totalNumberOfUrgentItems += vehicle.NumberOfUrgentItems;
        totalNumberOfItemsRequireingAttention += vehicle.ItemsRequireingAttention;

        portalViewModel.Add(vm);
    }

    ViewBag["TotalNumberOfUrgentItems"] = totalNumberOfUrgentItems;
    ViewBag["TotalNumberOfItemsRequireingAttention"] = totalNumberOfItemsRequireingAttention;
    // presumably your return statement is here
}


text:
Q: Add dynamic data in recyclerview in another dynamic recyclerview I am trying to add recyclerview to another recyclerview.
Like Sub Category Recyclerview in its Category RecyclerViews.
problem is that I am getting All categorie's sub category item list in last item of category list.
means
Cat1
cat2
catn(then below this list of subcat1, subcat2....so on)
but it should be like cat1 then in below subcat1 and so on...
here is MainActivity code from where I am calling the api and passing adapter to recyclerview
private void getCategory() {

    StringRequest stringRequest = new StringRequest(Request.Method.GET, CategoryUrl, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            try {
                JSONObject obj = new JSONObject(response);
                JSONArray jsonArray = obj.getJSONArray("DATA");
                Log.v("Cat Response", response.toString());

                for (int i = 0; i < jsonArray.length(); i++) {
                    DataModel Model = new DataModel();
                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    catId = jsonObject.getString("ID");
                    catTitle = jsonObject.getString("TITLE");

                    Model.setTITLE(catTitle);
                    Model.setID(catId);

                    catList.add(Model);
                    categoryAdaptor.getSubCategory(catId);

                }
                categoryAdaptor.notifyDataSetChanged();

            } catch (JSONException e) {
                System.out.print("Exception is :" + e.getMessage());

            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);

}

private void setCatAdaptor() {
    @SuppressLint("WrongConstant") LinearLayoutManager gridLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayout.VERTICAL, false);
    recyclerView1.setLayoutManager(gridLayoutManager); // set LayoutManager to RecyclerView
    //  call the constructor of CustomAdapter to send the reference and data to Adapter
    categoryAdaptor = new CategoryAdaptor(this, catList);
    recyclerView1.setAdapter(categoryAdaptor);

}

here is category adapter
public class CategoryAdaptor extends RecyclerView.Adapter<CategoryAdaptor.MyViewHlder> {
private Activity activity;
private ArrayList<DataModel> list;
private SubCategoryAdaptor subcategoryAdaptor;
private ArrayList<SubCatModel> subCatList = new ArrayList<>();
private String SubCategoryUrl = "http://philiabeauty.com/reader-choice/controller-api.php?action=get_subcategory_by_category&id=";
private String Token = "&access_token=Ym9va19kZXRhaWxz";
private String imgRoot = "http://philiabeauty.com/reader-choice/";
private String subCatId, subCatTitle, subCatImage;

public CategoryAdaptor(Activity activity, ArrayList<DataModel> list) {
    this.activity = activity;
    this.list = list;
}

@NonNull
@Override
public MyViewHlder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.category_list_layout, viewGroup, false);
    MyViewHlder my = new MyViewHlder(view);

    return my;
}

@Override
public void onBindViewHolder(@NonNull MyViewHlder myViewHlder, int i) {

    final DataModel model = list.get(i);

    myViewHlder.catText.setText(model.getTITLE());
    myViewHlder.catId.setText(model.getID());

    setSubCatAdaptor(myViewHlder);
}

@Override
public int getItemCount() {
    return list.size();
}

public void getSubCategory(String ID) {

    String SubCategoryUrlFinal = SubCategoryUrl + ID + Token;
    StringRequest stringRequest = new StringRequest(Request.Method.GET, SubCategoryUrlFinal, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            try {
                JSONObject obj = new JSONObject(response);
                JSONArray jsonArray = obj.getJSONArray("DATA");
                Log.v("SubCat Response", response.toString());

                for (int i = 0; i < 3; i++) {
                    SubCatModel Model = new SubCatModel();
                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    subCatId = jsonObject.getString("ID");
                    subCatTitle = jsonObject.getString("TITLE");
                    subCatImage = imgRoot + jsonObject.getString("IMG_SRC");
                    Model.setSubCatIMG(subCatImage);
                    Model.setSubCatTITLE(subCatTitle);
                    Model.setSubCatID(subCatId);

                    subCatList.add(Model);

                }
                subcategoryAdaptor.notifyDataSetChanged();

            } catch (JSONException e) {
                System.out.print("Exception is :" + e.getMessage());

            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(activity);
    requestQueue.add(stringRequest);

}

private void setSubCatAdaptor(MyViewHlder myView) {
    Log.v("test", "test" );
    @SuppressLint("WrongConstant") LinearLayoutManager gridLayoutManager = new LinearLayoutManager(activity, LinearLayout.HORIZONTAL, false);
    myView.recyclerviewSubCat.setLayoutManager(gridLayoutManager); // set LayoutManager to RecyclerView
    //  call the constructor of CustomAdapter to send the reference and data to Adapter
    subcategoryAdaptor = new SubCategoryAdaptor(activity, subCatList);
    myView.recyclerviewSubCat.setAdapter(subcategoryAdaptor);

}

class MyViewHlder extends RecyclerView.ViewHolder {

    private TextView catText, viewAllBtn, catId, tag;
    private RecyclerView recyclerviewSubCat;

    public MyViewHlder(@NonNull View itemView) {
        super(itemView);
        catText = itemView.findViewById(R.id.cat_name);
        viewAllBtn = itemView.findViewById(R.id.viewAllBtn);
        catId = itemView.findViewById(R.id.cat_id);
        recyclerviewSubCat = itemView.findViewById(R.id.recyclerviewSubCat);

    }
}

}
and here is the sub category adapter
public class SubCategoryAdaptor extends RecyclerView.Adapter<SubCategoryAdaptor.MyViewHlder> {
private Activity activity;
private ArrayList<SubCatModel> list;

public SubCategoryAdaptor(Activity activity, ArrayList<SubCatModel> list) {
    this.activity = activity;
    this.list = list;
}

@NonNull
@Override
public MyViewHlder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.subcat_list, viewGroup, false);
    MyViewHlder my = new MyViewHlder(view);

    return my;
}

@Override
public void onBindViewHolder(@NonNull MyViewHlder myViewHlder, int i) {

    final SubCatModel model = list.get(i);

    Log.v("data", model.getSubCatTITLE());

    myViewHlder.subCatTitle.setText(model.getSubCatTITLE());
    myViewHlder.subCatId.setText(model.getSubCatID());
    String img = model.getSubCatIMG();

    Picasso.get()
            .load(img)
            .placeholder(R.drawable.ic_book_black_24dp)
            .fit()
            .into(myViewHlder.subCatImage);
}

@Override
public int getItemCount() {
    return list.size();
}

class MyViewHlder extends RecyclerView.ViewHolder {

    private TextView subCatTitle, subCatId, subCatTag;
    private ImageView subCatImage;

    public MyViewHlder(@NonNull View itemView) {
        super(itemView);
        subCatTitle = itemView.findViewById(R.id.subcat_name);
        subCatId = itemView.findViewById(R.id.subcat_id);
        subCatTag = itemView.findViewById(R.id.subcat_tag);
        subCatImage = itemView.findViewById(R.id.subcat_image);

    }
}

}

A: Changed the sub category adapter declaration to viewHolder,
public class CategoryAdaptor extends RecyclerView.Adapter<CategoryAdaptor.MyViewHlder> {
    private Activity activity;
    private ArrayList<DataModel> list;

    private String SubCategoryUrl = "http://philiabeauty.com/reader-choice/controller-api.php?action=get_subcategory_by_category&id=";
    private String Token = "&access_token=Ym9va19kZXRhaWxz";
    private String imgRoot = "http://philiabeauty.com/reader-choice/";
    private String subCatId, subCatTitle, subCatImage;

    public CategoryAdaptor(Activity activity, ArrayList<DataModel> list) {
        this.activity = activity;
        this.list = list;
    }

    @NonNull
    @Override
    public MyViewHlder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.category_list_layout, viewGroup, false);
        MyViewHlder my = new MyViewHlder(view);

        return my;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHlder myViewHlder, int i) {

        final DataModel model = list.get(i);

        myViewHlder.catText.setText(model.getTITLE());
        myViewHlder.catId.setText(model.getID());

        getSubCategory(myViewHlder,model.getID());
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public void getSubCategory(MyViewHlder myViewHlder,String ID) {

        String SubCategoryUrlFinal = SubCategoryUrl + ID + Token;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, SubCategoryUrlFinal, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                try {
                    JSONObject obj = new JSONObject(response);
                    JSONArray jsonArray = obj.getJSONArray("DATA");
                    Log.v("SubCat Response", response.toString());

                    for (int i = 0; i < 3; i++) {
                        SubCatModel Model = new SubCatModel();
                        JSONObject jsonObject = jsonArray.getJSONObject(i);

                        subCatId = jsonObject.getString("ID");
                        subCatTitle = jsonObject.getString("TITLE");
                        subCatImage = imgRoot + jsonObject.getString("IMG_SRC");
                        Model.setSubCatIMG(subCatImage);
                        Model.setSubCatTITLE(subCatTitle);
                        Model.setSubCatID(subCatId);

                        myViewHlder.subCatList.add(Model);

                    }
                    myViewHlder.subcategoryAdaptor.notifyDataSetChanged();

                } catch (JSONException e) {
                    System.out.print("Exception is :" + e.getMessage());

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        RequestQueue requestQueue = Volley.newRequestQueue(activity);
        requestQueue.add(stringRequest);

    }

    class MyViewHlder extends RecyclerView.ViewHolder {

        private TextView catText, viewAllBtn, catId, tag;
        private RecyclerView recyclerviewSubCat;
        private SubCategoryAdaptor subcategoryAdaptor;
        private ArrayList<SubCatModel> subCatList = new ArrayList<>();

        public MyViewHlder(@NonNull View itemView) {
            super(itemView);
            catText = itemView.findViewById(R.id.cat_name);
            viewAllBtn = itemView.findViewById(R.id.viewAllBtn);
            catId = itemView.findViewById(R.id.cat_id);
            recyclerviewSubCat = itemView.findViewById(R.id.recyclerviewSubCat);
            LinearLayoutManager gridLayoutManager = new LinearLayoutManager(activity, LinearLayout.HORIZONTAL, false);
            recyclerviewSubCat.setLayoutManager(gridLayoutManager); // set LayoutManager to RecyclerView
            //  call the constructor of CustomAdapter to send the reference and data to Adapter
            subcategoryAdaptor = new SubCategoryAdaptor(activity, subCatList);
            recyclerviewSubCat.setAdapter(subcategoryAdaptor);

        }
    }
}