text:
Q: How to recover from I2C bus collision BCLIF? I posted this a couple of days ago on the Microchip Forum (here) but the only response has been crickets.
The I2C code below works most of the time but occasionally on power-up there is a bus collision (BCLIF) and the I2C module is unable to recover after the BCLIF.
The I2C lines are pulled up by 3.3K ohms.
Using REALICE and breakpoints I can see that i2c_write() resets BCLIF and returns FALSE when BCLIF is set.
I have used a scope to verify that the I2C bus has flat-lined.
Re-initializing the PIC18F25K20 I2C module (see init_i2c() below) when i2c_write() returns FALSE does not help.
The PIC18F25K20 I2C is connected to a single slave device (MCP4018 I2C Digital POT).
I have used this same code on previous PIC18 projects without issue so I replaced the MCP4018 suspecting a bad part but see no difference.
Is there a way to reset the PIC18F25K20 I2C module when it is locked up?
void init_i2c(I2C_BAUD_RATE baud_rate, float freq_mhz)
{
    UINT32 freq_cycle;
    /* Reset i2c */
    SSPCON1 = 0;
    SSPCON2 = 0;
    PIR2bits.BCLIF = 0;
    /* Set baud rate */
    /* SSPADD = ((Fosc/4) / Fscl) - 1 */
    freq_cycle = (UINT32) ((freq_mhz * 1e6) / 4.0);
    if (baud_rate == I2C_1_MHZ)
    {
        SSPADD = (UINT8) ((freq_cycle / 1000000L) - 1);
        SSPSTATbits.SMP = 1;        /* disable slew rate for 1MHz operation */
    }
    else if (baud_rate == I2C_400_KHZ)
    {
        SSPADD = (UINT8) ((freq_cycle / 400000L) - 1);
        SSPSTATbits.SMP = 0;        /* enable slew rate for 400kHz operation */
    }
    else /* default to 100 kHz case */
    {
        SSPADD = (UINT8) ((freq_cycle / 100000L) - 1);
        SSPSTATbits.SMP = 1;        /* disable slew rate for 1MHz operation */
    }
    /* Set to Master Mode */
    SSPCON1bits.SSPM3 = 1;
    SSPCON1bits.SSPM2 = 0;
    SSPCON1bits.SSPM1 = 0;
    SSPCON1bits.SSPM0 = 0;
    /* Enable i2c */
    SSPCON1bits.SSPEN = 1;
}
BOOL i2c_write(UINT8 addr, const void *reg, UINT16 reg_size, const void *data, UINT16 data_size)
{
    UINT16 i;
    const UINT8  *data_ptr, *reg_ptr;

    /* convert void ptr to UINT8 ptr */
    reg_ptr  = (const UINT8 *) reg;
    data_ptr = (const UINT8 *) data;
    /* check to make sure i2c bus is idle */
    while ( ( SSPCON2 & 0x1F ) | ( SSPSTATbits.R_W ) )
        ;
    /* initiate Start condition and wait until it's done */
    SSPCON2bits.SEN = 1;
    while (SSPCON2bits.SEN)
        ;
    /* check for bus collision */
    if (PIR2bits.BCLIF)
    {
        PIR2bits.BCLIF = 0;
        return(FALSE);
    }
    /* format address with write bit (clear last bit to indicate write) */
    addr <<= 1;
    addr &= 0xFE;
    /* send out address */
    if (!write_byte(addr))
        return(FALSE);
    /* send out register/cmd bytes */
    for (i = 0; i < reg_size; i++)
    {
        if (!write_byte(reg_ptr))
            return(FALSE);
    }
    /* send out data bytes */
    for (i = 0; i < data_size; i++)
    {
        if (!write_byte(data_ptr))
            return(FALSE);
    }
    /* initiate Stop condition and wait until it's done */
    SSPCON2bits.PEN = 1;
    while(SSPCON2bits.PEN)
        ;
    /* check for bus collision */
    if (PIR2bits.BCLIF)
    {
        PIR2bits.BCLIF = 0;
        return(FALSE);
    }
    return(TRUE);
}
BOOL write_byte(UINT8 byte)
{
    /* send out byte */
    SSPBUF = byte;
    if (SSPCON1bits.WCOL)       /* check for collision */
    {
        return(FALSE);
    }
    else
    {
        while(SSPSTATbits.BF)   /* wait for byte to be shifted out */
            ;
    }
    /* check to make sure i2c bus is idle before continuing */
    while ( ( SSPCON2 & 0x1F ) | ( SSPSTATbits.R_W ) )
        ;
    /* check to make sure received ACK */
    if (SSPCON2bits.ACKSTAT)
        return(FALSE);
    return(TRUE);
}

A: This same bug seems to ocur on PIC18F26K20/SS (Revision B3) too, also needs to be added to it's errata.

A: I don't know your specifics but I ran into a problem once where the microcontroller was coming out of reset way early (much before Vdd stabilized on the I2C bus).  So the uController started to read / write data before the target could function properly causing all sort of I2C operational issues.

A: This Errata needs to be added to PIC18F25K20 Errata.

PIC18F2455/2550/4455/4550 Rev. A3 Silicon Errata
17 Module: MSSP
It has been observed that following a Power-on Reset, I2C mode may not
initialize properly by just configuring the SCL and SDA pins as either
inputs or outputs. This has only been seen in a few unique system
environments.
A test of a statistically significant sample of
preproduction systems, across the voltage and current range of the
application's power supply, should indicate if a system is susceptible
to this issue.
Work around
Before configuring the module for I2C
operation:

*

*Configure the SCL and SDA pins as outputs by clearing their
corresponding TRIS bits.

*Force SCL and SDA low by clearing the corresponding LAT bits.

*While keeping the LAT bits clear, configure SCL and SDA as inputs
by setting their TRIS bits.

Once this is done, use the SSPCON1 and
SSPCON2 registers to configure the proper I2C mode as before.

