text:
Q: Flutter - Retrieve coordinates from user's current position I'm a newbie and I'm on a Flutter project where I'm trying to retrieve the latitude and longitude from user's current position.
I have this code:
class ProductHorizontalListItem extends StatelessWidget {
  const ProductHorizontalListItem({
    Key? key,
    required this.product,
    required this.coreTagKey,
    this.onTap,
  }) : super(key: key);

  final Product product;
  final Function? onTap;
  final String coreTagKey;

  @override
  Widget build(BuildContext context) {
    // print('***Tag*** $coreTagKey${PsConst.HERO_TAG__IMAGE}');
    final PsValueHolder valueHolder =
    Provider.of<PsValueHolder>(context, listen: false);

final double distanceInMeters = Geolocator.distanceBetween(
      0,
      0,
      double.parse(product.itemLocation!.lat.toString()),
      double.parse(product.itemLocation!.lng.toString()),
    );

    const double km = 1.60;
    final double distance = double.parse(valueHolder.mile.toString());
    final double total = distance * km;

    return InkWell(
        onTap: onTap as void Function()?,
        child: Container(
            margin: const EdgeInsets.only(
                left: PsDimens.space4, right: PsDimens.space4,
                bottom: PsDimens.space12),
            child: Text(
                '${distanceInMeters}' '${product.itemLocation!.name}',
                textAlign: TextAlign.start,
                style: Theme.of(context).textTheme.caption!.copyWith(
                    color: PsColors.textColor3
                )))

        );
  }
}

Instead of zero I need to pass the right latitude and longitude of the user.
I tried with Geolocator plugin but I had no luck probably due to my lack of knowledge.
Can some body help about how to implement correctly?
Thank you so much.
UPDATE
I tried to implement the Geolocator.getCurrentPosition and this is the code:
class ProductHorizontalListItem extends StatelessWidget {
  const ProductHorizontalListItem({
    Key? key,
    required this.product,
    required this.coreTagKey,
    this.onTap,
  }) : super(key: key);

  final Product product;
  final Function? onTap;
  final String coreTagKey;

  @override
  Widget build(BuildContext context) {
    // print('***Tag*** $coreTagKey${PsConst.HERO_TAG__IMAGE}');
    final PsValueHolder valueHolder =
    Provider.of<PsValueHolder>(context, listen: false);

Future<Position> _determinePosition() async {
      bool serviceEnabled;
      LocationPermission permission;

      // Test if location services are enabled.
      serviceEnabled = await Geolocator.isLocationServiceEnabled();
      if (!serviceEnabled) {
        // Location services are not enabled don't continue
        // accessing the position and request users of the
        // App to enable the location services.
        return Future.error('Location services are disabled.');
      }

      permission = await Geolocator.checkPermission();
      if (permission == LocationPermission.denied) {
        permission = await Geolocator.requestPermission();
        if (permission == LocationPermission.denied) {
          // Permissions are denied, next time you could try
          // requesting permissions again (this is also where
          // Android's shouldShowRequestPermissionRationale
          // returned true. According to Android guidelines
          // your App should show an explanatory UI now.
          return Future.error('Location permissions are denied');
        }
      }

      if (permission == LocationPermission.deniedForever) {
        // Permissions are denied forever, handle appropriately.
        return Future.error(
            'Location permissions are permanently denied, we cannot request permissions.');
      }

      // When we reach here, permissions are granted and we can
      // continue accessing the position of the device.
      return await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    }
    print(_determinePosition);

    return InkWell(
        onTap: onTap as void Function()?,
        child: Container(
            margin: const EdgeInsets.only(
                left: PsDimens.space4, right: PsDimens.space4,
                bottom: PsDimens.space12),
            child: Text(
                '${_determinePosition()}' '${product.itemLocation!.name}',
                textAlign: TextAlign.start,
                style: Theme.of(context).textTheme.caption!.copyWith(
                    color: PsColors.textColor3
                )))

        );
  }
}

But on print the console give me closure: () => future<position>


text:
Q: Synchronize value of column between two tables in different databases I am new to MYsql and I have two independent systems that use points(system1) and money(system2).I need to make it so that column money from bw_money will equal the same as pointshop_data. So that if a change in value will happen in either column it will still be equal to the same amount int he other column. Also this needs to happen at a really fast pace as it is a live item that needs updating on the fly.
(first database) pointshop_data = uniqueud, points
(second database)bw_money=  UID, steamid, money

Make money and points equal to each other.

A: You can use triggers to update one column when another changes. Triggers are procedures inside MySQL that are automatically executed on some event, such as, changing the value of a column.
You'll need an AFTER UPDATE trigger for both of the tables to propagate change in both directions.
(Obviously having the value in two places is a requirement, so I'm skipping the lecture on database normalization)

redpajama_set_name: RedPajamaStackExchange


text:
Q: MATLAB R2013b does not support Visual Studio 2013? I have recently installed VS 2013. I have a .cpp project which I want to compile into mex with MATLAB 2013b. As soon as I enter:
mex -setup

in MATLAB and then I select "y" for "Would you like mex to locate installed compilers?", I receive the message that: "No supported SDK or compiler was found on this computer."
How can I get around this problem?

A: Visual Studio 2013 is not supported by MATLAB R2013b.  See this link for more details: http://www.mathworks.com/support/compilers/R2013b/.  The latest compiler and environment that R2013b can support for Windows is Visual Studio 2012.  Your options are to either downgrade your version of Visual Studio to one that is compatible on that list I referred you to, or upgrade your version of MATLAB to at least R2014a or higher.


text:
Q: Magento 2 How to add class in product detail page? Theme - Luma
Location - Product detail page
I would like to add my custom class along with "column". Please review below screenshot for more information.

A: Its come from this location of file path vendor/magento/module-theme/view/base/page_layout/empty.xml where you are able to that class columns. its common for all layout page.
            <container name="columns" htmlTag="div" htmlClass="columns">
                <container name="main" label="Main Content Container" htmlTag="div" htmlClass="column main"/>
            </container>

For only product detail page , you need to add below code in your catalog_product_view.xml
<referenceContainer name="columns" htmlClass="columns add-your-class" />

htmlClass="columns add-your-class" used for adding class for div tab in Magento2.

A: As you want to add this class only on product view page, you have to add below code in your catalog_product_view.xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" >
    <body>
        <referenceContainer name="columns" htmlClass="columns customClass" />
    </body>
</page>

A: You could change it in following file.
\vendor\magento\module-theme\view\base\page_layout\empty.xml

However its not recommended, You could use the parent class like catalog-product-view .some-custom-class{}

A: If you add below syntax for css then it will apply for product page
.catalog-product-view .columns {

}


text:
Q: Multiprocessing a loop of a function that writes to an array in python I'm trying to implement multiprocessing for this loop. It fails to modify the array or and does not seem to order the jobs correctly (returns array before last function done).
import multiprocessing
import numpy

def func(i, array):
    array[i] = i**2
    print(i**2)

def main(n):
    array = numpy.zeros(n)

    if __name__ == '__main__':
        jobs = []
        for i in range(0, n):
            p = multiprocessing.Process(target=func, args=(i, array))
            jobs.append(p)
            p.start()

    return array

print(main(10))

A: Processes do not share memory, your program initially will create an array full of zeroes, then start 10 processes, which will call the func function on a copy of the array when it was first created, but never the original array.
It seems like what you're really trying to accomplish is this:
from multiprocessing import Process, Lock
from multiprocessing.sharedctypes import Array

def modify_array(index, sharedarray):
    sharedarray[index] = index ** 2
    print([x for x in sharedarray])

def main(n):
    lock = Lock()
    array = Array('i', 10, lock=lock)
    if __name__ == '__main__':
        for i in range(0, n):
            p = Process(target=modify_array, args=(i, array))
            p.start()
            p.join()
    return list(array)

main(10)

Output:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 4, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 4, 9, 0, 0, 0, 0, 0, 0]
[0, 1, 4, 9, 16, 0, 0, 0, 0, 0]
[0, 1, 4, 9, 16, 25, 0, 0, 0, 0]
[0, 1, 4, 9, 16, 25, 36, 0, 0, 0]
[0, 1, 4, 9, 16, 25, 36, 49, 0, 0]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 0]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

But the problem is, using multiprocessing is misguided. There's a lot of overhead in spawning an additional process, compared to a new thread, or even just staying single-threaded and utilizing an event loop to trigger actions.
An example of using concurrency, within a single-threaded, single process of Python may look like the following:
import numpy as np
from asyncio import get_event_loop, wait, ensure_future

def modify_array(index, array):
    array[index] = index ** 2
    print([x for x in array])

async def task(loop, function, index, array):
    await loop.run_in_executor(None, function, index, array)

def main(n):
    loop = get_event_loop()
    jobs = list()
    array = np.zeros(10)
    for i in range(0, n):
        jobs.append(
            ensure_future(
                task(loop, modify_array, i, array)
            )
        )
    loop.run_until_complete(wait(jobs))
    loop.close()

main(10)

This is a popular pattern these days, of using asyncio event loops to accomplish tasks in parallel. However, since you're using a library such as Numpy, I question how valuable this pattern may be to you.

A: I've not used multiprocessing before so I'm new to this too, but after doing a little research (mainly from these two posts), I think I've partially managed to address your problem with this code:
import multiprocessing
import numpy

def func(i, array, connection):
    squared_value = i ** 2
    array[i] = squared_value
    print(squared_value)

    connection.send(array)

def main(n):
    array = numpy.zeros(n)

    for i in range(0, n):
        recv_end, send_end = multiprocessing.Pipe(False)
        p = multiprocessing.Process(target=func, args=(i, array, send_end))
        p.start()
        p.join()
        array = recv_end.recv()

    return array

if __name__ == '__main__':
    print(main(10))

Output
0
1
4
9
16
25
36
49
64
81
[  0.   1.   4.   9.  16.  25.  36.  49.  64.  81.]

The reason why this approach modifies the array and yours doesn't is explained in this answer that I referenced in the comments:

The problem is that when the objects are passed to the worker processes, they are packed up with pickle, shipped to the other process, where they are unpacked and worked on. Your objects aren't so much passed to the other process, as cloned. You don't return the objects, so the cloned object are happily modified, and then thrown away.

There are a few things I should point out about my (partial) solution:

*

*This implementation runs a lot slower than just generating this list the regular way (via a single thread). This is most likely due to the added overhead of creating new processes and marshalling data between them.

*Due to the nature of your problem (having jobs that each modify an array), each job necessarily must take as input the output of the previous job. Because of this constraint, I don't believe it's possible to have the jobs run concurrently, which sort of defeats the point of multi-processing.
As for the latter of those two points, I did try a variation where func returns a function that accepts an array and returns a modified version of it. This would have allowed the jobs to run concurrently, but unfortunately it doesn't seem like functions can be pickled.


text:
Q: How to set optional field in where clause query? I have SQL query where I have to filter on bit field in some situations. If argument equals to an empty string then I should not include this bit field in my filter. Is there a goo way to do this with SQL Server 2008?
Here is example:
<cfargument name="masterActive" type="string" required="yes" default="">