A: This errata also helped me with I2C stuck on PIC18F27J53 (but in my case there was also needed unlock of I2C bus blocked by SGP30 device, code example here: https://github.com/esp8266/Arduino/issues/1025#issuecomment-158667929)
I finally decided to implement routine performing restart-unstuck-restart called when start condition fails (code fragment of my I2C stack):
eI2Cerr i2c_do_RUR(void) {
    //performs restart-unstuck-restart
    eI2Cerr   eRetVal;

    eRetVal = i2c_do_restart();
    if (eRetVal == I2C_ERR_TIMEOUT_RSEN_COLLISION) {
        i2c_unstuck(true); //true=performs also I2C bus unlock
        eRetVal = i2c_do_restart();
    }
    return(eRetVal);
}

I2C seems to be stable and working well now.


text:
Q: Convert a list of dates to date range in Angular Using Moment Js I am having a date list like below
let dates = ["2022-12-20", "2022-12-21", "2022-12-22", "2022-12-27", "2022-12-30","2022-12-31", "2023-01-01"];

I would like to convert the date array to a range of dates, as shown in the below output
let result = ["20 Dec - 22 Dec", "27 Dec 2022", "30 Dec - 1 Jan "];

Below is my code:
fun(dates)
{
    let startDate = this.dates[0], endDateIndex = - 1, finalDateString = "", arr = [];
    for (let i = 1; i < dates.length; i++) {

        if (moment(startDate).add(i, 'days').format("YYYY-MM-DD") == moment(dates[i]).format("YYYY-MM-DD")) {
            endDateIndex = i;
        }
        else {
            finalDateString += endDateIndex > 0 ? moment(startDate).format("DD MMM") + " - " +
                moment(dates[endDateIndex]).format("DD MMM") : '';
            if (endDateIndex == -1) {
                finalDateString = finalDateString + " " + moment(startDate).format("DD MMM") + ","
            }
            startDate = dates[i];
            endDateIndex = -1;
        }
    }
    arr.push(finalDateString);
    return arr;
}

In my code, I am getting the wrong result in the date range. Kindly guide me to build logic.

A: You could reduce your dates into date ranges first:
[
  { "start": "2022-12-20", "end": "2022-12-22" },
  { "start": "2022-12-27" },
  { "start": "2022-12-30", "end": "2023-01-01" }
]

Then format the ranges afterwards.

const dates = [
  "2022-12-20", "2022-12-21", "2022-12-22",
  "2022-12-27",
  "2022-12-30", "2022-12-31", "2023-01-01"
];

const parseDate = (date) => moment(date, 'YYYY-MM-DD');

const pushOrSetEnd = (results, last, prev, curr) => {
  if (moment.duration(parseDate(curr).diff(parseDate(prev))).asDays() <= 1) {
      last.end = curr;
    } else {
      results.push({ start: curr });
    }
};

const reduceDatesIntoRanges = (dates) =>
  dates.slice(1).reduce((acc, date) => {
    const last = acc[acc.length - 1];
    pushOrSetEnd(acc, last, last.end ? last.end : last.start, date);
    return acc;
  }, [{ start: dates[0] }]);

const dateRanges = reduceDatesIntoRanges(dates);

const formatDateWithYear = (date) => parseDate(date).format('D MMM YYYY');

const formatDate = (date) => parseDate(date).format('D MMM');

const formatDateRange = ({ start, end }) => `${formatDate(start)} - ${formatDate(end)}`;

const formattedDateRanges = dateRanges.map(dateRange =>
  !dateRange.end ? formatDateWithYear(dateRange.start) : formatDateRange(dateRange));

console.log(formattedDateRanges);
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

<!--

const expected = [
  "20 Dec - 22 Dec",
  "27 Dec 2022",
  "30 Dec - 1 Jan"
];

-->

A: Maybe this will work for you

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
<script>
let dates = ["2022-12-20", "2022-12-21", "2022-12-22", "2022-12-27", "2022-12-30","2022-12-31", "2023-01-01"];
let expectedResult = ["20 Dec - 22 Dec", "27 Dec 2022", "30 Dec - 1 Jan "];

function organizePeriods(dates) {
    let startDate = dates[0], endDateIndex = - 1, finalDateString = "", arr = [], periodLength = 1;
    for (let i = 1; i < dates.length; i++) {
      if (moment(startDate).add(periodLength, 'days').format("YYYY-MM-DD") === moment(dates[i]).format("YYYY-MM-DD"))  {
        periodLength++;
        endDateIndex = i;
        if (i < dates.length - 1) {
          continue
        }
      }
      if (endDateIndex > 0) {
          finalDateString = moment(startDate).format("DD MMM") + " - " + moment(dates[endDateIndex]).format("DD MMM");
        } else if (endDateIndex === -1) {
          finalDateString = moment(startDate).format("DD MMM")
        }
        arr.push(finalDateString);
        startDate = dates[i];
        endDateIndex = -1;
        periodLength = 1;
        finalDateString = ""
    }
    return arr;
}

console.log("result", organizePeriods(dates));
console.log("expected result", expectedResult);
</script>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating text pdf with multiple pages of the UITableView data
Possible Duplicate:
Print all rows of a table view when it's too large to fit on screen

I need to implement a functionality of creating a text pdf with multiple pages of a view that is having UITableView controller.
I am able to create pdf,but with one page only.
The problem is this: I am unable to break the tableView while rendering it to the pdf-context. I am using the following code to do this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

UIGraphicsBeginPDFContextToFile([NSString stringWithFormat:@"%@/test.pdf",documentsDirectory],CGRectMake(0, 0, m_TableView.frame.size.width, m_TableView.frame.size.height), nil);

UIGraphicsBeginPDFPage();
[self.m_TableView.layer renderInContext:UIGraphicsGetCurrentContext()];

UIGraphicsEndPDFContext();

As you can see,I am using self.m_TableView.layer for rendering. I can not break the UITableView layer.
Is there any other way with which I can create pdf with multiple pages from a tableview control??


text:
Q: Show loop content according to value, inside another loop Scenario:
I have a post type portfolio and a custom post type song, and also a custom taxonomy called songs_categories.
Portfolio is inside loop 1 and the songs are in loop 2, which is inside loop 1.
What I need to do is to show the songs in the portfolio but only if the songs category slug (album name) has the actual value of the portfolios post_name (album name).
I can get the values needed but I'm having trouble writing the actual function necessary to do the filtering. Any help is appreciated.

<?php

  $var1 = $post->post_name;
  $my_query = new WP_Query('post_type=song' );

    while ( $my_query->have_posts() ) : $my_query->the_post();

?>

    <?php $terms = get_the_terms( $post->ID , 'songs_categories' );
        foreach ( $terms as $term ) {
            $term_link = get_term_link( $term, 'songs_categories' );
            if( is_wp_error( $term_link ) )
            continue;

        echo "$var1";
        echo "$term->slug";

       } ?>

        <a href="<?php echo get_permalink(); ?>"><?php the_post_thumbnail(); ?>

         h2><?php the_title(); ?>

        <?php
        $autor_name = get_post_meta($post->ID, "_cmb_autor_text", false);
        if ($autor_name[0]=="") { ?>

        <?php } else { ?>

        <?php foreach($autor_name as $autor_name) {
        echo '
'.$autor_name.'
';
        } ?>

    <?php } ?>

<?php endwhile; ?>

<?php endif; endwhile; ?>

<?php endif; // password check ?>

A: just modify your wp_query to include the filters you want
$args= array(
    'post_type'=>'song',
    'category_name'=>$post->post_name
);

$my_query = new WP_Query($args);

Wp_query is quite detailed you should read up on it to get the most from it.
http://codex.wordpress.org/Class_Reference/WP_Query

A: Got the desired result by modifying my query:
<?php

$var1 = $post->post_name;

$args = array(
    'post_type' => 'song',
    'tax_query' => array(
        'relation' => 'OR',
        array(
            'taxonomy' => 'songs_categories',
            'field'    => 'slug',
            'terms'    => $var1,
        ),

    ),
);

$query = new WP_Query( $args );

while ( $query->have_posts() ) : $query->the_post();

?>


text:
Q: Statefulset's replica scheduling questions Is there anyway I can tell Kuberbetes how to schedule the replicas in the statefulset? For example, I have nodes divided into 3 different availability zones (AZ). I have labeled these nodes accordingly. Now I want K8s to put 1 replica in each AZ based on node label. Thanks

A: Pods will always try to be scheduled across different nodes, to achieve what you are looking for you can try to use DaemonSet, which will allow only one of these kind of pods in each node.
Also, you can use anti affinity based on the already scheduled pods in that node.
https://kubernetes.io/docs/concepts/configuration/assign-pod-node/

A: The feature you are looking for is called Pod Anti-Affinity and can be specified as such:
apiVersion: apps/v1
kind: StatefulSet
[..]
spec:
  template:
    spec:
      affinity:
        nodeAffinity: {}
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - podAffinityTerm:
              labelSelector:
                matchLabels:
                  app: myapp
              topologyKey: az
            weight: 100
[..]

Since Kubernetes 1.18, there is also Pod Topology Spread Constraints, which is a nicer way to specify these anti-affinity rules.


text:
Q: DM friends with discord.py I wrote this code that by all means should work. If you can't help me fix it then could someone help me write in in the python discum library?:
from discord.ext import commands
import discord

bot = commands.Bot(command_prefix='!')

@bot.event
async def on_ready():
    for user in bot.user.friends:
        message = "This Message is sent via DM"
        await bot.send_message(user, message)

bot.run("")

and it throws up this eror even though the token is valid.:
   Traceback (most recent call last):
  File "C:\Users\ArtyF\AppData\Roaming\Python\Python39\site-packages\discord\http.py", line 300, in static_login
    data = await self.request(Route('GET', '/users/@me'))
  File "C:\Users\ArtyF\AppData\Roaming\Python\Python39\site-packages\discord\http.py", line 254, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\ArtyF\AppData\Roaming\Microsoft\Windows\Network Shortcuts\HWMonitor\squirm\test.py", line 12, in <module>
    bot.run("ODI5Mzc2MDY2Nzk0ODE1NDk4.YNYJEQ.crJ2GzQZxRkCXy6fsd1zS8lxZCE")
  File "C:\Users\ArtyF\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 723, in run
    return future.result()
  File "C:\Users\ArtyF\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 702, in runner
    await self.start(*args, **kwargs)
  File "C:\Users\ArtyF\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 665, in start
    await self.login(*args, bot=bot)
  File "C:\Users\ArtyF\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 511, in login
    await self.http.static_login(token.strip(), bot=bot)
  File "C:\Users\ArtyF\AppData\Roaming\Python\Python39\site-packages\discord\http.py", line 304, in static_login
    raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001C7D4077940>
Traceback (most recent call last):
  File "C:\Program Files\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Program Files\Python39\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 746, in call_soon
    self._check_closed()
  File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

Process finished with exit code 1

A: I Think To DM Users You Have To Use The User Object!
Example
from discord.ext import commands
import discord

bot = commands.Bot(command_prefix='!')

Token = "Token Here"

@bot.event
async def on_ready():
    for user in bot.user.friends:
        message = "This Message is sent via DM"
        await user.send(message)

bot.run(Token)

A: As you can see, you get the error discord.errors.LoginFailure: Improper token has been passed.. You need to pass an API key to get authenticated.


text:
Q: Is there a way to put const values in a useState({}) I'm pretty new to react, and I'm working on a component where I'm calculating the percentages of values in below useState, so for instance:
    const [data, setData] = useState({ five: 5, four: 4, three: 3, two: 2, one: 1 });
    const [percentage, setPercentage] = useState(0);

   const fields = [
      { name: "five", value: data.five },
      { name: "four", value: data.four },
      { name: "three", value: data.three },
      { name: "two", value: data.two },
      { name: "one", value: data.one }
    ];

 useEffect(() => {
      const per1 = ((data.one) / (data.five + data.four + data.three + data.two + data.one)) * 100;
      setPercentage(per1);

    }, [data]);

I have constants that I created to calculated the amount of ratings for each type of rating for instance: the number of five star, four star, etc. :
    const numRating5 = product.reviews.filter((x) => x.rating === 5);
    const numRating4 = product.reviews.filter((x) => x.rating === 4);
    const numRating3 = product.reviews.filter((x) => x.rating === 3);
    const numRating2 = product.reviews.filter((x) => x.rating === 2);
    const numRating1 = product.reviews.filter((x) => x.rating === 1);

Is there a way for me to put the numRating5, numRating4,.... in their respective positions (five:5, four:4,...) in the useState. I would really appreciate any help or guidance on this. Thank you!

A: You can try something like this:

const product = {
  reviews: [
    {rating: 1},
    {rating: 2},
    {rating: 3},
    {rating: 4},
    {rating: 5},
  ]
};

const getNumRating = (num) => product.reviews.filter((x) => x.rating === num).length;

const numRating5 = getNumRating(5);
const numRating4 = getNumRating(4);
const numRating3 = getNumRating(3);
const numRating2 = getNumRating(2);
const numRating1 = getNumRating(1);

const useState = React.useState;
const useEffect = React.useEffect;

function App() {
  const [data, setData] = useState({
    five: numRating5,
    four: numRating4,
    three: numRating3,
    two: numRating2,
    one: numRating1
  });
  const [percentage, setPercentage] = useState(0);

  useEffect(() => {
      const per1 = (
        data.one / (data.five + data.four + data.three + data.two + data.one)
      ) * 100;
      setPercentage(per1);

    }, [data]);

  return (

      Hello! Percentage = {percentage}

  );
}

ReactDOM.render(<App/>, document.getElementById("root"));

A: you can update the data using setData and pass the object
 setData ({
     five : numRating5,
     four : numRating4,
     three : numRating3,
     two : numRating2,
     one : numRating1,
});

please check: https://reactjs.org/docs/hooks-state.html
for further information


text:
Q: Remove data from RRDTool I have several graphs created by RRDTool that collected bad data during a time period of a couple hours.
How can I remove the data from the RRD's during that time period so that it no longer displays?

A: I had a similar problem where I wanted to discard the most recent few hours from my RRDtool databases, so I wrote a quick script to do it (apologies for the unconventional variable names - coding style inherited from work, sigh):
#!/usr/bin/env python2
"""
Modify XML data generated by `rrdtool dump` such that the last update was at
the unixtime specified (decimal). Data newer than this is simply omitted.

Sample usage::

    rrdtool dump foo.rrd \
       | python remove_samples_newer_than.py 1414782122 \
       | rrdtool restore - foo_trimmed.rrd
"""

import sys

assert sys.argv[1:], "Must specify maximum Unix timestamp in decimal"

iMaxUpdate = int(sys.argv[1])

for rLine in iter(sys.stdin.readline, ''):
    if "<lastupdate>" in rLine:
        # <lastupdate>1414782122</lastupdate> <!-- 2014-10-31 19:02:02 GMT -->
        _, _, rData = rLine.partition("<lastupdate>")
        rData, _, _ = rData.partition("</lastupdate")
        iLastUpdate = int(rData)
        assert iLastUpdate < iMaxUpdate, "Last update in RRD older than " \
                                    "the time you provided, nothing to do"
        print "<lastupdate>{0}</lastupdate>".format(iMaxUpdate)
    elif "<row>" in rLine:
        # <!-- 2014-10-17 20:04:00 BST / 1413572640 --> <row><v>9.8244774011e+01</v><v>8.5748587571e-01</v><v>4.2046610169e+00</v><v>9.3016101695e+01</v><v>5.0000000000e-02</v><v>1.6652542373e-01</  v><v>1.1757062147e+00</v><v>1.6901226735e+10</v><v>4.2023108608e+09</v><v>2.1457537707e+08</v><v>3.9597816832e+09</v><v>6.8812800000e+05</v><v>3.0433198080e+09</v><v>6.0198912250e+06</v><v>2.        0000000000e+00</v><v>0.0000000000e+00</v></row>
        rData, _, _ = rLine.partition("<row>")
        _, _, rData = rData.partition("/")
        rData, _, _ = rData.partition("--")
        rData = rData.strip()
        iUpdate = int(rData)
        if iUpdate < iMaxUpdate:
            print rLine,
    else:
        print rLine,

Worked for me. Hope it helps someone else.

A: If you want to avoid writing and editing of xml file as this may takes few file IO calls(based on how much bad data you have) , you can also read entire rrd into memory using fetch and update values in-memory.
I did similar task using python + rrdtool and i ended up doing :

*

*read rrd in-memory in a dictionary

*fix values in the dictionary

*delete existing rrd file

*create new rrd with same name.

A: Best method I found to do this...

*

*Use RRDTool Dump to export RRD files to XML.

*Open the XML file, find and edit the bad data.

*Restore the RRD file using RRDTool Restore .

A: The only who proposed, what exactly to edit, was RobM. I tried his solution, and it did not work for me in rrdtool 1.4.7
My database uses AVERAGE, MAX and MIN. It contains DERIVE, GAUGE and COMPUTED. Intervals: second (70), minute (70), hour (25), day (367).
My task: delete some last part (typical reason: clock moved back).
I applied RobM's solution: change  to my new end time, delete all  after it. Restored database seemed to be normal. But it did not accept new additions.
I examined a newly created empty database. And I found in it 70 second records with NaN, same for minute and hour.
So, my working solution - if I delete  records in some period end, I add the same number of NaN records in this period beginning, with correctly decreasing times. Exception - daily records, they are only deleted without addition.
If period becomes empty after  deletes, I fill it with NaN records ending to my new end time (rounded to the period boundary).


text:
Q: Twin square-free numbers of the form $6k-1,6k+1$? Is it easy to show (or even known) that there are infinitely many square-free pairs $6k-1,6k+1$?
(Presumably, not disproven yet, since a lot of people would be wasting their time on the twin prime conjecture if it was.)

A: Given a prime $p > 3$, the setf $A_p = \{k \in \mathbb{N}\setminus \{0\} : 6k \equiv \pm 1 \pmod{p^2}\}$ contains exactly two elements in each interval of length $p^2$.
Also, if $n\geq 7$ then $A_p\cap \{1,2,\dots,n\}=\emptyset$ when $p\geq n$, since $p^2\mid 6k\pm 1$ means $6k+1\geq p^2$ which in turn means $k\geq\frac{p^2-1}{6} \geq p+1>n$.
Thus
$$\biggl\lvert\{ 1,\dotsc,n\} \cap \bigcup_{p > 3} A_p\biggr\rvert \leqslant \sum_{3 < p \leqslant n} 2\biggl\lceil \frac{n}{p^2}\biggr\rceil \leqslant 2\pi(n) + 2n\sum_{3 < p\leqslant n} \frac{1}{p^2},$$
and since $\frac{\pi(n)}{n}\to 0$, the natural density of
$$A = \bigcup_{p > 3} A_p$$
is bounded above by
$$\sum_{ p > 3} \frac{2}{p^2} < 2\sum_{k = 2}^\infty \frac{1}{(2k+1)^2} < 1.$$
Hence the natural density of $B = \mathbb{N}\setminus (A\cup \{0\})$ is positive, in particular $B$ is infinite.
(Corrected argument per Thomas Andrews' comment.)


text:
Q: Efficiently returning the next larger value of a non-existing key in scala's sorted collections? In scala, given a sorted map, tree or list, what is the most efficient way to return the next larger value of a non-existing key? Additionally, is it possible to get an "iterator/cursor" starting at this element?
Edit:
I'm happy with any interpretation of "efficiently", e.g. "runtime", "memory usage", "clarity" or "taking the smallest possible amount of programmer time to implement and maintain" (thanks Kevin Wright).

A: Defining "efficiently" as "taking the smallest possible amount of programmer time to implement and maintain"...
For a Sequence:
val s = Seq(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41)
val overSixteen = s dropWhile (_ < 16)

For a Map:
val s = Map(2->"a", 3->"b", 5->"c", 7->"d", 11->"e", 13->"f")
val overSix = s dropWhile (_._1 < 6)

If you prefer an Iterator, just call .iterator on the resulting collection, or you can use .view before dropWhile if you're especially interested in lazy behaviour.

A: If you use a SortedMap, then you can call range on it. Well, sort of. It is broken up to 2.8.1 if you plan to add and/or remove elements from the map afterwards. It should be ok if you avoid these operations, and it has been fixed for upcoming Scala versions as well.


text:
Q: How can I solve HTTP 500 error when installing Wordpress in Elastic Beanstalk? I'm getting a HTTP 500 error when installing Wordpress in AWS Elastic Beanstalk using Codepipeline and Github.
I'm using a new downloaded WordPress with some minor changes in the config file, I tested the Beanstalk with a test index.php file and it worked correctly, I get the error when I substitute the files with the Wordpress Files.

A: I'm posting my own answer because I couldn't find an answer for my specific problem.
I solved this issue by changing my instance type from t1.micro (free tier) to m2.small, it seems that the Wordpress bundle was too big for the bundle.


text:
Q: Edit Text Send Function in chat application i'm creating a narrative game, for that i have a conversation screen.
The user have to choose a predifined message to send it.
The choosen message is transfered inside the Edit Text but to send it, the user have to open the swift keyboard and click on "send".
I want to create a method that automatically send the message after the user choice. (Skip the manual "send" on the keyboard)
I tried TextWatcher :
EditText userInput;
RecyclerView recyclerView;
List<ResponseMessage> responseMessageList;
MessageAdapter messageAdapter;
String[] listChoices;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chapitretest);

  Button btn = (Button) findViewById(R.id.btnChoice);
    btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
              listChoices = new String[]{"Mdr","Lol","xd"};
            AlertDialog.Builder mBuilder= new AlertDialog.Builder(ChapTest.this);
            mBuilder.setTitle("Ton choix:");
            mBuilder.setSingleChoiceItems(listChoices, -1, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    userInput.setText(listChoices[i]);
                    userInput.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {

                        }

                        @Override
                        public void afterTextChanged(Editable s) {

                            String txtbulle = userInput.getText().toString();
                        }
                    });

                    dialogInterface.dismiss();
                }
            });
            AlertDialog mDialog = mBuilder.create();
            mDialog.show();