<cfquery name="getRecords" datasource="#dsnRead#">
    DECLARE @ActiveFlag bit;
    SET @ActiveFlag = <cfqueryparam value="#trim(arguments.masterActive)#" cfsqltype="cf_sql_bit">;

    SELECT tm_name, tm_comment, tm_active
    FROM Master WITH (NOLOCK)
    WHERE tm_tblid = <cfqueryparam value="#trim(arguments.masterTblid)#" cfsqltype="cf_sql_char" maxlength="15">
        AND tm_active = @ActiveFlag -- This field should be optional (if @ActiveFlag empty do not include tm_active in the filter)
</cfquery>

A: Instead of
AND tm_active = @ActiveFlag

add the following to your where clause:
AND (@ActiveFlag is null or tm_active = @ActiveFlag)

But be aware that parameter sniffing could lead to future performance problems.
See here.
Consider adding this instead
AND (@ActiveFlag is null or tm_active = @ActiveFlag)
OPTION (OPTIMIZE FOR (@ActiveFlag UNKNOWN))


text:
Q: Concatenate with FOR XML changes encoding I have a query which converts a number into a set of ASCII characters and then attempts to concatenate them into a string:
declare @number int = 651854564

;with cte as (
select @number prev_nr
    , cast(char(@number % 256) as nvarchar(100)) nextchar
union all
select prev_nr / 256    prev_nr
    , cast(char((prev_nr / 256) % 256) as nvarchar(100)) nextchar
from cte
where prev_nr <> 0)
select
    cast(nextchar + '' as nvarchar(100))
from cte
where prev_nr <> 0
for xml path ('');

The characters resulted from splitting the above number to individual characters is:
characters
ä
'
Ú
&

But when attempting to concatenate them with FOR XML they change encoding so that in the end & is transformed and concatenated into the final result which is: ä'Ú&
How can I fix this so I can get the correct encoding and generate the ä'Ú& result?
I've tried converting everything to nvarchar(100) but I have a feeling this has no effect (and actually almost nothing to do with encoding - or at least not helpful in my scenario).
I've also tried the well known STUFF with FOR XML but that didn't really help.

A: Using the type directive in for xml queries
Try this:
declare @number int = 651854564

;with cte as (
select @number prev_nr
    , cast(char(@number % 256) as nvarchar(100)) nextchar
union all
select prev_nr / 256    prev_nr
    , cast(char((prev_nr / 256) % 256) as nvarchar(100)) nextchar
from cte
where prev_nr <> 0
)

select (select
    cast(nextchar + '' as nvarchar(100))
from cte
where prev_nr <> 0
for xml path (''), type).value('.','nvarchar(max)')

rextester demo: http://rextester.com/QRUE46541
returns: ä'Ú&

A: I think the bigger question is: why are you using FOR XML in the first place? XML is not well suited for this task as it has several "special" characters that need to be encoded as they have functional meaning within XML. The list is short, and even changes with context (i.e. attribute vs. element / content) as shown here:
SELECT N'& < > " ?' FOR XML PATH('');
-- & < > " ?

SELECT N'& < > " ?' AS [attr] FOR XML RAW;
-- <row attr="& < > " ?"/>

Given what you are trying to accomplish, you would be better off doing actual string concatenation as follows, and not going anywhere near XML:
DECLARE @number INT = 651854564;
DECLARE @Result NVARCHAR(MAX) = N'';

;WITH cte AS (
  SELECT @number prev_nr
      , CAST(CHAR(@number % 256) AS NVARCHAR(100)) nextchar
  UNION ALL
  SELECT prev_nr / 256    prev_nr
      , CAST(CHAR((prev_nr / 256) % 256) AS NVARCHAR(100)) nextchar
  FROM cte
  WHERE prev_nr <> 0
)
SELECT  @Result += CAST(nextchar + N'' AS NVARCHAR(100))
FROM cte
WHERE prev_nr <> 0;

SELECT @Result;

-- ä'Ú&

I simply declared @Result NVARCHAR(MAX) = N'', then changed the SELECT to start with @Result +=, and removed the FOR XML.

A: If you want to avoid XML encoding, then you could do the following:
SELECT STUFF((SELECT ','+Name AS [text()] FROM #Test FOR XML PATH(''),
TYPE).value('.', 'VARCHAR(MAX)'),1,1,'') AS 'NameList'

by adding:
    ,type).value('.', 'VARCHAR(MAX)'),1,1,'')
you skip XML encoding.


text:
Q: Re-mapping array list values - from subtype to super (sonar qube) Bar extends Foo, and I need to return List of Foos based on List of Bars
Below code works:
private static List<Foo> getList(List<Bar> list) {
       return list.stream()
               .map((Bar e) -> (Foo) e)
               .collect(Collectors.toList());
   }

But I get sonar error:

contrib:FII_USE_FUNCTION_IDENTITY This method declares a no-op
  (identity) lambda method rather than just specifying
  Function.identity()

I don't uderstand the sonar message as it is not actually no-op.

*

*is there a way to implement this sonar compliant and in more elegant manner?

A: Just avoid the explicit type casting and use cast method on Class
return list.stream()
           .map((Bar e) -> Foo.class.cast(e))
           .collect(Collectors.toList());

Probably you can avoid exception by using instanceof
list.stream()
        .filter(bar-> bar instanceof Foo)
        .map(Foo.class::cast)
        .collect(Collectors.toList());

A: It is asking you to do something like this ?
list.stream().map(Function.identity()).collect(Collectors.toList());

Function.identity code:
static <T> Function<T, T> identity() {
        return t -> t;
    }

Casting from a subclass to a superclass is called upcasting.
  Typically, the upcasting is implicitly performed by the compiler.
  Upcasting is closely related to inheritance – another core concept in
  Java. It's common to use reference variables to refer to a more
  specific type

Read more here

A: Seems like the simplest way is to do it via
private static List<Foo> getList(List<Bar> list) {
       return new ArrayList<>(list);
   }

which makes the whole function an overkill.
(I just use it asList<Foo> fooList = new ArrayList<>(list);) when needed.
Sonar has no objection on this approach. (It would be interesting to see performance of these approaches though).
@user3487063 answer was very helpful though, revealing implicit upcasting mechanism


text:
Q: Cypress check if the sort the grid by order I am trying to sort images by order, i have the button new and old. the [data-cy="list-file"] is the wrap for all images and [data-cy=fileCard-list] represent each one image.
I want after clicking the button old for example to be able the check with cypress if the sort is working perfectly.
import { sortFilteredComments } from './../../../../lib/vmr';
import loginData from '../../../fixtures/login.json';
/// <reference types='cypress' />
describe('upload multiple photos', () => {
  before(() => {
    cy.clearLocalStorageSnapshot();
  });

  beforeEach(() => {
    cy.restoreLocalStorage();
  });

  afterEach(() => {
    cy.saveLocalStorage();
  });

  it('login', () => {
     cy.get('[data-cy=projects-card-table]').contains('E2E-TEST').click();
cy.get('[data-cy="header-search-bar"]').click();
cy.wait(3000).get('[data-cy=file-order-old]').click();
cy.get('[data-cy="list-file"]').should('be.visible');
cy.get('[data-cy=each-item-file]').should('be.visible');
  });
});

Here is the file with sort method
`import Card from '@material-ui/core/Card';
import CardMedia from '@material-ui/core/CardMedia';
import Grid from '@material-ui/core/Grid';
import { makeStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import { IFetchedFiles } from 'api';
import clsx from 'clsx';
import { useRouter } from 'next/router';
import React from 'react';
import { useTranslation } from 'react-i18next';
import { formatFullDate } from '~/lib/date';
import MimeIcon from '../../MimeIcon';
import { COLORS } from '~/lib/theme';

const useStyles = makeStyles(() => ({
  card: {
    backgroundColor: '#F1F3F3',
    height: '400px',
    width: '288px',
    margin: '8px'
  },
  cardMedia: {
    height: '200px',
    margin: '10px',
    cursor: 'pointer',
    position: 'relative'
  },
  cardMediaImgContain: {
    backgroundSize: 'contain'
  },
  excelTitle: {
    backgroundColor: COLORS.white,
    bottom: 0,
    color: 'black',
    fontSize: 14,
    fontWeight: 'bold',
    position: 'absolute',
    padding: 4,
    right: 0
  },
  group: {
    marginRight: 20
  },
  groupWrap: {
    display: 'flex',
    padding: '0px 10px'
  },
  projectLabel: {
    fontSize: 14,
    fontWeight: 'bold',
    marginBottom: '11px',
    padding: '0px 10px'
  },
  title: {
    fontSize: 14
  },
  titleWithMarginTop: {
    fontSize: 14,
    marginTop: 12
  },
  fileData: {
    fontSize: 14,
    fontWeight: 'bold'
  },
  fileDataMarginTop: {
    fontSize: 14,
    fontWeight: 'bold',
    marginTop: 12
  },
  iconsContainer: {
    display: 'flex',
    gap: '4px',
    padding: '4px'
  }
}));

const iconSize = 24;

interface IProps {
  file: IFetchedFiles['files'][number];
  organizationName: string;
  getImageUrl: () => any;
  imageMime: boolean;
  excelMime: boolean;
  pdfMime: boolean;
  tiffMime: boolean;
}

const FileCard: React.VFC<IProps> = ({
  file,
  organizationName,
  getImageUrl,
  imageMime,
  excelMime
}) => {
  const classes = useStyles();
  const { t, i18n } = useTranslation();
  const router = useRouter();

  return (
    <Grid **data-cy='each-item-file'** key={file.file.id}>
      <Card className={classes.card}>
        <CardMedia
          className={clsx(classes.cardMedia, {
            [classes.cardMediaImgContain]: excelMime
          })}
          image={getImageUrl()}
          onClick={() => {
            const photoUrl = `/orgs/${organizationName}/projects/${file.project.id}/photos/${file.file.id}`;
            router.push(photoUrl);
          }}
        >

            {file.file.mime && (
              <MimeIcon mime={file.file.mime} iconSizeMime={iconSize} />
            )}

          {excelMime && (

{file.file.name}

          )}
        </CardMedia>
        <Typography variant='h6' className={classes.projectLabel}>
          {file.project.label}
        </Typography>

            {file.material_group.label && (
              <Typography variant='h6' className={classes.title}>
                {t('searchFile.fileList.materialGroup')}
              </Typography>
            )}
            <Typography variant='h6' className={classes.title}>
              {t('searchFile.fileList.material')}
            </Typography>
            <Typography variant='h6' className={classes.title}>
              {t('searchFile.fileList.process')}
            </Typography>
            <Typography variant='h6' className={classes.titleWithMarginTop}>
              {imageMime
                ? t('searchFile.fileList.date')
                : t('file.lastModified')}
            </Typography>
            <Typography variant='h6' className={classes.title}>
              {imageMime
                ? t('searchFile.fileList.photographer')
                : t('searchFile.fileList.registrant')}
            </Typography>

            {file.material_group.label && (
              <Typography
                variant='h6'
                color='primary'
                className={classes.fileData}
              >
                {file.material_group.label}
              </Typography>
            )}
            <Typography
              variant='h6'
              color='primary'
              className={classes.fileData}
            >
              {file.material.label ?? t('searchFile.fileList.uncategorized')}
            </Typography>
            <Typography
              variant='h6'
              color='primary'
              className={classes.fileData}
            >
              {file.process.label ?? t('searchFile.fileList.uncategorized')}
            </Typography>
            <Typography
              variant='h6'
              className={classes.fileDataMarginTop}
              color='primary'
            >
              {`${formatFullDate(new Date(file.file.date), i18n.language)}`}
            </Typography>
            <Typography
              variant='h6'
              color='primary'
              className={classes.fileData}
            >
              {file.user.display_name ?? ''}
            </Typography>

      </Card>
    </Grid>
  );
};

export default FileCard;
`

It's a little bit confusing because it's not a table and i am working on react.js and typescript. Here everything is working perfectly but just the last assertion is where i have no clue.
Notes: you can see that [data-cy="list-file"] represent the whole container and [data-cy=fileCard-list] represent each file inside of the container.

A: I think we need more details about the sorting method you are using. In a table we could check the aria-sort property. Do you have any similar way to check it?
Another way could be iterating over all the [data-cy=fileCard-list] and checking if the parameter you are using to order them is correctly sorted. I don't understand what you mean with that last assertion cy.get('[data-cy="list-file"]').should('be.visible');


text:
Q: Git: show dates in UTC The following command shows some metadata about the last git commit in json format:
git show --quiet HEAD --pretty=format:"{\"hash\":\"%h\", \"author\":\"%cn\", \"commit date\":\"%cd\"}"

{
  "hash":"0fc0fc0",
  "author":"Adam Matan",
  "commit date":"Sun Jan 26 12:26:19 2014 +0200"}
}

Is there a way to present the date in the UTC/GMT time zone, e.g. "Sun Jan 26 10:26:19 2014" ?

A: You can use this:
TZ=UTC0 git show --quiet --date=local --format="%cd"

If you want to control the date format, you can do this:
TZ=UTC0 git show --quiet --date='format-local:%Y%m%dT%H%M%SZ' --format="%cd"

Update 2021-10-16: changed TZ=UTC to TZ=UTC0 thanks to @alex-shpilkin.

A: I don't see an utc format in the log data formats (listed this answer).
The closest I get from your format is:
git config log.date local

C:\Users\VonC\prog\git\git\>git show --quiet HEAD --pretty=format:"{\"hash\":\"%h\", \"author\":\"%cn\", \"commit date\":\"%cd\"}"
{"hash":"b594c97", "author":"Junio C Hamano", "commit date":"Thu Jan 23 10:00:28 2014 -0800"}

C:\Users\VonC\prog\git\git\>git config log.date local

C:\Users\VonC\prog\git\git\Documentation\technical>git show --quiet HEAD --pretty=format:"{\"hash\":\"%h\", \"author\":\"%cn\", \"commit date\":\"%cd\"}"
{"hash":"b594c97", "author":"Junio C Hamano", "commit date":"Thu Jan 23 19:00:28 2014"}

So from iso:
"Thu Jan 23 10:00:28 2014 -0800"

To local:
"Thu Jan 23 19:00:28 2014"

As commented, this is not UTC, unless the your machine local time is already UTC.

That was discussed on the mailing list:

Adding user.hideTimezone for setting UTC timezone
Authoring and sharing a commit by default exposes the user's time zone.
"commit --date=YYYY-MM-DDThh:mm:ss+0000" suffices to put the author
time in UTC but not the commit time in UTC.
But the user shouldn't have to pass a flag at all.
Git should entirely stop accessing, recording, and sharing the user's time zone, full stop.
Failing that, git should by default stop accessing, recording, and sharing the user's time zone, but if individual users want to have their time zones on their commits, they can opt into it.

Junio C. Hamano, Git maintainer, answered:

You are free to run
$ TZ=GMT git commit

if you wanted to opt out of the feature, but this has been the
default since day one and people expect Git to behave this way.

Also:

For now, using the --date argument on git commit allows you to also pass a timezone:
git commit --date="$(TZ=PST date)"

This patch (for adding a  user.hideTimezone) is yet to be fully developed.

A: Technically git's Unix timestamp format (e.g. via --date='unix' / --format='%at') is always in UTC too. See https://git-scm.com/docs/git-log / https://git-scm.com/docs/pretty-formats for details.


text:
Q: radius of convergence of integral of power series Suppose $\sum \limits_{n=0}^{\infty} a_n x^n$ has radius of convergence R. What is the radius of convergence of $\sum \limits_{n=0}^{\infty} \frac{a_n x^{n+1}}{n+1}$?
How do I solve this without using power series integration?

A: Given $R=\lim\limits_{n\to\infty} \left|\frac{a_n}{a_{n+1}}\right|=\lim\limits_{n\to\infty} \left|\frac{a_{n-1}}{a_{n}}\right|$
Also, let $$\sum \limits_{n=0}^{\infty} \frac{a_n x^{n+1}}{n+1}=\sum \limits_{n=1}^{\infty} \frac{a_{n-1} x^{n}}{n}=\sum \limits_{n=1}^{\infty} b_{n} x^{n}$$
where $b_n=\frac{a_{n-1}}{n}$
$R_1=\lim\limits_{n\to\infty} \left|\frac{b_n}{b_{n+1}}\right|=\lim\limits_{n\to\infty} \left|\frac{a_{n-1}}{n}\times\frac{n+1}{a_{n}}\right|=\lim\limits_{n\to\infty} \left|\frac{n+1}{n}\right|\times \lim\limits_{n\to\infty} \left|\frac{a_{n-1}}{a_{n}}\right|$. You know where to go from here.


text:
Q: How to use math expression in mysql sql? See below.
If use like this:

select product_id, name from product limit (1-1)*5, 5;
  ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(1-1)*5, 5' at line 1

but if use like this:

select (1-1)*5 ;
  +---------+
  | (1-1)*5 |
  +---------+
  |       0 |
  +---------+
  It's ok.

How to use math expression in first statement?

A: http://dev.mysql.com/doc/refman/5.5/en/select.html says,

LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants.

And it goes on to list two exceptions,

*

*placeholders in prepared statements, and

*parameters or variables in a stored procedure (the latter only from 5.5.6 on).
So looks like other than that, you can use only integers there, and not expressions.


text:
Q: Retrieve Twitter tweets in actionscript this is my first time using Twitter API therefore I am not very familiar. I want to retrieve all twitter tweets which has a hashtag, for example #converse
This is my code:
var myXMLLoader:URLLoader = new URLLoader();
myXMLLoader.load(new URLRequest("http://search.twitter.com/search.atom?q=converse"));
myXMLLoader.addEventListener(Event.COMPLETE, processXML);

function processXML(e:Event):void{
    var myXML:XML = new XML(e.target.data);
    trace(myXML.status[0].text);

    load1.text = myXML.status[0].text;
}

This is the error I got :

Error #2044: Unhandled ioError:. text=Error #2032: Stream Error. URL: http://search.twitter.com/search.atom?q=converse
      at mainClass()

I don't understand the URL and I don't know if the syntax is correct. I searched in the internet and this is how they retrieve the feeds.

A: change the URL you are using for this other:
http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=pcinfo72


text:
Q: How to detect if image is landscape from UIImagePicker I use the following code to check but it doesn't work.. always returns portrait even on images taken in landscape
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{

    //dismiss imagepicker controller
    [self dismissViewControllerAnimated:NO completion:nil];

    fishingSpotChosenImage = [info objectForKey:UIImagePickerControllerOriginalImage];

    if (fishingSpotChosenImage.imageOrientation == UIImageOrientationUp) {
        NSLog(@"portrait");
    } else if (fishingSpotChosenImage.imageOrientation == UIImageOrientationLeft || fishingSpotChosenImage.imageOrientation == UIImageOrientationRight) {
        NSLog(@"landscape");
    }
  }

Im assuming it doesn't work because the image is actually in portrait when selected so how do I detect when the image has black bars like the following image..

A: Yeah, in this case your "landscape" image orientation is still "UP" since the image is right-side up.
If you only care about images that are of the camera's 4:3 or 3:4 rectangular aspect ratio, perhaps you can just compare the image width to the image height to see whether it's wider than it is tall or vice versa using UIImage's size property, ex.
if (fishingSpotChosenImage.size.height > fishingSpotChosenImage.size.width) {
    NSLog(@"portrait");
} else {
    NSLog(@"landscape");
}


text:
Q: CSS - How to insure that a input will be in the middle of a specific area I'm having a simple row with three utf-8 arrows

▼

▲

▼

So what I am trying to do is to have the arrows in the same row, but I want them to be in the middle of their height and their width - no matter what text size value they will get.
I've tried the next CSS code -
#container{
display: inline-block;
height: 80px;
width: 100%;
}

#one{
float:left;
width: 20%;
font-size: 90px;
}

#two{
float:left;
width: 20%;
font-size: 50px;
}

#three{
float:left;
width: 20%;
font-size: 60px;

}

As you can understand it sure don't work, any ideas what can I do?
Thanks for any kind of help

A: You have to display elements as inline-block and set vertical-align: middle, text-align: center.

#container {
  display: inline-block;
  height: 80px;
  width: 100%;
}
#one,
#two,
#three {
  display: inline-block;
  text-align: center;
  vertical-align: middle;
}
#one {
  width: 20%;
  font-size: 90px;
}
#two {
  width: 20%;
  font-size: 50px;
}
#three {
  width: 20%;
  font-size: 60px;
}

▼

▲

▼

A: Just add some styles to the 3 elements:
#container{
height: 80px;
width: 100%;
display: table;
}
#one{
width: 20%;
font-size: 90px;
}

#two{
width: 20%;
font-size: 50px;
}

#three{
width: 20%;
font-size: 60px;
}
#one,#two,#three{
    text-align: center;
    display: table-cell;
    vertical-align: middle;
}

WORKING FIDDLE


text:
Q: JSONDecodeError when looping through SEC indices Something strange keeps happening when I try to scrape SEC filings from the web. The web scraping code I've executed in Python 3 loops through a list of CIKs (a unique filing ID for companies). This is where the code breaks (early in the code):
from bs4 import BeautifulSoup
import requests

base_url = 'https://www.sec.gov/Archives/edgar/data/'

for cik_number in ciks['public_ciks']:

    url = f'{base_url}{cik_number}/index.json'
    response = requests.get(url)

    # Parse the response
    soup = BeautifulSoup(response.content, 'lxml')

    # **This is where the error occurs**
    decoded_content = response.json()

    JSONDecodeError: Expecting value: line 1 column 1 (char 0)

When I ran this command the other day, it worked just fine. Today, not only does this command keep throwing an error, but it happens at different parts of the loop: sometimes it's the 1st url, sometimes the 5h, the 8th, etc., with no consistency. When I isolate those URLs and perform this command for a single instance, there's never an error, making this issue of mine ever stranger. Can anyone help? Thanks!

A: Instead of
 decoded_content = response.json()

You have to import the json module then you should use:
decoded_content = json.loads(response.text, encoding="utf-8")

A: Add the strict attribute as False
Try this:
decoded_content = json.loads(response.text, encoding="utf-8", strict=False)


text:
Q: Unassigned Reference Exception UnassignedReferenceException: The variable segmentPrefab of Snake has not been assigned.
You probably need to assign the segmentPrefab variable of the Snake script in the inspector.
Im making a very simple snake game where you eat the fruit and the snake multiplies and so on, when the snake eats the fruit it creates a segmentprefab clone creates but then i get this error and have no idea how to fix it? please help