This is my first app, thank you ;)
Update: Why I use EditText :  (Conversation method)
  userInput = findViewById(R.id.UserInput);

     recyclerView=findViewById(R.id.Conversation);
     responseMessageList = new ArrayList<>();
     messageAdapter=new MessageAdapter(responseMessageList,this);
     recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
     recyclerView.setAdapter(messageAdapter);
    userInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

            if(actionId == EditorInfo.IME_ACTION_SEND){
               ResponseMessage message = new ResponseMessage(userInput.getText().toString(),true);
               responseMessageList.add(message);
               ResponseMessage message2 = new ResponseMessage(userInput.getText().toString(),false);
                responseMessageList.add(message2);
                messageAdapter.notifyDataSetChanged();

                if (!isLastVisible())
                    recyclerView.smoothScrollToPosition(messageAdapter.getItemCount() - 1);
            }
            return false;
        }
    });
}


text:
Q: How to include multiple class files and .Jar files in class path which exist in sub folders in linux? How to include multiple class files and .Jar files in class path , i am on linux  .. and want to integrate lucene packages downloaded with my code , all libraries and class files are in lucene dirc. ( they are multiple sub-directories inside that folder ) ?
HelloLucene.java:1: error: package org.apache.lucene.analysis.standard does not exist
import org.apache.lucene.analysis.standard.StandardAnalyzer;
                                          ^
HelloLucene.java:10: error: package org.apache.lucene.queryparser.classic does not exist
import org.apache.lucene.queryparser.classic.ParseException;
                                            ^
HelloLucene.java:11: error: package org.apache.lucene.queryparser.classic does not exist
import org.apache.lucene.queryparser.classic.QueryParser;
                                            ^
HelloLucene.java:23: error: cannot find symbol
  public static void main(String[] args) throws IOException, ParseException {
                                                             ^
  symbol:   class ParseException
  location: class HelloLucene
    HelloLucene.java:26: error: cannot find symbol
    StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
    ^
  symbol:   class StandardAnalyzer
  location: class HelloLucene
HelloLucene.java:26: error: cannot find symbol
    StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
                                    ^
  symbol:   class StandardAnalyzer
  location: class HelloLucene
HelloLucene.java:45: error: cannot find symbol
    Query q = new QueryParser(Version.LUCENE_40, "title", analyzer).parse(querystr);
                  ^
  symbol:   class QueryParser
  location: class HelloLucene
Note: HelloLucene.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
7 errors

A: Use below command:
export CLASSPATH="$CLASSPATH:xyz.jar**:**path_to_abc.jar.jar"

You basically have to append to the classpath, all the new entries that you want. To do so, just make use of ':' in linux and ';' in windows.

A: You can just add the paths to the folders where the jars are located and recursively the inner jars are picked.


text:
Q: KnockoutJS: Handling Select Boxes. Selecting a default value and removing an existing item I am having trouble handling checkboxes in Knockout JS.
jsfiddle link: http://jsfiddle.net/wenbert/Xyuhk/72/
Note that I have provided 2 select boxes for each parent (Hero). Each one is using a different way but both are more or less "observing" the same object.
Workflow

*

*Click on a gray box

*A box with a blue dotted line should appear containing the items of the Select box.

*From here, you can edit the items of the select box.

*Fiddle here: http://jsfiddle.net/wenbert/Xyuhk/72/
The Problems

*

*When I remove an item, I am not able to remove it from the Select boxes. Note that I do not want to completely remove it from the object. I just want the current item to be flagged as "isDeleted".

*Select A - hides the item but it leaves an empty option in the select box.

*Select B - the "ifnot: isDeleted" is not having any effect on the options.

The Question
How do I handle Select Boxes? I have rendered 2 Select Boxes in 2 different ways to try to have the ifnot: isDeleted take effect but none of them are working.
Update: With this setup, how do I do the "selected" value of the select box?
HTML
<button data-bind="click: addHero">Add Hero</button>

        <input class="big-box" type="text" data-bind="value: name" />
        <button class="btn-small" data-bind="click: $parent.removeHero">Remove Hero</button>

        SKILLS:

        Select A) <select data-bind="foreach: skills">
            <option data-bind="value: name, text: name, ifnot: isDeleted"></option>
        </select>
        Select B) <select data-bind="options: skills, optionsText: 'name', value: selected_skill.name, ifnot: isDeleted">
        </select>

        (Step 1: Click somewhere here)

    Edit Skill:

        <button class="btn-small" data-bind="click: addSkill">Add Skill</button>

                <button class="btn-small" data-bind="click: $parent.setAsDefaultSkill">Set as default</button>
                <input data-bind="value: name" />
                <button class="btn-small" data-bind="click: $parent.removeSkill">Remove Skill</button>

        (Step 2: Remove a Skill, then have a look at the Select Box above.)

Javascript
var initialData = [
    {
        id: '1',
        name: "Batman",
        isDelete: false,
        selected_skill: {name: "Boxing", isDeleted: false},
        skills: [
            { id: '1', name: "Karate", isDeleted: false },
            { id: '2', name: "Boxing", isDeleted: false},
            { id: '6', name: "Sonar", isDeleted: false}
        ]
    },
    {
        id: '2',
        name: "Hulk",
        isDelete: false,
        skills: [
            { id: '3', name: "MMA", isDeleted: false },
            { id: '4', name: "Rage", isDeleted: false},
            { id: '5', name: "Extra Strength", isDeleted: false}
        ]
    },
];

function Hero(data) {
    var self = this;
    self.name = ko.observable(data.name);
    self.selected_skill= ko.observable(data.selected_skill);
    self.skills = ko.observableArray(ko.utils.arrayMap(data.skills, function(i) {
        return new Skills(i);
    }));

    self.addSkill = function() {
        self.skills.push(new Skills({name: '---', isDeleted: false}));
    }

    self.setAsDefaultSkill = function(item) {
        self.selected_skill(item);
    }

    self.isDeleted = ko.observable(data.isDeleted);

    self.removeSkill = function(item) {
        item.isDeleted(true);
    }
}

function Skills(data) {
    var self = this;
    self.name = ko.observable(data.name);
    self.isDeleted = ko.observable(data.isDeleted);
}

function SuperheroViewModel(data) {
    var self = this;
    self.heroes = ko.observableArray(ko.utils.arrayMap(data, function(i){
        return new Hero(i);
    }));

    self.selectedHero = ko.observable();
    self.selectedHero.skills = ko.observableArray();

    self.addHero = function() {
        self.heroes.push(
            new Hero({
                name: 'Wolverine',
                isDelete: false,
                skills: [{name: 'Breathing', isDeleted: false}],
            })
        );
    }

    self.selectHero = function(item) {
        self.selectedHero(item);
    }

    self.removeHero= function(item) {
        item.isDeleted(true);
    }
}

ko.applyBindings(new SuperheroViewModel(initialData ));