A: You have to assign a prefab to the segmentPrefab variable before you can clone something.
Just select the GameObject on which the Snake script is attached, then in the inspector locate the Snake component and look at the "Segment Prefab" property, it should be empty. Just drag and drop a valid prefab on the field, it should be enough.
Reference: https://docs.unity3d.com/Manual/UsingComponents.html


text:
Q: Entity Framework returning IQueryable of join of two tables I'd like to use Entity Framework to return data from 2 tables, and a selection of columns of the 2 tables, at first I was not having much luck with something simple, like returning int's and strings (ie. select new { id = t1.ID, other = t2.OtherData }, as casting that anonymous type was cumbersome at the destination (destination being my winform), so I struck on the idea to just return both table rows...
So something like this :
  public static IQueryable<{Table1,Table2}> byRecID(Guid recID, MyContext DBContext)
  {
      return (from i1 in DBContext.Table1
             join j1 in DBContext.Table2 on i1.GroupID equals j1.GroupID
             where i1.RecID.Equals(RecID)
             select new { i1, j1 }).SingleOrDefault();
  }

This is all fine EXCEPT the return type of the method is incorrect. I've tried a few combinations. Unfortunately, when I call "byRecID" from the winform, "SingleOrDefault" is not available, but IS available inside 'byRecID' method, so I can't just return IQueryable, needs to be the typed IQueryable<SOMETHING IN HERE> (because SingleOrDefault not an extension of IQueryable, only IQueryable<T>).
My Question... is there a syntax for 'SOMETHING IN HERE' that lets me specify its a join of two table rows?
and I'm wondering... Why is SingleOrDefault an option INSIDE the method but not an option of the result of the method when called from my winform?
Basically I was hoping for something that allows clean data calls from my winforms, without casting to hideous anonymous types then using reflection (like when I returned anonymous type of primitives), but also don't want to spawn a Type just for use by my byRecID method.

A: In C# anonymous types are best used in the scope of the same method where you project them. As you have seen for your self they can't be used outside of the defining method. So you can't return anonymous types from methods (and keep their structure, you can always return them as objects, but this is not good idea) this makes your syntax of the method invalid.
Best option is to project the result to class specified for your needs.
public class TableJoinResult
{
   public Table1 Table1 { get; set; }
   public Table2 Table2 { get; set; }
}

Your query:
 public static IQueryable<TableJoinResult> byRecID(Guid recID, MyContext DBContext)
  {
      return (from i1 in DBContext.Table1
             join j1 in DBContext.Table2 on i1.GroupID equals j1.GroupID
             where i1.RecID.Equals(RecID)
             select new TableJoinResult { Table1= i1, Table2 = j1 }).SingleOrDefault();
  }

More info on anonymous types: https://msdn.microsoft.com/en-us/library/bb397696.aspx

A: 1)Create a specific class that describes you result.
2)See 1

A: I wanted to avoid creating a specific class or a struct.
The below is a lengthy way that avoids creating a struct/class.
So I did this in my service class:-
 List<KeyValuePair<string,int>> IWorkflowService.GetServiceRetention()
        {
           var serviceRetention =  from y in _context.SERVICES
                     join z in _context.SERVICE_SETTINGS on y.ID equals z.SERVICEID
                     select new { Service= y.SERVICE, Retention=z.RETENTION };//new KeyValuePair<string,int?>( y.SERVICE, z.RETENTION ));
            var list = new List<KeyValuePair<string, int>>();
            foreach (var obj in serviceRetention)
            {
                list.Add(new KeyValuePair<string, int>(obj.Service,Convert.ToInt32(obj.Retention)));
            }
            return list;
        }

I had to do this in my controller class:
List<KeyValuePair<string, int>> c = _service.GetServiceRetention();

            foreach (var obj in c)
            {
                 //The key contains service and value contains Rtention.
                  RecurringJob.AddOrUpdate(DELETE_SERVICE + obj.Key, () =>
                  Delete(obj.Key), //this is my function that does the actual process
               Cron.DayInterval(Convert.ToInt32(obj.Value)));
            }

I am not sure if this is the best way to do it, but works for me.


text:
Q: Chrome Debugging Protocol: block hostnames (cancel network request) Through Chrome Debugging Protocol (or maybe a command-line flag), is there a way to block some hostnames (i.e. cancel any network request to them) in a Chrome headless instance using a remote proxy?
I suppose doing so via the local hosts file will work, but it won't have any affect if using a remote proxy.

A: I think it should be possible to do this with the Chrome Debugging Protocol. There's an experimental feature in the web inspector, which exposes a Request blocking tab. Here you can block network requests, given a particular match criteria.

The Debugging Protocol has an addBlockedURL method under the Network domain, which takes a URL as a parameter. It's an experimental API, but I think the current way you could do this is to do a regex match on the request URLs and pass each matched URL to the method. I suspect the new web inspector feature implements it along these lines.

A: I'm not aware of any way to do this using the remote debugging protocol.
The typical way to do block web requests to certain hostnames (or based on any other criteria!) is by installing an extension which uses the chrome.webRequest API to intercept and cancel requests. This is how ad-blocking extensions work, for instance.


text:
Q: Inserting multiple spans into div by character offsets within div with javascript For a text annotation app I would like to programmatically color spans of text within a given div using previous user annotations, which are saved in the database as character offsets, e.g. - color character 0 to 6, color from 9 to 12, etc.
My approach has been to get the first #text node within the div (using an answer from 1), create a range there, and then insert the span there. But after the first span is inserted the first there is no longer a text element that contains all of the text in the div, and this fails:
function color_x_y(elementname, x, y){ // color from coordinate x to y, within div elementname

    elem = get_text_node(elementname);

    range = document.createRange();
    range.setStart(elem, x);
    range.setEnd(elem, y);

    span = document.createElement("span");
    span.style.border = "5px solid red";

    range.expand();
    span.appendChild(range.extractContents());
    range.insertNode(span);
}

function get_text_node(node){
    var oDiv = document.getElementById(node);
    var firstText = "";
    for (var i = 0; i < oDiv.childNodes.length; i++) {
        var curNode = oDiv.childNodes[i];
        if (curNode.nodeName === "#text") {
            firstText = curNode;
            break;
        }
    }
    return firstText;
}

I am new to javascript and would appreciate any ideas on how to accomplish this.
Thanks!
EDIT
I should note that highlights may overlap with one another.

A: I set the annotation span class name annotate so the script can get rid of inline style.
I revised the getTextNode() looping order. Because for 2+ annotations, the first text node will be your first annotation. Therefore, I loop the childNode starting from the end.
Finally, the more annotation inserted, the more childNodes would be, and more content will be extract from it. Therefore, your "target" text node will become shorter (e.g. to color 4 to 7, 7 will be your new 0). To compensate the loss of content, the coordinate need an offset.
p.s. name your function camelCase

function colorRange(elementname, x, y) { // color from coordinate x to y, within div elementname

  elem = getTextNode(elementname);

  range = document.createRange();

  // compensate the shorter text length
  var offset = document.getElementById(elementname).innerText.length - elem.length;
  range.setStart(elem, x - offset);
  range.setEnd(elem, y - offset);

  span = document.createElement("span");
  span.className = "annotate";

  range.expand();
  span.appendChild(range.extractContents());
  range.insertNode(span);
}

function getTextNode(node) {
  var oDiv = document.getElementById(node);
  var lastText = "";
  // loop from the end
  for (var i = oDiv.childNodes.length - 1; i >= 0; i--) {
    var curNode = oDiv.childNodes[i];
    if (curNode.nodeName === "#text") {
      lastText = curNode;
      break;
    }
  }
  return lastText;
}

colorRange('lorem', 0, 5); // annotate "Loerm"
colorRange('lorem', 12, 17); // annotate "dolor"
colorRange('lorem', 116, 124); // annotate "pulvinar"
.annotate {
  border: 5px solid red;
}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.

A: In allow for overlaps in highlighting and for ranges of highlighting not coming in numerical order, we'll need to build up the element innerHTML bit by bit on each call of the colorXY function, taking into consideration any existing highlighting.
We can do this most easily by putting both highlighted and unhighlighted segments into span elements so JavaScript will do the parsing of the HTML associated with the elements for us.
Here's a snippet which does this on a 'vanilla' text - that is, text that does not contain other HTML elements. I guess in the real case  you will want to count character positions ignoring any intervening HTML, but keep the HTML in the final result. This needs a slight tweak to the below, but I hope this is enough to get things started.
Also note that span presents a problem in that not all HTML can be 'legally' embedded within a span element. The question mentioned span so it is used here, but it may be necessary to either parse any embedded HTML further, to ensure span elements do not straddle them, or possibly to use divs - but even so nesting of HTML elements will have to be preserved. This will require e.g. sensing when you are within say a p element.

let inputX = document.getElementById('x');
let inputY = document.getElementById('y');

// NOTE: counting starts at 0 - so for the first character in the string x=0

function colorXY(element, x, y) {
  x = Number(x);
  y = Number(y);
  if (y<x) { alert('Error: y<x'); return; }

  let els = element.querySelectorAll('.highlighted, .unhighlighted');
  let ranges = []; //will hold start and end character position of string within each special span

  let i; //working index

  if (els.length == 0) { //first time we've handled this element so make it all an unhighlighted span
    element.innerHTML = '' + element.innerHTML + '<\/span>';
    els = element.querySelectorAll('.unhighlighted');
  }

  //extract all the text to get the original string and the range of each special span
  let originalStr = '';
  let chNo = 0;
  for (i = 0; i < els.length; i++) {
    originalStr += els[i].innerHTML;
    ranges[i] = [chNo, chNo + els[i].innerHTML.length - 1];
    chNo = ranges[i][1] + 1;
  }

  if (x > (originalStr.length - 1) || y > (originalStr.length - 1) ) {alert('x and/or y is larger then the length of the text'); return;}

  element.innerHTML = '';

  function wrap(highlight, first, last) { // wrap the characters from first to last in a span element and add it to the element
    if ((first >= 0) && (last >= first)) {
      wrapStr(highlight, originalStr.slice(first, last+1));
    }
  }

  function wrapStr(highlight, str) {
      element.innerHTML = element.innerHTML + '' + str + '<\/span>';
 }

  function elHighlighted(el) { // true if element has a class highlighted, false otherwise
    return !el.classList.contains('unhighlighted')
  }

//now go through the special elements we already have to see where our new range fits in - there may be overlaps

  let startEl = false; //will be set to the element number that contains the character at x
  let startX = 0; //will be set to the number of the first character in this element
  let startI = 0; //will be set to its index
  let endEl = false; //will be set to the element number that contains the character at y
  let EndY = 0; //will be set to its index

  for (i = 0; i < els.length; i++) {
    if (x >= ranges[i][0] && x <= ranges[i][1]) { // it starts in this element
      startEl = els[i];
      startX = ranges[i][0];
      startI = i;
    }
    if (y >= ranges[i][0] && y <= ranges[i][1]) { // it ends in this element
      endEl = els[i];
      endY = ranges[i][1];
      endI = i;
    }
  }

// now we know where the x,y range lies we can copy across non-involved elements
// we only have to do special stuff when we see the startEl
  for (i = 0; i < startI; i++) {
     wrapStr(elHighlighted(els[i]), els[i].innerHTML);
}

  if (elHighlighted(startEl) && elHighlighted(endEl)) { // both elements already highlighted
    wrap(true, startX, endY);
  }
  else if (elHighlighted(startEl)) { //first one already highlighted, second one not
    wrap(true, startX, y);
    wrap(false, y+1, endY);
  }
  else if (elHighlighted(endEl)) { // first one not highlighted, second one is
    wrap(false, startX, x-1);
    wrap(true, x, endY);
  }
  else { //neither of them highlighted
    wrap(false, startX, x-1);
    wrap(true, x, y);
    wrap(false, y+1, endY);
  }

//now copy across the rest
  for (i = (endI + 1); i < els.length; i++) {
     wrapStr(elHighlighted(els[i]), els[i].innerHTML);
  }
}
.highlighted {
  background-color: yellow;
}
.unhighlighted {
  background-color: transparent;
}
x: <input id="x" type="number" />
y: <input id="y" type="number" />
<button onclick="colorXY(document.querySelector('.thedata'), inputX.value, inputY.value);">Click to highlight</button>

(Note: counting starts at 0)

Lorem ipsum dolor sit amet. Ea pariatur veritatis et commodi voluptas quo quaerat voluptates qui natus dolor et quia Quis! Et quia labore non minus mollitia ut magnam dicta ea impedit facilis ut animi perspiciatis eos amet totam.
Non earum doloremque ea nobis impedit sed totam consequuntur et omnis totam et modi sunt et perferendis tempore. At eaque totam aut amet omnis et magni laboriosam et enim amet. Sit aperiam quos quo deserunt harum eum laboriosam explicabo.Ut exercitationem quidem et voluptatum harum et repellat fugiat vel consequatur exercitationem ut sunt molestias qui galisum laudantium et esse quam. Quo veniam nihil ex maxime facilis sed natus nihil. Et aliquam tenetur qui fugiat placeat et quae repudiandae aut pariatur adipisci ut Quis optio. Id culpa labore aut labore nisi cum voluptatem molestiae ab accusamus voluptas sed fugit dolores ut doloremque cumque.


text:
Q: UPDATE mysql database and the id and the image in relation to the id? I have this php file which will update a table in mysql database.
it works to a certain. it will update the name of the product (product_name) and it will update the (date_added) too. but it is not updating the id and as a result the image that was uploaded with that id is not showing!!
here is the code:
<?php
// Parse the form data and add inventory item to the system
if (isset($_POST['product_name'])) {

    $product_name = mysql_real_escape_string($_POST['product_name']);
    // See if that product name is an identical match to another product in the system
    $sql = mysql_query("SELECT id FROM tomProduct WHERE product_name='$product_name' LIMIT 1");
    $productMatch = mysql_num_rows($sql); // count the output amount
    if ($productMatch > 0) {
        echo 'Sorry you tried to place a duplicate "Product Name" into the system, click here';
        exit();
    }
    // Add this product into the database now
    $sql = mysql_query("UPDATE tomProduct SET product_name='$product_name', date_added=now()") or die (mysql_error());
     $pid = mysql_insert_id();
    // Place image in the folder
    $newname = "$pid.jpg";
    move_uploaded_file( $_FILES['fileField']['tmp_name'], "../tom/$newname");
    header("location: verify_members.php");
    exit();
}
?>

and here is the form:
<form action="verify_members.php" enctype="multipart/form-data" name="myForm" id="myform" method="post">

    Product Name

      <input name="product_name" type="text" id="product_name" size="64" />

    Product Image

      <input type="file" name="fileField" id="fileField" />

      <input type="submit" name="button" id="button" value="Add This Item Now" />

</form>

anyone knows why this is happening?
Thanks

A: mysql_insert_id() returns the last INSERT record, not UPDATE.


text:
Q: How to place mat-sidenav under the mat-toolbar I have this code stackbliz:
<mat-sidenav-container class="sidenav-container">
  <mat-sidenav #drawer class="sidenav" fixedInViewport
      [attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'"
      [mode]="(isHandset$ | async) ? 'over' : 'side'"
      [opened]="(isHandset$ | async) === false">
    <mat-toolbar>Menu</mat-toolbar>
    <mat-nav-list>
      Link 1
      Link 2
      Link 3
    </mat-nav-list>
  </mat-sidenav>
  <mat-sidenav-content>
    <mat-toolbar color="primary">
      <button
        type="button"
        aria-label="Toggle sidenav"
        mat-icon-button
        (click)="drawer.toggle()"
        *ngIf="isHandset$ | async">
        <mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
      </button>
      youtube-angular
    </mat-toolbar>
    <app-dashboard></app-dashboard>
  </mat-sidenav-content>
</mat-sidenav-container>

Currently the left sidebar shown above the mat-toolbar.
What I want is to place mat-sidenav under the mat-toolbar basically the way it works on gmail.
Also I want the left toolbar to behave like the one on gmail.
How would you do that?

A: Just add top: <your_toolbar_size>px !important; to your .sidenav class.

Edit:
Please see this stackblitz.


text:
Q: htaccess rewrite rule for subdomains with page id i want to redirect
http://subdomain.example.com/index.php?pageID=45
to
http://example.com/subdomain/45.html
Please help me with this
i tried
RewriteCond %{HTTP_HOST} ^(www\.)?subdomain\.example\.com$ [NC]
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^(.*)$ http://www.example.com/sudomain/$1 [L,R=301]

A: You can replace your code by this one in your htaccess (in root folder)
RewriteEngine On

RewriteCond %{HTTP_HOST} ^subdomain\.example\.com$ [NC]
RewriteCond %{QUERY_STRING} ^pageID=([1-9][0-9]*)$ [NC]
RewriteRule ^index\.php$ http://example.com/subdomain/%1.html? [R=301,L]


text:
Q: Font awesome icon as a html link I created two links for my projects and I would like to increase to size of the github icon to take at least 80% of the space within the green box.
However, I am using padding to create my buttons, so when I am increasing the size of my icon, the button also increases.

html

                    Visit website

css
.project-links

{
  text-align: center;
}

.project-links a{
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;

}

A: You can simple add font size of icon, add
To increase icon sizes relative to their container, use the fa-lg (33% increase), fa-2x, fa-3x, fa-4x, or fa-5x classes.
 fa-lg
 fa-2x
 fa-3x
 fa-4x
 fa-5x

A: You can use

transform: scale(size_multiplier);

To scale the icon without it changing the container/button size or center point (unlike font-size and fa-[size])

/* magic happens here */
.icon{
  transform: scale(3);
}

.project-links
{
  text-align: center;
}

.project-links a{
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;

}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

  Visit website

A: Here is the possible solution you are looking for:-
use  and reduce the padding only for you github icon to adjust according like :-
.project-links a fa-github-square {
  padding: 5px 10px;
}


text:
Q: Check if an XML node exists, using Tinyxml  I am using tinyXml for parsing an XML file in C++. Could anyone please tell me how do I check to see if a node (parent/child/next sibling) exists or not. Below are the only nodes present in the xml file I'm working on.
TiXmlElement* Instrmt = TrdCaptRpt->FirstChildElement();
TiXmlElement* Undly = Instrmt->NextSiblingElement();
TiXmlElement* Amt = Undly->NextSiblingElement();
TiXmlElement* RptSide = Amt->NextSiblingElement();
TiXmlElement* Pty = RptSide->FirstChildElement();

if any of the nodes above is missing in the sequence then the program aborts with a segmentation fault.
Could anyone please help.
Thanks

A: You can use the const TiXmlNode* TiXmlNode::FirstChild (   const char *    value    )   const function of the TiXmlNode class and check if the resulting TiXmlNode* is NULL or not.
TiXmlNode* child = mynode->FirstChild();

if (child != NULL)
{
  //A child exists....
}

For Parent you have a similar function.  You can find the documentation here.
I hope this helps.

A: TiXml provides the TiXMlHandle class to take care of checking for NULL, so it should sort out the segmentaiton faults. You still need to check the existence of the node at the end of the chain.


text:
Q: How do I define a vector of chrono::DateTime with different TimeZones? I am working with the chrono library, and do not know how to define a struct field that is a vector of DateTime<Tz: TimeZone> structs with a TimeZone trait instead of a concrete type.
I.e, I can do:
use chrono::{DateTime, TimeZone, Utc}; // 0.4.11

pub struct ItemSchedule {
    pub times: Vec<Box<DateTime<Utc>>>,
}

When I try to use a trait object:
use chrono::{DateTime, TimeZone, Utc}; // 0.4.11

pub struct ItemSchedule {
    pub times: Vec<Box<DateTime<dyn TimeZone>>>,
}

I get an error:
error[E0191]: the value of the associated type `Offset` (from trait `chrono::offset::TimeZone`) must be specified
 --> src/lib.rs:4:37
  |
4 |     pub times: Vec<Box<DateTime<dyn TimeZone>>>,
  |                                     ^^^^^^^^ help: specify the associated type: `TimeZone<Offset = Type>`

Looking at the code, the TimeZone trait has an associated type called Offset, which has to implement a trait called Offset. I also get errors if I attempt to specify this the type declaration.


text:
Q: Poll works on stdin when entering manually, but not when input is piped and not redirected Consider this C program:
#include <poll.h>
#include <stdio.h>
#include <unistd.h>

#define TIMEOUT 500 // 0.5 s
#define BUF_SIZE 512

int fd_can_read(int fd, int timeout) {
    struct pollfd pfd;

    pfd.fd = fd;
    pfd.events = POLLIN;

    if (poll(&pfd, 1, timeout)) {
        if (pfd.revents & POLLIN) {
            return 1;
        }
    }

    return 0;
}

int main(int argv, char **argc) {
    int fd;
    size_t bytes_read;
    char buffer[BUF_SIZE];

    fd = STDIN_FILENO;

    while (1) {
        if (fd_can_read(fd, TIMEOUT)) {
            printf("Can read\n");
            bytes_read = read(fd, buffer, sizeof(buffer));

            printf("Bytes read: %zu\n", bytes_read);
        }
        else {
            printf("Can't read\n");
        }
    }
}

It tries to poll given file descriptor (which is the fd of stdin in this case), and tries to read from it when it's available for reading. Here's an example input file called "input":
stuff to be read

So let's say I run the program, give a few inputs and close it:
./a.out
test
Can read
Bytes read: 5
Can't read
Can't read
...

So lets try reading the input from a file by piping/redirecting the contents of it to stdin of my program:
cat input | ./a.out # Or ./a.out < input
Bytes read: 0
Can read
Bytes read: 0
Can read
...

Now, the poll returns instantly (does not wait for the timeout to run out), and gives the results I was not expecting. I do know poll() does not work on files correctly, but if I'm not mistaken, I'm not reading from a file.

A: The problem is that poll (just like select) only tell you that a call to e.g. read will not block. It doesn't tell you if there's actually anything to read.
And if you read the read manual page you will see that when it returns 0 it means end of file (or connection closed for sockets).
What poll is telling you is that read can be called without blocking, and what read tells you by returning 0 is that there is nothing more to read.
You will get a similar "false positive" by pressing the end-of-file shortcut key (by default Ctrl-D on POSIX systems like Linux) for the non-piped or -redirected input example.


text:
Q: Sumifs() function in excel second condition is not working? I want to be able to use sumifs() for two conditions. If the section is groceries and the month is September, I want it to sum it. If I take away the second condition, it sums the 286.55, but if I leave the second condition in sumifs() then it gives me 0.

A: I can think of one of two issues...
1 You are trying to match a date with a string. To check I would do a =B2*1 & =I2*1. If both of them give error then you are ok.
2 The strings are different(one of them  has a trailing space etc.) Try =LEN(B2) & LEN(I2). I'm sure one of them is >9.
You would know what to do by yourself


text:
Q: Get informed when listener has been attached to a Backbone.Model event I'd like to know if its somehow possible to notify a Backbone Model that a listener has been attached to a certain event so it can react by doing some initialization process.
I'm asking, because I have a case where some events need too much costly preprocessing to just having the data available to fire a event that nobody listens to.
Is that possible at all with the Backbone Event system, or do I have to override the on() method?

A: There are a lot of ways to implement your idea.
Here is the first easy way:
_.extend(Backbone.Model.prototype, {

    subscribe: function (name, callback, context) {
        this.on(name, callback, context);
        this.trigger('bind:' + name, callback, context);
    }

});

So we will not override "on" method. We created own "subscribe" method. Here is usage example:
var Human = Backbone.Model.extend({

    initialize: function () {
        this.on('bind:change', function () {
            console.log('Someone started listening to "change" event');
        });
    }

});

var human = new Human({ name: 'Christian Engel' });

human.subscribe('change', function () {
    // do some stuff when a model's attributes have changed
});

But new method can make you confused. So we have an ability to override "on" for all the Backbone models:
_.extend(Backbone.Model.prototype, {

    on: function (name, callback, context) {

        var eventSplitter   = /\s+/,
            eventBinder     = /bind:/;

        Backbone.Events.on.call(this, name, callback, context);

        if (!eventBinder.test(name) && !eventSplitter.test(name)) {
            this.trigger('bind:' + name, name, callback, context);
        }

    }

});

Great! Now we can write pretty nice code:
var Human = Backbone.Model.extend({

    initialize: function () {
        this.on('bind:change', function () {
            console.log('Someone started listening to "change" event');
        });
    }

});

var human = new Human({ name: 'Christian Engel' });

human.on('change', function () {
    // do some stuff when a model's attributes have changed
});

And here is live demo / example / test:
http://jsfiddle.net/gmAL3/1/


text:
Q: Git Status not recognizing changes Odd situation here.  I have modified several files, and for the sake of this discussion, SearchG2Helper.cs and SearchG2Helper.Custom.cs are definitely different but git status shows no differences.  I also checked git check-ignore -v SearchG2Helper.Custom.cs and that didnt respond with anything.
See the git internals command outputs below:
$ git cat-file -p 9b02b119
...snip...
100644 blob 231f4f6eebcb377fbb318845b8a2b17a7eb7732e    SearchG2Helper.Custom.cs
100644 blob 56dc73150a5c73ccba0d4d41c205caa8379c9314    SearchG2Helper.cs
100644 blob 6922412c3a1954367f89b873188aa38a1a5ac4d5    _AssetExtensions.cs
100644 blob dbe562aede1287a2a42824a2c29fc15579df4b98    _CPContrib.AspxHelper,0.1.0,AspxHelper.cs
100644 blob c68060a2e13842a8fe3e1f559f484a0f53c5ca1e    _CPContrib.Core,0.2.0,Core.cs

$ git hash-object SearchG2Helper.cs
8bdd145719c3a8a6dd8cccf2185d3826d159b28e

$ git hash-object SearchG2Helper.Custom.cs
9f071c622d7896026c556cf2574b94778f58cec6

Notice that hash in the tree object is totally different from the hash given by git hash-object, yet, a git status doesnt show any changes
Using Git for Windows 2.15.2.1
Note, using git internal information understood from this url: https://git-scm.com/book/en/v2/Git-Internals-Git-Objects
Update: A new Clone into a new directory seems to have fixed the issue.  I'm just wondering how this git database got corrupted? and what to look for?


text:
Q: How to control source files in VS Code This seems like a painfully simple question that would be 3 seconds of googling away, but here I am after days of head scratching.  I have a collection of c files and headers saved in

*

*F:\public\code\tlfps02c\embedded\src\
some of which require include files saved in

*

*F:\public\code\watt32\inc\
but I also have old code I don't want to use saved in

*

*F:\public\code\tlfps02c\embedded\src_old\
The problem is Visual Studio Code is using definitions from src_old and I can't figure out how to control this.  I don't have any files open from this folder so from what I've read it shouldn't be finding these files.  I need to exclude these files and would prefer to achieve this within VSCode and not with some heavy handed file management changes


text:
Q: How to avoid duplicate video files when using PHAssetChangeRequest.FromVideo I'm writing an app importing a video file from a remote server (drone) over HTTP. After downloading the file to local storage (/Documents/video) I import it to a custom album in the PHPhotLibrary using PHAssetChangeRequest.FromVideo.
I'm able to import the video, and when accessing the Photos app in the simulator the video appears in the correct album. However, if I delete it from the album the file is not deleted from my the apps /Documents/video folder.
I then tried to delete the file from /Documents/video after importing it using PHAssetChangeRequest.FromVideo, but then the video disappears from the Photos app.
How do I ensure there is only one copy of the video file, preferably stored in the shared photo gallery? Can I detect that a file is deleted, so that I can delete it from the /Documents/video folder? Or do I need to "sync" this my self everytime the app starts?

A: I think you should store the downloaded video to a temporary directory like
NSString *outputPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"output.mov"];
And then you can store it into Photos app.
The benefit of storing it into temporary directory is OS will automatically clear it when required however you can manually delete it whenever you want by creating following class method
+ (void)clearTemporaryDirectoryData
{
    NSArray* tempDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL];
    for (NSString *file in tempDirectory) {
        [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), file] error:NULL];
    }
}