I hope everything is clear.
Any reply will be greatly appreciated.
THanks!

A: I would do the filtering in the viewmodel. So I would create a filtered collection something like availableSkills
self.availableSkills = ko.computed(function() {
    return ko.utils.arrayFilter(self.skills(), function(item) {
        return !item.isDeleted();
    })
});

And then I would use this in the selects:
<select data-bind="foreach: availableSkills">
     <option data-bind="value: name, text: name"></option>
</select>

Demo fiddle.


text:
Q: How to calculate the ⌉ operator? In a book about finance, the following formula appears:
$$\large a_{10 \,⌉\, 0.04}$$
What is this ⌉ operator and how to read / calculate it?

A: This just a notation in Actuarial sciences
$a_{\overline{n|}i} := v + v^2 + \cdots + v^n = \frac{1-v^n}{i}$
,      where $v:=\frac{1}{i+1}$
Read this to know all notation of Actuarial sciences:
Click Here

So,
$a_{\overline{10|}0.04}=\frac{1-(1+0.04)^{-10}}{0.04} \approx 8.111$


text:
Q: Grails: Spring's @Transactional annotations are ignored sometimes In the example below, I successfully fall into the end point - mandatory() - although one of two mutually exclusive @Transactional annotations must throw an exception: whether Propagation.NEVER or Propagation.MANDATORY. But the code is executed successfully.
How could that be?!
A couple (not all) of my services are affected by that and I'd like to understand what is the cause.
class NewService {

static transactional = true

boolean process() {
    return never()
}

@Transactional(propagation = Propagation.NEVER)
boolean never() {
    return mandatory()
}

@Transactional(propagation = Propagation.MANDATORY)
boolean mandatory() {
    // successfully breakpointed here o_O
    return true
}
}

Grails 2.2.0

A: It looks like you are bypassing the bean proxy, as Burt Beckwith (Slide 23) called it "Unintentionally bypassing the bean proxy".
You need to get proxy and execute your method on that.
@Transactional(propagation = Propagation.NEVER)
boolean never() {
    def myproxy= grailsApplication.mainContext.newService
    return myproxy.mandatory()
}

@Transactional(propagation = Propagation.MANDATORY)
boolean mandatory() {
    // successfully breakpointed here o_O
    return true
}

A: Spring declarative transactions are AOP-based. And Spring AOP is proxy-based. This means that the transactional annotation is read and taken into account when a bean is called from another bean, through a proxy:
Bean A --> injected transactional proxy --> Bean B

In your case, you call another ethod of the same bean directly. The transactional proxy is thus not aware of this call, and thus can't enforce the presence of a transaction:
Bean A --> this


text:
Q: Polymer2.0 - Looking for json format icon - { } using paper icon I was looking for json format icon from the polymer iron icons list which is not available
something similar to http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons/high-resolution-dark-blue-denim-jeans-icons-alphanumeric/072287-high-resolution-dark-blue-denim-jeans-icon-alphanumeric-bracket-curley.png
I am tried below workaround but it didnt work either
<paper-icon-button id="json">{}</paper-icon-button>

https://codepen.io/nagasai/pen/rwqYYZ
<head>
<base href="https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/">
<link rel="import" href="polymer/polymer.html">
<link rel="import" href="paper-icon-button/paper-icon-button.html">
<link rel="import" href="iron-icons/iron-icons.html">
<div class="toolbar">
</head>

<body>
      <paper-icon-button id="json">{}</paper-icon-button>
      <paper-icon-button id="save" icon="icons:save"></paper-icon-button>
</body>

A: <paper-icon-button> has a src property to specify the URL of the desired image. You could even specify the .png URL you indicated in the question, like this:
<paper-icon-button src="http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons/high-resolution-dark-blue-denim-jeans-icons-alphanumeric/072287-high-resolution-dark-blue-denim-jeans-icon-alphanumeric-bracket-curley.png"></paper-icon-button>

codepen


text:
Q: How can I disable SFTP so that FTP is the only daemon open? In sshd_config I've commented out:
Subsystem sftp /usr/lib/openssh/sftp-server
but sftp is still working. What am I missing?

A: Port 22 is SSH/scp/SFTP. Port 21 is ftp. vsftpd handles FTP/FTPS, not SFTP. They are different protocols, and everything is like it's meant to be.


text:
Q: Howto model named parameters in method invocations with Scala macros? There are use cases where it is useful to create a copy of an object which is an instance of a case class of a set of case classes, which have a specific value in common.
For example let's consider the following case classes:
case class Foo(id: Option[Int])
case class Bar(arg0: String, id: Option[Int])
case class Baz(arg0: Int, id: Option[Int], arg2: String)

Then copy can be called on each of these case class instances:
val newId = Some(1)

Foo(None).copy(id = newId)
Bar("bar", None).copy(id = newId)
Baz(42, None, "baz").copy(id = newId)

As described here and here there is no simple way to abstract this like this:
type Copyable[T] = { def copy(id: Option[Int]): T }

// THIS DOES *NOT* WORK FOR CASE CLASSES
def withId[T <: Copyable[T]](obj: T, newId: Option[Int]): T =
  obj.copy(id = newId)

So I created a scala macro, which does this job (almost):
import scala.reflect.macros.Context

object Entity {

  import scala.language.experimental.macros
  import scala.reflect.macros.Context

  def withId[T](entity: T, id: Option[Int]): T = macro withIdImpl[T]

  def withIdImpl[T: c.WeakTypeTag](c: Context)(entity: c.Expr[T], id: c.Expr[Option[Int]]): c.Expr[T] = {

    import c.universe._

    val currentType = entity.actualType

    // reflection helpers
    def equals(that: Name, name: String) = that.encoded == name || that.decoded == name
    def hasName(name: String)(implicit method: MethodSymbol) = equals(method.name, name)
    def hasReturnType(`type`: Type)(implicit method: MethodSymbol) = method.typeSignature match {
      case MethodType(_, returnType) => `type` == returnType
    }
    def hasParameter(name: String, `type`: Type)(implicit method: MethodSymbol) = method.typeSignature match {
      case MethodType(params, _) => params.exists { param =>
        equals(param.name, name) && param.typeSignature == `type`
      }
    }

    // finding method entity.copy(id: Option[Int])
    currentType.members.find { symbol =>
      symbol.isMethod && {
        implicit val method = symbol.asMethod
        hasName("copy") && hasReturnType(currentType) && hasParameter("id", typeOf[Option[Int]])
      }
    } match {
      case Some(symbol) => {
        val method = symbol.asMethod
        val param = reify((
          c.Expr[String](Literal(Constant("id"))).splice,
          id.splice)).tree
        c.Expr(
          Apply(
            Select(
              reify(entity.splice).tree,
              newTermName("copy")),
            List( /*id.tree*/ )))
      }
      case None => c.abort(c.enclosingPosition, currentType + " needs method 'copy(..., id: Option[Int], ...): " + currentType + "'")
    }

  }

}

The last argument of Apply (see bottom of above code block) is a List of parameters (here: parameters of method 'copy'). How can the given id of type c.Expr[Option[Int]] be passed as named parameter to the copy method with the help of the new macro API?
In particular the following macro expression
c.Expr(
  Apply(
    Select(
      reify(entity.splice).tree,
      newTermName("copy")),
    List(/*?id?*/)))

should result in
entity.copy(id = id)

so that the following holds
case class Test(s: String, id: Option[Int] = None)

// has to be compiled by its own
object Test extends App {

  assert( Entity.withId(Test("scala rulz"), Some(1)) == Test("scala rulz", Some(1)))

}

The missing part is denoted by the placeholder /*?id?*/.

A: Here's an implementation that's also a little more generic:
import scala.language.experimental.macros

object WithIdExample {
  import scala.reflect.macros.Context

  def withId[T, I](entity: T, id: I): T = macro withIdImpl[T, I]

  def withIdImpl[T: c.WeakTypeTag, I: c.WeakTypeTag](c: Context)(
    entity: c.Expr[T], id: c.Expr[I]
  ): c.Expr[T] = {
    import c.universe._

    val tree = reify(entity.splice).tree
    val copy = entity.actualType.member(newTermName("copy"))

    val params = copy match {
      case s: MethodSymbol if (s.paramss.nonEmpty) => s.paramss.head
      case _ => c.abort(c.enclosingPosition, "No eligible copy method!")
    }

    c.Expr[T](Apply(
      Select(tree, copy),
      params.map {
        case p if p.name.decoded == "id" => reify(id.splice).tree
        case p => Select(tree, p.name)
      }
    ))
  }
}

It'll work on any case class with a member named id, no matter what its type is:
scala> case class Bar(arg0: String, id: Option[Int])
defined class Bar

scala> case class Foo(x: Double, y: String, id: Int)
defined class Foo

scala> WithIdExample.withId(Bar("bar", None), Some(2))
res0: Bar = Bar(bar,Some(2))

scala> WithIdExample.withId(Foo(0.0, "foo", 1), 2)
res1: Foo = Foo(0.0,foo,2)

If the case class doesn't have an id member, withId will compile—it just won't do anything. If you want a compile error in that case, you can add an extra condition to the match on copy.

Edit: As Eugene Burmako just pointed out on Twitter, you can write this a little more naturally using AssignOrNamedArg at the end:
c.Expr[T](Apply(
  Select(tree, copy),
  AssignOrNamedArg(Ident("id"), reify(id.splice).tree) :: Nil
))

This version won't compile if the case class doesn't have an id member, but that's more likely to be the desired behavior anyway.

A: This is the solution of Travis where all parts are put together:
import scala.language.experimental.macros

object WithIdExample {

  import scala.reflect.macros.Context

  def withId[T, I](entity: T, id: I): T = macro withIdImpl[T, I]

  def withIdImpl[T: c.WeakTypeTag, I: c.WeakTypeTag](c: Context)(
    entity: c.Expr[T], id: c.Expr[I]
  ): c.Expr[T] = {

    import c.universe._

    val tree = reify(entity.splice).tree
    val copy = entity.actualType.member(newTermName("copy"))

    copy match {
      case s: MethodSymbol if (s.paramss.flatten.map(_.name).contains(
        newTermName("id")
      )) => c.Expr[T](
        Apply(
          Select(tree, copy),
          AssignOrNamedArg(Ident("id"), reify(id.splice).tree) :: Nil))
      case _ => c.abort(c.enclosingPosition, "No eligible copy method!")
    }

  }

}


text:
Q: How to initialize project when it is imported I have an eclipse plugin and a custom project type. When the project is created through the wizard i can do as much setup code as i want. While using the plugin an .xml file is created containing plugin specific information about some resources inside the project.
Now when the project is checked into a versioning system the xml file is included. When someone checks out the project into eclipse again i would have to read the .xml file and apply the information to the resources again.
Is there a place where i can put code that is executed when a project of my custom project nature is beeing imported from somewhere else ?

A: You could use an IResourceChangeListener to listen for resource changes.
Your listener should get an IResourceDelta for the project with the 'kind' flag set to IResourceDelta.ADDED.


text:
Q: Alternative of OffsetByXY method of mapXtreme in PostGIS I have an application in MapXtreme. I am converting that into PostGIS.For a purpose I am using the below given function in Mapxtreme.
IGeometryEdit geomEdit = ftrgeo.GetGeometryEditor();
geomEdit .OffsetByXY(-(Convert.ToDouble(300) / 2), -(Convert.ToDouble(300) / 2), DistanceUnit.Foot, DistanceType.Spherical);
geomEdit .EditingComplete();

What are the alternative methods of above in PostGIS?
Any Idea?

A: Without understanding exactly what this function does, I think you want ST_Translate