In your case you can delete temp data after saving the downloaded video into Photos app.


text:
Q: Finding percentage of rejection in pandas dataframe I have a pandas data frame like given below
Id1     YEAR    CLAIM_STATUS   no_of_claims
 1  2019-01       4               1
 1  2019-01       5               1
 1  2019-02       4               1
 1  2019-02       5               1
 1  2019-03       4               6
 1  2019-03       5               2
 1  2019-04       5               1
 1  2019-04       6               1
 1  2019-05       5               2
 1  2019-06       4               1
 1  2019-06       5               1

Here claim_STATUS status 4 means claim is rejected I need to find percentage of claims rejected for each Id1 at each year where percentage of claims rejected is calculated like
claim-status-4/(claim-status-4+claim-status-5+claim-status-6)

in above table claim rejected percentage is (1/(1+6+3))*100 = 10%
I need to convert above dataframe into output given below:
Id1   YEAR_MO    % of claims rejected
1   2019-01         50%
1   2019-02         50%
1   2019-03         75%
1   2019-04         0%
1   2019-05         0%
1   2019-06         50%

A: Test column claim_STATUS and assign back, aggregate sum and last divide columns:
print (df.assign(CLAIM_STATUS = df['CLAIM_STATUS'].eq(4).mul(df['no_of_claims'])))
    Id1     YEAR  CLAIM_STATUS  no_of_claims
0     1  2019-01             1             1
1     1  2019-01             0             1
2     1  2019-02             1             1
3     1  2019-02             0             1
4     1  2019-03             6             6
5     1  2019-03             0             2
6     1  2019-04             0             1
7     1  2019-04             0             1
8     1  2019-05             0             2
9     1  2019-06             1             1
10    1  2019-06             0             1

df = (df.assign(CLAIM_STATUS = df['CLAIM_STATUS'].eq(4).mul(df['no_of_claims']))
        .groupby(['Id1','YEAR'], as_index=False).sum())

print (df)
   Id1     YEAR  CLAIM_STATUS  no_of_claims
0    1  2019-01             1             2
1    1  2019-02             1             2
2    1  2019-03             6             8
3    1  2019-04             0             2
4    1  2019-05             0             2
5    1  2019-06             1             2

#used pop for divide and drop columns
df['% of claims rejected'] = df.pop('CLAIM_STATUS').div(df.pop('no_of_claims')).mul(100)
print (df)
   Id1     YEAR  % of claims rejected
0    1  2019-01                  50.0
1    1  2019-02                  50.0
2    1  2019-03                  75.0
3    1  2019-04                   0.0
4    1  2019-05                   0.0
5    1  2019-06                  50.0

EDIT:
For better debugging si possible use:
df = (df.assign(new = df['CLAIM_STATUS'].eq(4).mul(df['no_of_claims']))
        .groupby(['Id1','YEAR'], as_index=False).sum())

print (df)
   Id1     YEAR  CLAIM_STATUS  no_of_claims  new
0    1  2019-01             9             2    1
1    1  2019-02             9             2    1
2    1  2019-03             9             8    6
3    1  2019-04            11             2    0
4    1  2019-05             5             2    0
5    1  2019-06             9             2    1

df['% of claims rejected'] = df['new'].div(df['no_of_claims']).mul(100)
print (df)
   Id1     YEAR  CLAIM_STATUS  no_of_claims  new  % of claims rejected
0    1  2019-01             9             2    1                  50.0
1    1  2019-02             9             2    1                  50.0
2    1  2019-03             9             8    6                  75.0
3    1  2019-04            11             2    0                   0.0
4    1  2019-05             5             2    0                   0.0
5    1  2019-06             9             2    1                  50.0

df = df.drop(['no_of_claims','CLAIM_STATUS','new'], axis=1)
print (df)
   Id1     YEAR  % of claims rejected
0    1  2019-01                  50.0
1    1  2019-02                  50.0
2    1  2019-03                  75.0
3    1  2019-04                   0.0
4    1  2019-05                   0.0
5    1  2019-06                  50.0


text:
Q: Oracle database installation version enforcing stricter SQL rules on group by function Recently I copied an Oracle database from one machine to another.

*

*Original: Oracle Database 10g Enterprise Edition Release 10.2.0.3.0

*Copy: Oracle Database 11g Express Edition Release 11.2.0.2.0 - Production
For some reason the following query works on the original but not on the copy.

If a t.tdt_id is substituted in place of tdt_id in the group by the query works (as per td_tablespaces t )
Can someone explain why this is and if it has something to do with the installation. The data is the exact same in both.
SELECT
    tdt_name as "name",
    tdt_contents as "Content",
    tdt_status as "Status",
    round(( subsize.SubSize_MB ), 2 ) as "size used",
    round(( sum( MaxMB ) - subsize.SubSize_MB ), 2 ) as "size free"
FROM
    td_tablespaces t
INNER JOIN
    (
        SELECT
            tdt_id,
            CASE
                 WHEN upper( d.df_autoextend ) = 'YES' THEN  round(( sum( df_maxsize ) / 1024 ), 2 )
                 WHEN upper( d.df_autoextend ) = 'NO' THEN round(( Sum( df_size ) / 1024 ), 2 )
            END as MaxMB
        FROM
            td_datafiles d
        GROUP BY
            tdt_id,
            d.df_autoextend,
            df_maxsize,
            df_size
    ) sub
ON
    t.tdt_id = sub.tdt_id
INNER JOIN
    (
        SELECT
            tdt_id,
            sum( df_size / 1024 ) -( df_free / 1024 ) SubSize_MB,
        df_free      / 1024 SubSize_Free
        FROM
            td_datafiles df
        GROUP BY
            tdt_id,
            df_free
    ) subsize
ON
    t.tdt_id = subsize.tdt_id
WHERE
    ins_id   = 2096
GROUP BY
    tdt_id,
    tdt_name,
    tdt_contents,
    tdt_status,
    subsize.SubSize_MB,
    SubSize_Free
ORDER BY tdt_contents

A: I don't think this is 'stricter rules', I think this is a side effect of improved query optimisation. In oracle 11, the optimizer may try to perform group by actions before certain joins in order to minimize the number of rows joined.
See pages 19-20 here for details http://www.oracle.com/technetwork/database/bi-datawarehousing/twp-upgrading-10g-to-11g-what-to-ex-133707.pdf

A: Oracle enforces strict rules when referencing columns in a query and will raise ORA-00918: column ambiguously defined if a column is found on two tables and referenced without a table prefix or an alias.
Since tdt_id is defined both in t and subsize, you couldn't call tdt_id without an alias or a table name in:

*

*the SELECT clause

*the WHERE clause

*the ORDER BY clause

For some reason in some versions of 10g the error is not raised when the column is in a GROUP BY clause. This is inconsistent with the rest of the syntax parsing, this could lead to ambiguous results and must have been classified as a bug. This has been corrected in 11g.


text:
Q: Android parse json tree I have tree JSON-structured data.
Something like
{
"result": [
    {
        "id": 1,
        "name": "test1"
    },
    {
        "id": 2,
        "name": "test12",
        "children": [
            {
                "id": 3,
                "name": "test123",
                "children": [
                    {
                        "id": 4,
                        "name": "test123"
                    }
                ]
            }
        ]
    }
]

}
model:
class DataEntity {
    int id;
    String name;
    List<DataEntity> childDataEntity;
}

Parsing via org.json
    List<DataEntity> categories = new ArrayList<DataEntity>();

private List<DataEntity> recursivellyParse(DataEntity entity, JSONObject object) throws JSONException {
    entity.setId(object.getInt("id"));
    entity.setName(object.getString("name"));
    if (object.has("children")) {
        JSONArray children = object.getJSONArray("children");
        for (int i = 0; i < children.length(); i++) {
            entity.setChildDataEntity(recursivellyParse(new DataEntity(), children.getJSONObject(i)));
            categories.add(entity);
        }
    }
    return categories;
}

call
  JSONObject jsonObject = new JSONObject(JSON);
        JSONArray jsonArray = jsonObject.getJSONArray("result");
        for (int i = 0; i < jsonArray.length(); i++) {
            recursivellyParse(new DataEntity(), jsonArray.getJSONObject(i));
        }

But this way is wrong. After execution of the method List filled out same data.
How do I parse it right?
UPD: update JSON.

A: Here is Full Demo How to Parse json data as you want.
String JSON = "your json string";
  ArrayList<DataEntity> finalResult = new ArrayList<>();

  try {
                JSONObject main = new JSONObject(JSON);

                JSONArray result = main.getJSONArray("result");

                for(int i=0;i<result.length();i++){
                    DataEntity dataEntity = parseObject(result.getJSONObject(i));
                    finalResult.add(dataEntity);
                }

                Log.d("DONE","Done Success");

            } catch (JSONException e) {
                e.printStackTrace();
            }

Create One recursive function to parse object.
public DataEntity parseObject(JSONObject dataEntityObject) throws JSONException {
    DataEntity dataEntity = new DataEntity();
    dataEntity.id = dataEntityObject.getString("id");
    dataEntity.name = dataEntityObject.getString("name");

    if(dataEntityObject.has("children")){
        JSONArray array = dataEntityObject.getJSONArray("children");
        for(int i=0;i<array.length();i++){
            JSONObject jsonObject = array.getJSONObject(i);
            DataEntity temp = parseObject(jsonObject);
            dataEntity.children.add(temp);
        }
    }

    return dataEntity;
}

Model Class
public class DataEntity implements Serializable {
public String id = "";
public String name = "";
ArrayList<DataEntity> children = new ArrayList<>();}

In FinalResult Arraylist you will get all your parse data.

A: Ignoring that the JSON you show is invalid (i'm going to assume that's a copy/paste problem or typo), the issue is that you've declared your categories List as a member of whatever object that is.
It's continually getting added to on every call to recursivellyParse() and that data remains in the list. Each subsequent call from your loop is seeing whatever previous calls put in it.
A simple solution to this as your code is written would be to simply add a second version that clears the list:
private List<DataEntity> beginRecursivellyParse(DataEntity entity,
                                      JSONObject object) throws JSONException {

    categories.clear();
    return recursivellyParse(entity, object);
}

Then call that from your loop.


text:
Q: Why would I get a 401 when retrieving someone's public profile I am trying to retrieve someone's profile, but it throws me a 401. I am pretty puzzled, since it works for quite a few people, but fails for others
401 Not Authorized error: Unauthorized:

This leads to a very poor UX. Any ideas?

A: I've encountered this in the past because the REST API (you don't specify which you're using) returns profiles that are protected in its results. If you simply iterate through them you might end up doing an operation that you can't do without being allowed to see their protected tweets/profile.


text:
Q: Why should I not make a class Serializable? I'm storing some objects in my viewstate and I was wondering if there are any disadvantages to making a class Serializable?
Is it bad practice to make all of the classes Serializable?

A: It is a good practice to make all classes that are actually Serializable as Serializable. I would just use common sense, and set it for those classes that are intended for crossing process boundaries (DTO classes).
So it those classes which:

*

*All their properties are simple types

*And if they have complex properties, their types themselves are serializable

A: Marking it as [Serializable] (or ISerializable) is necessary for anything using BinaryFormatter, which may well include viewstate under the default configuration. As for good vs bad practice... well, most classes don't need to be serialized, and IMO even when they are, using BinaryFormatter is not always the best choice*. And specifically, marking it as both [Serializable] and [DataContract] will cause an exception IIRC.
*=actually, IMO BinaryFormatter is very rarely a good choice, but I might be biased... and I deliberately don't use viewstate ;p

A: Firstly. Avoid viewstate.
Generally serialization (textual) is used for transferring objects.
You should avoid marking any class as serializable that is not a DTO (Data transfer object) or message class. We do this for several reasons. What ever picks up your class in serialized format may not have the method information (which is in the original assembly) of a non DTO class. Secondly, a class may reference a resource (DB connection, file handle, etc) Do NOT serialize these, since de serialization does not re-establish resource connections and state, unless explicitly designed for, but is still a bad idea.
So in summary: Do NOT serialize when you have contextual methods and storing data for a thrid party to use. (Like a service response with methods is a bad idea). And do NOT serialize when the class contains a resource reference. Keep your serializable object clean from methods as much as possible. This might involve a little re factoring into a service type pattern.
Do serialize DTO's and messages.
This is more of a design choice.