Returns a new geometry whose coordinates are translated delta x,delta y,delta z units. Units are based on the units defined in spatial reference (SRID) for this geometry.

ST_Translate — Translate a geometry by given offsets.

Synopsis
geometry ST_Translate(geometry g1, float deltax, float deltay);
geometry ST_Translate(geometry g1, float deltax, float deltay, float deltaz);


text:
Q: How should I prove $\Box (\Box p \rightarrow q) \vee \Box (\Box q \rightarrow \Box p)$ using KT45. How am I supposed to prove the same using natural deduction? I started my proof with a LEM
$$\Box (\Box p \rightarrow \Box q) \vee \neg \Box (\Box p \rightarrow \Box q)$$
I split the LEM via $\vee$ elimination, take the part before the $\vee$, and then add $\Box (\Box q \rightarrow p)$ by $\vee$ introduction.
Now for the part after the $\vee$ in the LEM. How am I supposed to use it to reach my conclusion?  I tried by assuming $\neg \Box \Box (q \rightarrow p)$, my intention being that I would able to prove it wrong and thereby proving $\Box \Box (q \rightarrow p)$ being true, and thereafter is trivial.
Any help on this problem is highly appreciated.


text:
Q: Unable to convert string into date in tMap component Talend I have gone through some similar questions but those solutions didn't worked for me I am having a date field which is String of timestamp "1631898440" I tried converting this string into date using tMap but got this error - java.lang.RuntimeException: java.text.ParseException: Unparseable date: "1631898440".
The function I am using -
row5.mydatecolumn!=null && !"".equalsIgnoreCase(row5.mydatecolumn)? TalendDate.parseDateLocale("EEE MMM dd HH:mm:ss zzz yyyy", row5.mydatecolumn, "EN") :null

Also tried -
TalendDate.parseDate("ddMMyyyy",row5.mydatecolumn)

In this I am getting this err- timestamp out of range: "898442-07-16 00:00:00+05:30"ERROR
How to resolve this issue is there anything wrong with the format of date?

A: In your user routine  just create a fonction like this :
 public static Date Convert_String_To_Date(String String_Timestamp) {

        SimpleDateFormat sf = new SimpleDateFormat("ddMMyyyy");
        Date date = new Date(Long.parseLong(String_Timestamp));
        System.out.println("*** Date Converted to this patter ddMMyyyy : "+sf.format(date));
        return TalendDate.parseDate("ddMMyyyy",sf.format(date)) ;
    }

don't forget the import
import java.text.SimpleDateFormat;
import java.util.Date;

then for me i just put a tjava component where i called my fonction like below
String str = "1631898440";
System.out.println(Format_String_Date.Convert_String_To_Date(str)) ;

So , in your case you would call this fonction in your tMap like this i guess :
row5.mydatecolumn!=null && !"".equalsIgnoreCase(row5.mydatecolumn)?
Format_String_Date.Convert_String_To_Date(row5.mydatecolumn) :null

Here is the output
[statistics] connected
*** Date Converted to this patter ddMMyyyy : 19011970
Mon Jan 19 00:00:00 CET 1970
[statistics] disconnected


text:
Q: Sharing a devotion? Someone told me that this phrase is grammatically incorrect, but I do not understand why?

XYZ is a fellowship of adults sharing a devotion to encourage students.

A: It's not ungrammatical in itself, but there is a subtle shift in meaning if a different verb form is used. The sentence as stated probably doesn't mean what is intended.
Consider

*

*XYZ is a fellowship of adults sharing a devotion to encourage students

*XYZ is a fellowship of adults sharing a devotion to encouraging students

The first indicates that the students are encouraged because the adults share an [unspecified] devotion. The second indicates that the object of the devotion is the students' encouragement.
I suspect that the second sense is what is intended. For that, the verb form is wrong: it needs to be a gerund. A devotion is to a noun of some sort.


text:
Q: how to unfocus datagridview in winform I have some buttons, one textbox and a datagridview on a winform.
and i want when form show in the screen to put cursor on the textblock,
for this i use txtName.Focus().
But everytime when the from loads textbox doesn't focus,
indeed dagaridview takes a focus on itself.
how to solve it.

A: You should set the TabIndex property of the controls in your form (your TextBox for example should have the lowest TabIndex so that when the form loads it will automatically have focus )

A:    private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.TabStop = false;
            textBox1.TabIndex = 0;
        }

hope its help

A: Simply change the tabindex property of your controls.
Pay attention to use directly the tabindex property, because, if you have controls contained in other controls (groupbox or panels) it could be misleading.
Use the menu View and the TabOrder tool.
Put your textbox first in the taborder. No need to code anything

A: You have to make sure that the page has been loaded before giving the textbox focus.  Therefore, add an event for the Form's Load event.
You can do this on the designer, or in the code behind like so:
this.Load += new EventHandler(Form1_Load);

During the loading event, call Select on your textbox.
private void Form1_Load(object sender, EventArgs e){
    txt_Name.Select();
}

The Select command can choose how much of the text you select.  For example, select the first letter starting a index 0 would be txt_Name.Select(0,0).  More info at the
MSDN.
Alternatively, you can use the tabindex property to 0 to ensure it gets focus first (as per ionden).


text:
Q: Where is Spring ResourceSupport I'm reading Spring in Action 5th. and to add hateoas hyperlink. this class is extending org.springframework.hateoas.ResourceSupport however I cannot find it. i'm using Spring Boot version 2.2.5.RELEASE
import org.springframework.hateoas.ResourceSupport;
import tacos.Taco;

@Relation(value = "taco", collectionRelation = "tacos")
public class TacoResource extends ResourceSupport {

    private static final IngredientResourceAssembler ingredientAssembler = new IngredientResourceAssembler();