text:
Q: Easy way to port environment defined in framed to mdframed? I've been working on environment based on framed package, but wanted to port to mdframed due to fact that it plays better with footnotes and has more features and more active development. The issue is that I do not know mdframed internals or how to create more advanced styles with it. Also, I found the manual lacking in description on how to create advanced styles.
Is there any porting guide/reference for conversion of framed environments to mdframed environments? Or maybe at least ideas for converting this specific environment?
The environment in question is placing a line and one or two of 6 icons on margin. It has separate version for line and set of icons for odd, onepage and even situations, also separate icon sets for frames that fit on page, start of longer frames, middle frames and final frames. Frames could look like this:
icon | ......
     |               ( on this even page, line is placed on left
     |                 and icon on top, because it is start of frame)
     | ......
  ~ page break
       ...... |
              |      ( on this odd page, line is placed on right
              |icon    and icon in middle, because it's internal frame)
              |
       ...... |
  ~ page break
     | ......        ( and here it's on left again,
icon | ......          while ending icon is at bottom of frame)

or differently depending on how they lay out on pages. I got this working like I want. The relevant code looks a little like this (you can skip the %config block, but I placed it for for code to be complete and working) with lines and icons replaced by simpler versions:
\usepackage{framed}

% config
\newcommand\singletopleft{STL}
\newcommand\singletopright{STR}
\newcommand\singlebottomleft{SBL}
\newcommand\singlebottomright{SBR}
\newcommand\firstleft{FL}
\newcommand\firstright{FR}
\newcommand\middleleft{ML}
\newcommand\middleright{MR}
\newcommand\lastleft{LL}
\newcommand\lastright{LR}
\newcommand\decorleft[1]{\vrule height #1 width 0.5pt\hspace{1mm}}
\newcommand\decorright[1]{\hspace{1mm}\vrule height #1 width 0.5pt}

% \mirrorframe{left content}{right content}{minimum height}{content}
\makeatletter
\newcommand\mirrorframe[4]{%
\dimen1=#3\savebox0{#4}\dimen0=\ht0\relax
\ifdim\dimen0<\dimen1%
\dimen2=0.5\dimen1%
\advance\dimen2 by -0.5\dimen0%
\dimen0=\dimen1%
\else\dimen2=0pt\fi
\def\0{\raisebox{\dimen2}{\begin{minipage}[t]{\wd0}\usebox0\end{minipage}}}%
\def\1{\llap{\vbox to \dimen0{#1}\decorleft{\dimen0}}\0}%
\def\2{\0\rlap{\decorright{\dimen0}\vbox to \dimen0{#2}}}%
\ifodd\count0\2\else\if@twoside\1\else\2\fi\fi}
\makeatother

% \begin{mirrortest}[minimum height] ... \end{mirrortest}
\newenvironment{mirrortest}[1][2\baselineskip]{%
\def\FirstFrameCommand{\mirrorframe{\hbox{\firstleft}\vfill}{\hbox{\firstright}\vfill}{#1}}%
\def\MidFrameCommand{\mirrorframe{\vfill\hbox{\middleleft}\vfill}{\vfill\hbox{\middleright}\vfill}{#1}}%
\def\LastFrameCommand{\mirrorframe{\vfill\hbox{\lastleft}}{\vfill\hbox{\lastright}}{#1}}%
\def\FrameCommand{\mirrorframe{\hbox{\singletopleft}\vfill\hbox{\singlebottomleft}}{\hbox{\singletopright}\vfill\hbox{\singlebottomright}}{#1}}%
\MakeFramed{\advance\hsize-\width \FrameRestore}\ignorespaces}{\endMakeFramed}

I use it like this:
\usepackage{lipsum}
\begin{document}
\begin{mirrortest}
\lipsum[1-20]
\end{mirrortest}
\end{document}

The mdframed package internals seems to be a lot more complicated, that's why I don't know yet how to approach the conversion. Any help/directions would be appreciated!


text:
Q: how to convert an user number in days or hours or seconds swiftUI I am new in Swift UI, I am trying to convert a value what I get from a textfiled and picker to convert that in days, minutes or seconds, this is from the tutorial 100 days with swiftUI i am lost because I dont understand how do the operations if someone can help me and explain me a little the code please, thank you.
this is my code

struct ContentView: View {
    @State private var convertir  = 2
    let tipConverciones = ["segundos","minutos","horas","dias"]
    @State private var convertirselection  = 2
    let convertirA = ["segundos","minutos","horas","dias"]
    @State var cantidadconvertir = ""

    var convertidormetodo: Double{
        //Funcion que calcula el total de personas
        let conteocantidad = Double(cantidadconvertir) ?? 0
        let convertirSeleccion = (convertirA)

        return 0
    }

    var body: some View {

        NavigationView{
        Form {
        Section (header: Text("Convertir")) {

        Picker   ("Convertir de", selection: $convertir){
            ForEach(0 ..< tipConverciones.count){
                Text("\(self.tipConverciones[$0])")
            }//ForEach
        }//Picker
        .pickerStyle(SegmentedPickerStyle())
        }//Seccion3

            Section (header: Text("Ingresar Cantidad a convertir"))  {
                  TextField("Ingresa la cuentidad", text: $cantidadconvertir)
                     .keyboardType(.decimalPad)
            }//seccion5

            Section (header: Text("Convertir a")) {

            Picker   ("Convertir de", selection: $convertir){
                ForEach(0 ..< tipConverciones.count){
                    Text("\(self.tipConverciones[$0])")
                }//ForEach
            }//Picker
            .pickerStyle(SegmentedPickerStyle())
            }//Seccion4

            Section{//seccion 4
                            Text("La cantidad convertida es: \(convertidormetodo)")
                       }//seccion 4
            }//Form
            .navigationBarTitle("Convertidor SwiftUI")
        }//Navigation View
    }//body
}//view

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

A: an example of a user input and the desired output would help. But I think what you're looking for is either the dateFormatter or numberFormatter:
https://developer.apple.com/documentation/foundation/dateformatter
https://developer.apple.com/documentation/foundation/numberformatter


text:
Q: How to break out of a while loop and if statement? I need to break out both the while loop and if statement when the the value inside the if statement is great than 0, in turn the code should then break from the while loop.
How can I achieve this?
My code is as follows:
it('x Accordion description should appear after 5 seconds upon being clicked', function(done) {
      //this.timeout(15000);
      //setTimeout(done, 6000);
      var i = 0;
      while (i < 15000) {
          browser.click('#accordion');
          //var timeoutText = browser.getText('#timeout').length;
          var timeoutText = browser.getText('#timeout').length;
          console.log(timeoutText);

            if (timeoutText > 0) {
                  browser.pause(5000);
                  console.log("Pass");
                  break;
                  i++;
            }
      }

Thanks for your help.

A: Use a label to break out
 outer: while (i < 15000) {
    browser.click('#accordion');
    //var timeoutText = browser.getText('#timeout').length;
    var timeoutText = browser.getText('#timeout').length;
    console.log(timeoutText);

    if (timeoutText > 0) {
        browser.pause(5000);
        console.log("Pass");
        break outer;
        i++;
    }
}

A: Would adding the condition to the while statement work?
it('x Accordion description should appear after 5 seconds upon being clicked', function(done) {
      //this.timeout(15000);
      //setTimeout(done, 6000);
      var i = 0;
      var timeoutText = 1;
      while (i < 15000 && timeoutText <= 0) {
          browser.click('#accordion');
          timeoutText = browser.getText('#timeout').length;
          console.log(timeoutText);

            if (timeoutText > 0) {
                  browser.pause(5000);
                  console.log("Pass");
                  i++;
            }
      }

Also, if you don't need to run the while loop, this could be written more simply, for ex.
it('x Accordion description should appear after 5 seconds upon being clicked', function(done) {
      //this.timeout(15000);
      //setTimeout(done, 6000);
      var i = 0;
      var timeoutText = browser.getText('#timeout').length;
      while (i < 15000 && timeoutText <= 0) {
          browser.click('#accordion');
          timeoutText = browser.getText('#timeout').length;
          console.log(timeoutText);
          browser.pause(5000);
          console.log("Pass");
          i++;
      }

A: it('x Accordion description should appear after 5 seconds upon being clicked', function() {
    // http://webdriver.io/api/utility/waitUntil.html
    browser.waitUntil(function () {
      // Your condition to wait:
      browser.click('#accordion');
      return browser.getText('#timeout').length > 0
    },
    15200, // Waiting timeout 15 secs, but actually only 3 clicks will be done
    'expected accordion description should appear after 5 seconds upon being clicked',
    5000) // Pooling interval - each 5 secs
}


text:
Q: embbed html files in golang binary I am working on a golang webproject.
I am using "net/http" and "golang.org/x/net/websocket" packages
Here is a part of my code:
func handleHomePage(responseWriter http.ResponseWriter, request *http.Request)      {
    http.ServeFile(responseWriter, request, "index.html")
}

func main() {
    http.HandleFunc("/", handleHomePage)
}

As you can see, i am serving a file called index.html.
Here is my project architecture:
├── bin
│   └── main
├── index.html
├── pkg
│   └── darwin_amd64
│       └── golang.org
│           └── x
│               └── net
│                   └── websocket.a
└── src
    ├── golang.org
    │   └── x
    │       └── net
    │         .....
    └── main
        └── manager.go

I am compiling  the project with:
go install main

It provide me a main binary file in bin folder but this binary file does not include index.html file.
How can i embed this html file in binary as a resource ?
Thanks


text:
Q: In listing of items with checkbox make only 1 item selected In vuejs 2.6 app I make listing of items with checkbox at left as 1 element must be selected, like:

        <input
            type="checkbox"
            class="custom-control-input"
            id="custom_selected_personal_hostel_bookmark_id"
            name="custom_selected_personal_hostel_bookmark_id"
            v-model="selected_personal_hostel_bookmark_id"
        >
        XX

But if 1 elements is selected then the rest elements are selected too, that is not what I need. How can I do this
keeping in selected_personal_hostel_bookmark_id var ID of selected element?

A: You should use a watcher on the model to remove the first item in the array.
Like so:

  <input type="checkbox" name="vehicle1" value="Bike" v-model="items"> I have a bike

  <input type="checkbox" name="vehicle2" value="Car" v-model="items"> I have a car

  <input type="checkbox" name="vehicle3" value="Boat" v-model="items"> I have a boat

new Vue({
  el: '#app',
  data: {
    items: ['Car']
  },
  watch: {
    items(newVal) {
      // Do nothing f the array is empty or already only has one value
      if (newVal.length <= 1) {
        return
      }

      // Otherwise, remove the first item in the array
      newVal.shift()
    }
  }
})

You can also play with the JSFiddle here.


text:
Q: What is the difference between Docker Swarm and Kubernetes/Mesophere? From what I understand, Kubernetes/Mesosphere is  a cluster manager and Docker Swarm is an orchestration tool. I am trying to understand how they are different? Is Docker Swarm analogous to the POSIX API in the Docker world while Kubernetes/Mesosphere are different implementations? Or are they different layers?

A: Disclosure: I'm a lead engineer on Kubernetes
Kubernetes is a cluster orchestration system inspired by the container orchestration that runs at Google.  Built by many of the same engineers who built that system. It was designed from the ground up to be an environment for building distributed applications from containers. It includes primitives for replication and service discovery as core primitives, where-as such things are added via frameworks in Mesos. The primary goal of Kubernetes is a system for building, running and managing distributed systems.
Swarm is an effort by Docker to extend the existing Docker API to make a cluster of machines look like a single Docker API. Fundamentally, our experience at Google and elsewhere indicates that the node API is insufficient for a cluster API. You can see a bunch of discussion on this here: https://github.com/docker/docker/pull/8859 and here: https://github.com/docker/docker/issues/8781

A: Swarm is a very simple add-on to Docker. It currently does not provide all the features of Kubernetes. It is currently hard to predict how the ecosystem of these tools will play out, it's possible that Kubernetes will make use of Swarm.


text:
Q: Is there a way to execute the second-to-last command that started with a given string? In a project with different makefiles:
$ make -f foo1.make
... ...
$ testing testing
... ...
$ !ma
make -f foo1.make

Good! But then if I by accident do:
$ make -f foo1.make
... ...
$ testing testing
... ...
$ make
make: *** No targets specified and no makefile found.  Stop.

And now I am sad:
$ !!ma
makema
No command 'makema' found, did you mean:
  ... ...

Now I have to pick through all my testing commands with the up arrow like an animal. Unacceptable*!
Is there any way to re-run that full make -f foo1.make command using ! or some variant thereof?
*: I will not even dignify the suggestion that I just retype the entire command with a response!


text:
Q: Touch events seemingly not registering at top of screen I'm seeing very strange behavior within a view.  Here's my layout:
struct EventDetailViewContainer: View {

    let eventID: EventRecord.ID

    @State var event: EventRecord = EventRecord(keyResults: [], text: "", achievesKR: false)
    @State var editing: Bool = true

    var body: some View {
        if #available(iOS 15.0, *) {
            VStack {
                HStack {
                    Spacer()
                    Toggle("Editing", isOn: $editing)
                        .padding()
                }
                EventDetailView(event: $event, editing: $editing)
            }

        } else {
            // Fallback on earlier versions
        }
    }
}

@available(iOS 15.0, *)
struct EventDetailView: View {

    @Binding var event: EventRecord

    @Binding var editing: Bool
    @FocusState var textIsFocused: Bool

    var body: some View {
        VStack {
            TextField(
                "Event text",
                text: $event.text
            )
                .focused($textIsFocused)
                .disabled(!editing)
                .padding()
            DatePicker("Event Date:", selection: $event.date)
                .disabled(!editing)
                .padding()
            Toggle("Goal is Reached?", isOn: $event.achievesKR)
                .disabled(!editing)
                .padding()
            HStack {
                Text("Notes:")
                Spacer()
            }
            .padding()
            TextEditor(text: $event.notes)
                .disabled(!editing)
                .padding()
            Spacer()
        }
    }
}

struct EventRecord: Identifiable, Equatable {

    typealias ID = Identifier

    struct Identifier: Identifiable, Equatable, Hashable {
        typealias ID = UUID
        let id: UUID = UUID()
    }

    let id: ID

    var keyResults: [KeyResult.ID]

    var date: Date
    var text: String
    var notes: String
    var achievesKR: Bool

    init(
        id: ID = ID(),
        keyResults: [KeyResult.ID],
        date: Date = Date(),
        text: String,
        notes: String = "",
        achievesKR: Bool

    ) {
        self.id = id
        self.keyResults = keyResults
        self.date = date
        self.text = text
        self.notes = notes
        self.achievesKR = achievesKR
    }

}

So this works perfectly when I run it as an iPad app, but when I run it on the simulator, the the top toggle doesn't respond to text input.
The strange thing is, when I simply duplicate the toggle, the top one doesn't work and the bottom one works perfectly:
struct EventDetailViewContainer: View {

    let eventID: EventRecord.ID

    @State var event: EventRecord = EventRecord(keyResults: [], text: "", achievesKR: false)
    @State var editing: Bool = true

    var body: some View {
        if #available(iOS 15.0, *) {
            VStack {
                HStack {
                    Spacer()
                    Toggle("Editing", isOn: $editing)
                        .padding()
                }
                HStack {
                    Spacer()
                    Toggle("Editing", isOn: $editing)
                        .padding()
                }
                EventDetailView(event: $event, editing: $editing)
            }

        } else {
            // Fallback on earlier versions
        }
    }
}

It seems like this should be totally unrelated to the touch behavior of the other views.
Btw this is being displayed in the context of a navigation view.
Is there anything that can explain this?  And how can I get it working without adding this extra view on top?
edit: Here's a gif of this behavior being demonstrated.  The two controls are exactly the same, but the lower one responds to touch and the upper one does not.