    @Getter
    private final String name;

So what's the name of this class in this version since the source code was using an older versio I think 2.0.2 M1

A: Below is from the Spring HATEOAS documentation

The ResourceSupport/Resource/Resources/PagedResources group of classes never really felt appropriately named. After all, these types do not actually manifest resources but rather representation models that can be enriched with hypermedia information and affordances. Here's how new names map to the old ones:
ResourceSupport is now RepresentationModel
Resource is now EntityModel
Resources is now CollectionModel
PagedResources is now PagedModel

So since Spring HATEOAS 1.0, ResourceSupport is RepresentationModel
Spring also has provided a migration script which can help in replacing the legacy Spring HATEOAS type references with the new ones.


text:
Q: Iterating through two dictionaries I have two dictionaries:
dict_1 = {'H1':[0,1,3,2],
          'H2':[5,4,2,1,5],
          'H3':[1,2,5]}

dict_2 = {'H1':[[1,4,3,2],
                [6,5,3,2],
                [1,4,3,2]],
          'H2':[[0,0,1,6,3],
                [2,1,4,2,1],
                [5,1,2,5,3]],
          'H3':[[2,3,4],
                [2,1,4],
                [0,1,2]]}

I'm trying to iterate through the items in the values of the keys in dict_1, and check if any of those items are in any of the items in the values of the corresponding key in dict_2. Then print the value, and the index where it was found in the key of dict_2.
So for example, because 0 in the list of the key 'H1' of dict_1 isn't found in any of the lists of the key 'H1' in dict 2, nothing would be printed. Now if we check for 1, then
1, 'H1', 0, # because there is a one in the first list of 'H1' of dict_2
1, 'H1', 2, # because there is a one in the 3rd list of 'H1' of dict_2

here 1 corresponds to the item that was checked for, 'H1'  the key that was checked, and 0, and 2 represent which list the 1 was found in in dict_2
this is what I have:
for i in range(3):
    for k,v in dict_1.items():
        for x,y in dict_2.items():
            if k == x:
                for j in v:
                    if j in y[i]:
                        print j,x,i

But I'm wondering if this will take care of everything, or if it will print repeated items?

A: This should work:
for key, d1_list in dict_1.iteritems():
    for element in d1_list:
        for ind, d2_list in enumerate(dict_2[key]):
            if element in d2_list:
                print element, key, ind

Iterate over all the key, and lists and d1.  Then over element in d1_list, and finally check if it's any any of the lists in dict_2 corresponding to the same key.

A: Some answers first: yes, your code will "take care of everything", and will not "print repeated items" meaning that if a value is appearing several time in the same list in dict_2, than it will be spotted only once by your code.
Executing your code on those dict demonstrates this:
dict_1 = {'H1':[0,1,3,2]}

dict_2 = {'H1':[[0,0],
            [1,2]]}

for i in range(2):
    for k,v in dict_1.items():
        for x,y in dict_2.items():
            if k == x:
                for j in v:
                    if j in y[i]:
                        print j,x,i

Output is:
0 H1 0
1 H1 1
2 H1 1

Hence spotting only once the 0 value while appearing twice in first sublist in dict_2.
Now, to complete the same objective, we can simplify a little your code, given that:

*

*you want to compare only the same keys in the two dicts

*you may want to have different size of list in dict_2

I would propose the following:
# Loop on all key values in dict_1
for k,v in dict_1.items():
    # Loop only on values in dict_2 for same key
    for i,y in enumerate(dict_2[k]):
        # Loop over values in first list
        for j in v:
            # Assert existence in second list
            if j in y:
                # Display result if found (note that index of subblist in dict_2 is retrieved through enumerate function
                print j,x,i

This output the exact same result with additional lisibility and flexibility for dict_2 format.
Hope this helps.


text:
Q: c++ random numbers, evenly distributed I need to generate random numbers between two values in c++, which can be generated like that(in a range 1 to 6)
:
#include <iostream>
#include <random>

int main(int argc, char* argv[]){
 srand(time(NULL));

for (int j = 0; j < 6 ; j++) {
    randomNumber = rand() % 6 + 1;
    cout << randomNumber;

return 0;
}

But I also need to ensure that it generates at least once each number in the range, for example: range [1,6], you must generate at least once the 1,2,3,4,5 and 6.
And there is another thing, the numbers generated, must be evenly distributed, like if want generate 20 iterations in range of[1,6], each number(1,2,3,4,5,6) should have approximately the same quantity generated at 20 iterations. Example: 1,3,5,2,4,6,2,4,6,1,3,5,6,5,4,3,5,2,1.... and not like this: 1,3,5,6,6,6,2,6,4,4,4,4,4,4...
If anyone knows how to solve this, I'll be very grateful to you.
Thanks!!!

A: This is where the C++ Standard Library comes to the rescue. Typed off the top of my head:
#include <random>

int get_rand_in_1_6()
{
  static std::random_device rnd;
  return std::uniform_int_distribution <int> ( rnd )( 1, 6 );
}

The result will be uniformly-distributed.
(You may not get one of each in the first six iterations, though. Being uniformly distributed does not guarantee any specific values in any specific sub-interval, only that the number is just as likely as any other to appear. Given enough iterations, you will see that.)
[edit 2]: IDR the exact mathematical formula for minimum number of iterations to guarantee that you see each number at least once — I am wildly guessing around 15 for the minimum number of pulls to guarantee that.

A: If I understand correctly, std::shuffle might help you:
std::random_device rd;
std::mt19937 gen(rd());
int numbers[] = {1, 2, 3, 4, 5, 6};

for (int j = 0; j < 20 ; j++) {
    if (j % 6 == 0) { std::shuffle(numbers, numbers + 6, gen); }
    std::cout << numbers[j % 6];
}

Demo
You have then sequence of random permutations.


text:
Q: How to match subdomain with gorilla mux I need to build a route which matches two subdomains(prefix.api.example.com and prefix.api.sandbox.example.com) using gorilla mux router. So far I have the regex below but the router returns 404 on requests. Any idea why is that?
router := mux.NewRouter()
route :=  router.Host(`prefix.api{_:(^$|^\.sandbox$)}.example.com`)

More code
package main

import(
    "github.com/gorilla/mux"
    "net/http"
)

type handler struct{}

func (_ handler)ServeHTTP(w http.ResponseWriter, r *http.Request){
    w.Write([]byte("hello world"))
    w.WriteHeader(200)

}
func main() {
    router := mux.NewRouter().StrictSlash(true)
    route :=  router.Host(`prefix.api{_:(^$|^\.sandbox$)}.example.com`)
    route.Handler(handler{})
    http.Handle("/", router)
      panic(http.ListenAndServe(":80", nil))
}

Request:
$ curl prefix.api.sandbox.example.com/any -v
*   Trying 127.0.0.1...
* Connected to prefix.api.sandbox.example.com (127.0.0.1) port 80 (#0)
> GET /some HTTP/1.1
> Host: prefix.api.sandbox.example.com
> User-Agent: curl/7.43.0
> Accept: */*
>
< HTTP/1.1 404 Not Found
< Content-Type: text/plain; charset=utf-8
< X-Content-Type-Options: nosniff
< Date: Wed, 01 Jun 2016 22:08:21 GMT
< Content-Length: 19
<
404 page not found
* Connection #0 to host prefix.api.sandbox.example.com left intact

A: The ^ and $ metacharacters for matching beginning and end of lines should be removed, the parens can be as well.
route := router.Host(`prefix.api{_:|\.sandbox}.example.com`)`

My hosts file:
○ grep prefix /etc/hosts
127.0.0.1   prefix.api.example.com
127.0.0.1   prefix.api.sandbox.example.com
127.0.0.1   prefix.api.xsandbox.example.com

Gives me the following:
○ curl prefix.api.example.com:8000
hello world%
○ curl prefix.api.sandbox.example.com:8000
hello world%
○ curl prefix.api.xsandbox.example.com:8000
404 page not found

Updated:
Here are the regexes generated by the two different .Host()'s:
route :=  router.Host(`prefix.api{_:(^$|^\.sandbox$)}.example.com`)

regexp: ^prefix\.api(?P<v0>(^$|^\.sandbox$))\.example\.com$
route := router.Host(`prefix.api{_:|\.sandbox}.example.com`)

regexp: ^prefix\.api(?P<v0>|\.sandbox)\.example\.com$

*

*Example tests for both regexes can be played with
here at play.golang


text:
Q: Select rows based on closest date while meeting additional criteria in R I have a dataset that looks like this:
data <- read.table(text = "OID      Local_date      Dateincide      Join_Count      TARGET_FID      JOIN_FID        indiv_code      indiv_name      sex     month       year        treatment       perturbati      xx      yy      id_treatme      id_treat_1      lion_month      treatment_      OID_hc      DateRecord      Year_1      location        village     Longhomest      Lathomeste      Longitude       Latitude        Animalslos      Specieslos
3   2015-10-25  2008-01-15  1   127415  2   NGAaF1  Ngamo_Urchin    F   10  2015    E   A   547514.43970000000  7883074.46200000000 11  11E NGAaF1_10_2015  11E_NGAaF1_10_2015  3   19-02-08    2008    E   Nganyana    548505  7881998 547800  7883200 4   cattle
3   2016-01-18  2008-01-15  1   128429  2   NGAaF1  Ngamo_Urchin    F   1   2016    E   A   547461.30170000000  7882858.82600000000 11  11E NGAaF1_1_2016   11E_NGAaF1_1_2016   3   19-02-08    2008    E   Nganyana    548505  7881998 547800  7883200 4   cattle
3   2016-02-23  2008-01-15  1   128858  2   NGAaF1  Ngamo_Urchin    F   2   2016    E   A   547395.24460000000  7883056.29100000000 11  11E NGAaF1_2_2016   11E_NGAaF1_2_2016   3   19-02-08    2008    E   Nganyana    548505  7881998 547800  7883200 4   cattle
3   2015-10-25  2008-01-15  1   130659  2   NGAaF1  Ngamo_Urchin    F   10  2015    E   A   547514.43970000000  7883074.46200000000 12  12E NGAaF1_10_2015  12E_NGAaF1_10_2015  3   19-02-08    2008    E   Nganyana    548505  7881998 547800  7883200 4   cattle
3   2016-01-18  2008-01-15  1   131673  2   NGAaF1  Ngamo_Urchin    F   1   2016    E   A   547461.30170000000  7882858.82600000000 12  12E NGAaF1_1_2016   12E_NGAaF1_1_2016   3   19-02-08    2008    E   Nganyana    548505  7881998 547800  7883200 4   cattle
3   2016-02-23  2008-01-15  1   132102  2   NGAaF1  Ngamo_Urchin    F   2   2016    E   A   547395.24460000000  7883056.29100000000 12  12E NGAaF1_2_2016   12E_NGAaF1_2_2016   3   19-02-08    2008    E   Nganyana    548505  7881998 547800  7883200 4   cattle", header = TRUE)

Each row is a record with a code "OID", a "Local_date", "Dateincide" and other attributes. I have missing data which right now is not coded as NA but left blank. The original data set is large and it has 120,000 rows and 40 columns, which is why I am trying to find an R code that will do the following in the most efficient way:
I want to go through the OID values and for all the rows that share the same OID to look for the row for which "Dateincide" is closest (either before or after) to the "Local_date". Then to write "Keep" for these rows with the closest date in a new column named "Keep/delete".
There is a condition though: There are rows that will have the same OID and will have the same "Local_date", so it seems like in some cases there will be two or more records that are the same match. I want to keep all of these matches not just one, because they represent different records according to the column "id_treat_1".
The output that I want is the following (I have made it short to make it clear but I want to keep all the rest of the columns as well):
OID Local_date  Dateincide  keep/delete id_treat_1
3   2015-10-25  2008-01-15  keep        11E
3   2016-01-18  2008-01-15  delete      11E
3   2016-02-23  2008-01-15  delete      11E
3   2015-10-25  2008-01-15  keep        12E
3   2016-01-18  2008-01-15  delete      12E
3   2016-02-23  2008-01-15  delete      12E
13  2011-11-08  2008-02-14  keep        7E

So there are 2 records with the same OID= 3 that have been labelled "keep" because they have the closest date in "Local_date" to "Dateincide" and they have a different value in the "id_treat_1" column. In the case of the record with OID 13 the row with the closest date was picked and there is only one because there wasn't another match that had a different value in the "id_treat_1" column.
Any help on how to compute this "Keep/delete" column that would allow for multiple matches and how to deal with the missing data will be very much appreciated!

A: You need to convert your dates into POSIXct so you can subtract them. You can then use dplyr to create the keep/delete column.
library(dplyr)
data$Local_date <- as.POSIXct(data$Local_date,
                                format='%Y-%m-%d')
data$Dateincide <- as.POSIXct(data$Dateincide,
                                format='%Y-%m-%d')
data %>%
  group_by(OID) %>%
   mutate(keep.delete =
        ifelse(Local_date - Dateincide == min(Local_date - Dateincide), 'keep', 'delete'))

#     OID Local_date Dateincide id_treat_1 keep.delete
#  (int)     (time)     (time)      (dbl)       (chr)
#1     3 2015-10-25 2008-01-15         11        keep
#2     3 2016-01-18 2008-01-15         11      delete
#3     3 2016-02-23 2008-01-15         11      delete
#4     3 2015-10-25 2008-01-15         12        keep
#5     3 2016-01-18 2008-01-15         12      delete
#6     3 2016-02-23 2008-01-15         12      delete

Regarding your id_treat_1 constraint, you can save the above as a new data frame (say data3) and then do
data3$keep.delete[duplicated(data3)] <- 'delete'


text:
Q: How to detect failed downloads using yfinance I am using the API yfinance: https://github.com/ranaroussi/yfinance
With the simple code below:
data = yf.download("A AA AAA Z LOL KE QP")

I got the following output:
[*********************100%***********************]  7 of 7 completed

2 Failed downloads:
- LOL: 1d data not available for startTime=-2208988800 and endTime=1621954979. Only 100 years worth of day granularity data are allowed to be fetched per request.
- QP: 1d data not available for startTime=-2208988800 and endTime=1621954979. Only 100 years worth of day granularity data are allowed to be fetched per request.

I would like to know how can I detect in my code that "LOL" and "QP" failed?

A: This is the code where the 'error' is thrown in the yfinance package. This is not an actual error so you might want to override the function download which is quite big.
if shared._ERRORS:
    print('\n%.f Failed download%s:' % (
    len(shared._ERRORS), 's' if len(shared._ERRORS) > 1 else ''))
    # print(shared._ERRORS)
    print("\n".join(['- %s: %s' %
    v for v in list(shared._ERRORS.items())]))

Edit

If found a way to get the failed download:
simply import the shared.py file and get the ERRORS dict.
This dict stores the last errors of the download method. It is reset before a download so it is accessible right after it.
Simply use the following code:
import yfinance.shared as shared

data = yf.download("A AA AAA Z LOL KE QP")
print(list(shared._ERRORS.keys()))

A: After playing a little bit more with the data output I found a non-elegant way of checking for failed values, for example for the element "LOL":
all(pd.isna(v) for v in dict(data.Close["LOL"]).values())

It check if all values are nan for the closing price.
This method is working, but not optimal I think, there might be a better and simpler way of doing it. Lets hope someone find it :)


text:
Q: Android app does not connect via socket.io Android app does not connect via socket.io, but via browser everything is fine. If I access via browser http://localhost:3000, it works, but when I run the android app nothing happens and there is no error message either. Note: I am using nodejs.
MainActivity.java
package com.security.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.net.URISyntaxException;
import io.socket.client.IO;
import io.socket.client.Socket;

public class MainActivity extends AppCompatActivity {

    public Socket socket;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //I created a ddns domain for external access directing to the nodejs
        server port 3000
        try {
            socket = IO.socket("http://my_domain_ddns:3000");
            socket.connect();

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

node.js
const express = require('express');
const path = require('path');

const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);

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

app.set('views', path.join(__dirname, 'public'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.use('/', (req, res) => {
    res.render('index.html');
});

io.on('connection', socket => {

    console.log(`Socket conectado: ${socket.id}`);

});

server.listen(3000);

index.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="with=device-with, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Chat</title>

    <link rel="stylesheet" href="styles.css">

    <form id="chat">
        <input type="text" name="username" placeholder="Digite seu usuario">

        <input type="text" name="message" placeholder="Digite sua mensagem">
        <button type="submit">Enviar</button>
    </form>

I have corrected the url in index.html
var socket = io('http://my_domain_ddns:3000');

A: Change localhost in your android by the public IP of your router.
Do a port forwarding from your router to your server.
Check that your server has the port where you do your forwarding is open.
This video  video give more explanation.

A: Well, I found another way that worked.
private void initiateSocketConnection() {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(SERVER_PATH).build();
        webSocket = client.newWebSocket(request, new SocketListener());

   }

build.grade
implementation 'com.squareup.okhttp3:okhttp:3.10.0'


text: Q: Create Custom Path Macros in Visual Studio I would like to create custom Path Macros in Visual Studio. I know there is another topic on this but that one only works for Visual C++ projects. I'm not writting a C++ project so the Property Manager isn't available.


text:
Q: Scroll to y location within react element with useRef I have an component on my page that scrolls, but the rest doesn't. I want to scroll to a certain Y location within this element, when I change a useState value using a different component.
const scrollMe = useRef();

useEffect(
        () => {
                if (scrollMe === true) {
                    scrollPanel.scrollTo(0, 300)
                }

        },
        [ scrollMe ]
    );

The scrollable component is like so:

 handleScroll(e)}>A mapped array

The scroll function is as follows:
const handleScroll = (e) => {
    if (e.target.scrollTop !== 0) {
        setTopBarPosition(true);
    } else {
        setTopBarPosition(false);
    }
};

Setting the topBarPosition affects
<div className={`topBar ${topBarPosition === true ? 'topBarToTop' : ''}`}>
                    <TopBar/>

And the css class topBarToTop moves the topBar to the top of the page:
.topBarToTop {
    top: 30px;
}

How come I just get scrollMe.scrollTo is not a function ?
I made a codesandbox that illustrates what I'm trying to do:
https://codesandbox.io/s/react-hooks-counter-demo-izho9

A: You need to make some small changes, Please follow the code comments:
  useEffect(() => {
    // swap the conditions to check for childRef first
    if (childRef && topPosition) {

      // use to get the size (width, height) of an element and its position
      // (x, y, top, left, right, bottom) relative to the viewport.
      const { y } = childRef.current.getBoundingClientRect()

      // You have to call `current` from the Ref
      // Add the `scrollTo()` second parameter (which is left)
      childRef.current.scrollTo(y, 0)

      // Initially it was set to `false` and we change it to `true` when click on scroll
      // button then we change it back to `false` when re-render
      setTopPosition(false)

    }
  }, [topPosition, childRef])

More about getBoundingClientRect()


text:
Q: Date Timestamps and datetime64[ns, UTC] comparison in python pandas I'm quite confused because of effect of this filtering process using pandas DataFrames. I'm trying to get rows that are in between some dates but my result DataFrame is empty. I'm sure data is there in that period.
df.info() returning that 'opentime' is type: `opendate 440383 non-null datetime64[ns, UTC]
Code snippet:
from datetime import timedelta
from datetime import datetime

current_date = pd.datetime.now()
t_delta_week = timedelta(days=7)
t_delta_year = timedelta(days=365)

#CurrentDate
date_start2020 = pd.Timestamp(current_date - t_delta_week, unit='ms')
date_end2020 = pd.Timestamp(current_date, unit='ms')

date_start2020 = date_start2020.tz_localize('utc')
date_end2020 = date_end2020.tz_localize('utc')

#LastYearDate
date_start2019 = pd.Timestamp(current_date - t_delta_year - t_delta_week, unit='ms')
date_end2019 = pd.Timestamp(current_date - t_delta_year, unit='ms')

date_start2019 = date_start2019.tz_localize('utc')
date_end2019 = date_end2019.tz_localize('utc')

df2020_2019['opendate'] = pd.to_datetime(df2020_2019['opendate'], unit='ms')
mask = (df2020_2019['opendate'] > date_start2020) & (df2020_2019['opendate'] <= date_end2020)
df_currYear = df2020_2019.loc[mask]

df_currYear

The returned DataFrame is empty
Thanks for help! :)
EDIT:
Maybe that could help: 'opendate' is generated column and is created using this code fragment:
import pandas as pd
fmt = '%Y-%m-%dT%H:%M:%S'
df2020_2019.dropna(subset=['opentime_TS'], inplace=True)
df2020_2019['opendate'] = pd.to_datetime(df2020_2019['opentime_TS'], utc=True, format=fmt, errors='ignore')

Additionally I've put some head() prints of
data sample. I'm cannot provide record of df, because of privacy :)

A: Ok, my bad. I've just get mind-blind because of focus on tz TypeErrors... I've taken wrong datasource that is already outdated :) Final solution which works with proper data:
from datetime import timedelta
from datetime import datetime
import pandas as pd

fmt = '%Y-%m-%dT%H:%M:%S'
df2020_2019.dropna(subset=['opentime_TS'], inplace=True)
df2020_2019['opendate'] = pd.to_datetime(df2020_2019['opentime_TS'], utc=True, format=fmt, errors='ignore')
df2020_2019.info()

current_date = pd.Timestamp.now()
t_delta_week = timedelta(days=7)
t_delta_year = timedelta(days=365)

#CurrentDate
date_start2020 = pd.Timestamp(current_date - t_delta_week, unit='ms')
date_end2020 = pd.Timestamp(current_date, unit='ms')

date_start2020 = date_start2020.tz_localize('utc')
date_end2020 = date_end2020.tz_localize('utc')

#LastYearDate
date_start2019 = pd.Timestamp(current_date - t_delta_year - t_delta_week, unit='ms')
date_end2019 = pd.Timestamp(current_date - t_delta_year, unit='ms')

date_start2019 = date_start2019.tz_localize('utc')
date_end2019 = date_end2019.tz_localize('utc')

df2020_2019['opendate'] = pd.to_datetime(df2020_2019['opendate'], unit='ms')

df_currYear = df2020_2019[df2020_2019["opendate"] > date_start2020]
df_lastYear = df2020_2019[df2020_2019["opendate"].between(date_start2019, date_end2019)]

df_currYear


text:
Q: If $\beta$ is a basis of $V$ then does that mean that $V=span{\beta}$? I am confused with the definition of 'basis'.
A basis $\beta$ for a vector space $V$ is a linearly independent subset of $V$ that generates $V$. And span($\beta$) is the set consisting of all linear combinations of the vectors in $\beta$. So from my understanding, just because all vectors in $V$ can be generated by $\beta$ doesn't necessarily mean that V=span($\beta$), since there might exist $b\in span(\beta)$  s.t. $b\notin V$ But I have learned that if $W\leq V$ and $\beta$ is a basis for both $V, W$, then $V=W$ since $W=V=span(\beta)$. ($V, W$ are finite dimensional vector space) This seems to imply that a vector space is equal to the span of its basis, which contradicts my understanding of its definition.  I'd like to know which part of my understanding above is flawed.

A: Yes, it is true that $$V = \text{span}\ \beta$$
To address your concern, suppose $\beta = \{v_1,v_2,\ldots,v_n\}$. If $b\in\text{span}\ \beta$, then $b = \alpha_1v_1 + \ldots + \alpha_nv_n$ for scalars $\alpha_1,\alpha_2,\ldots,\alpha_n$. Since $V$ is a vector space, and $v_1,v_2,\ldots,v_n \in V$, $\alpha_1v_1 + \ldots + \alpha_nv_n\in V$. This is from vector space axioms!
Not only is a vector space a span of its basis, but the basis of a vector space is also oftentimes defined as a minimal spanning set! In other words, the basis of a vector space (finite-dimensional) is a set of minimal/least possible size, such that the span of vectors in this set is exactly the entire space $V$.

A: Since $V$ is the whole space, the possibility "there might exist $b\in\operatorname{span}(\beta)$  s.t. $b\notin V$" isn't real. So, $V$ being generated by $\beta$ is the same thing as $V=\operatorname{span}(\beta)$.


text:
Q: Set closed under composition of a continuous function Determine the sets $S=\left \{ f+C|C\in \mathbb{R} \right \}$ which are closed under composition, where $f:\mathbb{R}\rightarrow \mathbb{R}$ is a continuous function.
Sadly, I have no idea on how to solve it.

A: Pick a function $f$ satisfying the conditions.
We can assume that $f(0)=0$.
Now notice that $f\circ f$ must also be in $S$.
We conclude $(f\circ f)(x)-(f\circ f)(0)=f(x)-f(0)$ for all $x$.
therefore $f\circ f(x) = f(x)$ for all x.
Let $A$ be the image of $f$. Clearly every element of $A$ is a fixed point, in fact the image of $A$ coincides with set of fixed points of $A$.
Because of IVT we have that $A$ is an interval. And because $A$ is the preimage of $\{0\}$ under the continuous function $f(x)-x$ we have that $A$ is closed.
We show that $A$ is either a point or all of $\mathbb R$.
Suppose that $A$ is not a point, notice there is an $a\in A$ and $\epsilon>0$ such that $a+\epsilon\in A$. We will prove that $A$ does not have a maximum element, suppose $b$ is the maximum element.
Consider the composition $f\circ(f+\epsilon)$. Notice that when evaluating it at $a$ we get $f(a+\epsilon)=a+\epsilon$. therefore $f\circ(f+\epsilon)=f+\epsilon$. But this is not true, because the image of $f+\epsilon$ is $A+\epsilon$ (this set contains $b+\epsilon$), while the image of $f\circ(f+\epsilon)$ is clearly contained in $A$ and thus does not contain $b+\epsilon$.
A similar argument shows that $A$ does not have a minimum, thus $A=\mathbb R$.
Clearly when $A$ is a point we have $A=\{0\}$ and when $A=\mathbb R$ we must have that $f(x)=x$.
Conclusion: the functions that work are $f(x)=c$ and $f(x)=x+c$

A: If $f$ is constant, then $S$ is the set of all constant functions and closed under composition.
If $f$ is of the form $f(x)=x+a$, then one also verifies that $S$ is closed under composition.
To see that there are no other solutions, let $f$ be any function with the desired property.
By picking $C=-f(0)$, we find a $g\in S$ with $g(0)=0$.
As $g\circ g\in S$, there exists $C'$ with $g(g(x))=f(x)+C'$ for all $x$. In particular $g(g(0))=f(0)+C'$ implies $C'=-f(0)=C$.
We conclude $g\circ g=g$.
Also, for any $y$, the map $x\mapsto g(g(x)+y)-g(y)$ maps $0$ to $0$, hence must be $g$. Hence
$$ g(g(x)+y)=g(x)+g(y).$$
Thus if $A:=g(\Bbb R)=\{\,g(x)\mid x\in\Bbb R\,\}$ and $h\in A$, then $g(x+h)=g(x)+h$.
Trivially, $0\in A$, and by the Intermediate Value Theorem, $A$ must be connected, i.e., either $A=\{0\}$ or for suitable $a>0$, we have $[0,a)\subset A$ or $(-a,0]\subset A$.

*

*In the first case, $g$ is identically zero, which corresponds to our first solution: constant functions.

*In the second case, let $B=\{\,x\in\Bbb R\mid g(x)=x\,\}$.
We know $[0,a)\subset B$.
In fact, if $0<h<a$ then $x\in B\iff x+h\in B$. We conclude that $B$ is an open set. But $B$ is also closed. Therefore $B=\Bbb R$ and $g$ is the identity function.

*The third case works similar.


text:
Q: Is this not a contradiction in propositional logic (when translated)? I saw this statement, 'If you see me you won't'.
At face value I assumed this proposition was a contradiction. When translated to propositional logic, is this not a contradiction?
I could see it, rather, as a contingent proposition due to the difference in won't and don't:
Let $p$ = 'You see me'
Hence, $\neg p$ can be translated to, 'You do not see me' in English.
$\neg p$ thus holds a different truth value to the claim, 'You will not see me'.
Hence, the compound proposition, 'If you see me you won't', cannot be translated as:
$p$ $\implies$ $\neg p$, $\space$ can it?
But rather, something like $p \implies \neg q$, such that $q$ = 'You will see me'.
Here, the proposition is contingent.
Basic it might be, but I still want the confirmation.

A: Apart from your concern with the difference in tense (seeing now verses not seeing later, and I agree with your distinction concerning that), let me just respond to the title question. No, the propositional assertion $$p\to\neg p$$ is not a contradiction. Rather, this assertion is logically equivalent to $\neg p$, which you can see by computing the truth table. For me to say: "if you'll see me, then you won't" is another way of me saying "you won't see me."

A: No, this is not a contradiction: $p \rightarrow \neg p$ is equivalent to $\neg p$:
$p \rightarrow \neg p \overset{Implication}{\Leftrightarrow} \neg p \lor \neg p \overset{Idempotence}{\Leftrightarrow} \neg p$


text:
Q: Want to disable the whole class after i checked the check box I want to disable the whole class after i checked the check box.
I'm having 2 options "upgrade now " and "upgrade later".
If i check upgrade Later, I'll get the options to time picker to scheduling the time.
If i check upgrade now then the schedule picker should be disabled.
How can i disable the whole class?
Below code is for the check box:

                                        <input type="checkbox" id="vcenter-1" name="vcenter-1" value="1">

                                        Upgrade Now

                                        <input type="checkbox" id="vcenter-2" name="vcenter-2" value="1">

                                        Upgrade Later

below code is for time picker:

Update schedule for all selected

                                date
                                <input class="date-picker form-control" ng-click="open($event)" datepicker-popup="{{format}}" ng-model="dt" is-open="opened" min-date="minDate" max-date="'2015-06-22'" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" type="text">

                                Time
                                <input class="time-picker" type="text" name="" value="10:00 PM">

                                expected completion
                                Tuesday, Oct 7, 2014 - 2:00 AM

A: Please refer the following code,
<!doctype html>

  <meta charset="UTF-8">
  <title>Example - example-checkbox-input-directive-production</title>

<form name="myForm" ng-controller="ExampleController">
  Upgrade Now: <input type="checkbox" ng-model="value1">

  Upgrade Later: <input type="checkbox" ng-model="value2">

Time picker

 </form>

This will give you appropriate output.


text:
Q: What's wrong with my liquibase changelog? I'm trying to learn how to use liquibase to update my database schema if MySQL. I've created an empty schema in the Workbench and in my spring project I have:
application.properties (resources package):
spring.liquibase.enabled=true
spring.liquibase.change-log=classpath:db/changelog/changelog-master.yaml
spring.datasource.url=jdbc:mysql://localhost:3306/practice
spring.datasource.username=maxim
spring.datasource.password=123456
spring.jpa.hibernate.ddl-auto=update

In this file I'm sure about url, username, password and path to changelog-master are correct.
My changelog-master.yaml is in (resources/db/changelog package)
databaseChangeLog:
  - include:
      file: changelog_1.yaml
      relativeToChangelogFile: true

And finally, my changelog_1.yaml(resources/db/changelog package):
databaseChangeLog:
  - changeSet:
      id: 1
      author: maxim
      changes:
        - createTable:
            tableName: Device
            columns:
              - column:
                  name: id
                  type: BIGINT
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: name
                  type: VARCHAR
                  constraints:
                    nullable: false

When I try to execute the program, I get:
liquibase.exception.ValidationFailedException: Validation Failed:1 change sets check sum
          classpath:db/changelog/changelog_1.yaml::1::maxim was: 8:8896ac0d055b8ae982733866bc5682b1 but is now: 8:1e0167b7454bbfa9b38e2c11740cadee

Is there a way of fixing it?

A: I changed spring.jpa.hibernate.ddl-auto in my application.properties file to 'create-drop' and it worked


text:
Q: python underscore function name I was reading the django article on form validatin here and i came across this
ValidationError(_('Invalid value'), code='invalid')

my question is what does the _('Invalid value') does?

A: _ is often associated with internationalization
might be duplication of Mercurial/Python - What Does The Underscore Function Do?

A: it's for translation purpose
you should see this at the begining of the script
from django.utils.translation import ugettext as _

you can see a complete explanation in the doc


text:
Q: Could the acts_as_tenant Rails gem suffer from race conditions? The acts_as_tenant gem sets the tenant based on subdomain upon each request.
If a user hits a page on a different tenant at the perfect moment... is it possible for another person's action to save to an incorrect tenant?

A: AaT uses RequestStore (https://github.com/steveklabnik/request_store?source=c) to store the current tenant at the middleware level.
As far as i'm aware this makes AaT immune to the type of race conditions you describe.


text:
Q: handle time picker with hour, minute, am, pm and time I am creating a time picker for fun. I could create a time picker which can be selected and show the selected time. User can select am or pm either. But for now I could save the time as '09:30' format only rather I want to show '09:30 am' or '09:30 pm' format. How do I handle am, pm, hour and minutes separately because in my time picker I have shown hour, minutes and am, pm separately and merged one is shown as the title so I can use that time for sending to the server if I want in future. How do I handle such?
Here is a workaround I have created for now
Can anyone help me at this?
https://codesandbox.io/s/lpyqy3mo99
Here is the code too
class TimePicker extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      time: this.convertTime(props.time),
      hourTime: this.convertTime(props.time),
      selectedNumber: 1,
      meridian: "am",
      minutes: this.calculateMinutes(props.time),
      hasError: false
    };
  }

  convertTime = time => {
    const splittedTime = time && time.split(":");
    const hour = splittedTime && splittedTime[0];
    if (hour > 12) {
      // const hour = time.split(':')[0];
      const momentInstance = moment(time, "hhmm");
      const twelveHourTime = momentInstance.format("h:mm");
      console.log("twelveHourTime", twelveHourTime);
      return twelveHourTime;
    }

    return props.time;
  };

  calculateMinutes = time => {
    const splittedTime = time && time.split(':');
    return splittedTime[1];
  }

  handleClick(time) {
    const { meridian, minutes } = this.state;
    const hourTime = moment(`${time}:${minutes}`, [
      "hhmm"
    ]).format("h:mm");
    this.setState(
      {
        time,
        selectedNumber: time,
        hourTime
      },
      () => this.props.onClick(hourTime)
    );
  }

  handleTimeAmPm(meridian) {
    const { time, minutes } = this.state;
    // const hourTime = moment(`${time}:${minutes} ${meridian}`, [
    //   "h:mm A"
    // ]).format("HH:mm");
    this.setState({ meridian }, () => this.props.onClick(this.state.hourTime));
  }

  handleMinutes = e => {
    const { value, min, max } = e.target;
    if (value >= min && value < max) {
      const hourTime = moment(
        `${this.state.time}:${value}}`,
        ["hhmm"]
      ).format("h:mm");
      if (value.length < 2) {
        this.setState({ minutes: "0" + value.slice(-2), hourTime }, () =>
          this.props.onClick(this.state.hourTime)
        );
      } else {
        this.setState({ minutes: value.slice(-2), hourTime }, () =>
          this.props.onClick(this.state.hourTime)
        );
      }
    } else {
      this.setState({ minutes: "00", hasError: true });
    }
  };

  render() {
    let time = [];
    for (let i = 1; i <= 12; i++) {
      time.push(

 this.handleClick(i)}
        >
          {i}

      );
    }
    return (

                {this.state.hourTime}{this.state.meridian}

                    {time}

 this.handleTimeAmPm("am")}>
                    am

                      <input
                        type="number"
                        min={0}
                        max={60}
                        value={this.state.minutes}
                        onChange={this.handleMinutes}
                      />

 this.handleTimeAmPm("pm")}>
                    pm

    );
  }
}

export default TimePicker;

UPDATE
I could handle the separate hour, minute, am, pm but could not store hourTime in all these elements(hour minue am/pm).


text:
Q: Use same MXML for an Add & Modify Form? I have a form that is written in MXML that allows a user to create/add a User.
I need to add a form that allows a user to modify SOME but NOT ALL of the fields for this user.
The forms are so similar, I don't want to have to create two separate forms, one for Add and one for Modify.
For example, in the Add form, the user specifies a user id.  In the Modify form, the "user id" field is not editable.
I'm wondering how I can initialize the MXML form (i.e. pass in a parameter?) so that it knows whether it is in the Add state or the Modif state.
I know I can't do the following but this is what I would like to do (pseudocode):
if (ADD_FORM) {
 mx:TextInput id="txtUserID"
}
else {
 mx:Label id="lblUserID"
}

A: This kind of thing is handled well with states.  In Flex 3 you define your states like view, add, and edit.  Then you can add the components that are common to all states to the document.  Within each state declaration, you can then add the components that are specific to only some states.  You can have the edit state dependent on add state since edit is add plus a few more fields.
In Flex 4 this is even easier.  You declare your states, and then inline in the single document have all content for all states, with includeIn attributes for which states each element should be included in (or excludeIn).


text:
Q: How to control which overlapping polygon is assigned using polygon to raster? I have multiple overlapping polygons that represent fire perimeters.   Each polygon has several attributes including year.   I'm turning this shapefile into a raster in ArcGIS 10.5 and I'd like for the most recent year to be on top.  Currently it seems to be placing them randomly.

A: The Polygon to Raster (Spatial Analyst) tool has the priority_field option that would work in the case of overlapping polygons.

This field is used to determine which feature should take preference
  over another feature that falls over a cell. When it is used, the
  feature with the largest positive priority is always selected for
  conversion irrespective of the Cell assignment type chosen.

A: if you are looking for the generated raster layer to have the value field = to the "year" attribute of the feature layer, so that where multiple polygons overlap the raster value is that of the most recent year, ArcGIS does not have any way of doing this, unfortunately (and quite surprising).


text:
Q: jar: Package org.apache.catalina.ssi missing from ModulePackages class file attribute I changed my tomcat version 9 to 8 but when I wrote jar uf ../catalina.jar org/apache/catalina/util/ServerInfo.properties it gave me the following error

jar: Package org.apache.catalina.ssi missing from ModulePackages class
file attribute

How can I solve this issue?

A: Had the same issue. Upgraded from apache 9.0.16 to 9.0.41, wanted to remove server version/infos, edited ServerInfo.properties, and when time came to
jar uf ../catalina.jar org/apache/catalina/util/ServerInfo.properties
got the same error than you.
I think I found the why :
I opened catalina.jar both on 9.0.16 and 9.0.41, and lo and behold : there is no ssi in org/apache/catalina/ for 9.0.41
Yet the MANIFEST.MF still includes it, as well as the module-info.class
From reading Tomcat changelog, it looks like this happened with tomcat 9.0.30 :
Moved server-side include (SSI) module into a separate JAR library. (schultz)
(looking in the lib directory, it seems like it is catalina-ssi.jar now)
Not sure how clean this is, but I went around the problem by opening catalina.jar with 7zip, modify the ServerInfo.properties from there, saved, restarted Tomcat, and it worked.

A: That is a really weird issue I'm facing myself right know, excluding
org.apache.catalina.ssi from the module-info.class

using ModiTect helped, hope it won't crash in a long run...


text:
Q: Selecting Organization Appcelerator CLI How do I select the organization through appcelerator cli ?
I have two organizations, I tried through appcelerator studio option.
File > Switch organization
But it says I have only one organization.
Edit:
I have configured appc on my windows machinne, and also configured android SDK, now after leaving the system untouched for a week. I'm not able to run any commands related to appc, not even able to print appc version, Please help.
Error: "SyntaxError: Unexpected token"

A: You can switch to a different organization using the cli this way:

appc switch --org-id YOURORGID

You can also log into your organization using the cli tool this way:

appc login --org-id YOURORGID --username USERNAME --password PASSWORD

You can find more documentation for the Appcelerator cli options here:
http://docs.appcelerator.com/platform/latest/#!/guide/Appcelerator_Command-Line_Interface_Reference

A: You can use this command

*

*appc logout -D

*appc login
Now choose your ORG and go ahead.

Hope this helps.

A: Sorted out the issues
Issue 1: Selecting Organization
Solution:
One of my organizations was inactive hence Appcelerator CLI was considering only the active organization.
We can switch organizations using Appcelerator Studio > File > Switch organization
Issue 2: Using any appc commands gives error Unexpected token
Solution:

*

*Delete .appcelerator folder in C:\Users\saif\

*Reinstall appc using npm install -g appcelerator

*Configure appc account using appc use latest, followed by appc setup