text:
Q: Jest Enzyme: TypeError: Cannot read property 'getBoundingClientRect' of null Can anyone help please: TypeError: Cannot read property 'getBoundingClientRect' of null.
handleInformationIcon = (setIndex, index) => {
    this.setState({ TooltipCheck: !this.state.TooltipCheck, activeTooltip: setIndex });
    const toolTipElement = document.getElementById(`tooltip_${index}`).getBoundingClientRect().top;
    const pageBottomHeight = window.innerHeight - toolTipElement;
    if ((pageBottomHeight < 200) && !this.state.TooltipCheck) {
      window.scrollBy({
        top: 200,
        behavior: 'smooth',
      });
    } else {
      window.addEventListener('scroll', this.handleScroll);
    }
}

renderTooltip = (message, index) => (
    <div
      className="tier-tooltip"
      id={`tooltip_${index}`}
    >
      <button
        role="link"
        type="button"
        tabIndex="0"
        aria-expanded={this.state.isTooltipCollapse}
        aria-label={this.props.resources.infoIcon}
        onClick={() => this.handleInformationIcon(`${index}__tier-tooltip`, index)}
        className={`icon icon-information tooltip${index}`}
      />

      {this.state.activeTooltip === `${index}__tier-tooltip` && (
        <div
          className={sn('tier-tooltip-text', this.state.TooltipCheck ? 'isOpen' : '')}
          tabIndex={0}
        >
          <EnhancedRichText
            className="tooltip__body"
            htmlText={message}
          />
          <FocusoutButton
            role="link"
            onClick={this.handleInformationIconHide}
            className="link modal__close"
            aria-label={this.props.resources.infoPopoverClose}
          >
            <span className="icon icon-close" />
          </FocusoutButton>
        </div>
      )}
      {this.state.TooltipCheck && (
        <div
          className="tooltip__backdrop"
          onClick={this.handleInformationIconHide}
        />
      )}
    </div>
  )

render = () => {
   return (
       {this.renderToolTip(message,0)}
   )
}

I tried using the test cases specified in this one but still they are failing for this piece of code : Jest/React mock scrollBy and .getBoundingClientRect function.

A: I was able to resolve this.
Reference : https://github.com/jsdom/jsdom/issues/1590#issuecomment-578350151

 const htmlElment = document.createElement('div');
    htmlElment.setAttribute('id', 'tooltip_0');
    htmlElment.getBoundingClientRect = jest.fn(() => ({
      x: 851.6,
      y: 200.0,
      width: 8.3,
      height: 17,
      top: 967.0,
      right: 860.0,
      bottom: 984.0,
      left: 851.6,
    }));
    const elementMock = jest.fn().mockImplementation(() => htmlElment);
    document.getElementById = elementMock;


text:
Q: Laravel Scheduler - how to output chained / series commands? This question is similar to this one except that:

*

*I need to send the output of the chained (2nd, 3rd or 4th) commands in an emailOutputTo method

Single Command Scheduler Code
This is working fine - both command and the email output:
protected function schedule(Schedule $schedule)
{
    $schedule   ->command('commandA:myoption')
                ->emailOutputTo('myemail@gmail.com');
}

Chained Command / Call - Using Previous SO Answer
The aforementioned accepted answer runs commandB correctly but because it uses ->call() it does not include the output for commandB in the email:
protected function schedule(Schedule $schedule) {
    $schedule   ->command('commandA:myoption')
                ->then(function() {
                    return $this->call('commandB:myoption');
                })
                ->emailOutputTo('myemail@gmail.com');
}

...as noted here it's not possible to email from a Scheduler ->call() method, only when using the ->command() method :

The emailOutputTo, sendOutputTo and appendOutputTo methods are exclusive to the command method and are not supported for call.

I tried a modification of the aforementioned accepted answer to use ->command()
instead of ->call() :
protected function schedule(Schedule $schedule) {
    $schedule   ->command('commandA:myoption')
                ->then(function() {
                    $this->command('commandB:myoption');
                            ->emailOutputTo('myemail@gmail.com');
                })
                ->emailOutputTo('myemail@gmail.com');
}

...gives the following error:

[Symfony\Component\Debug\Exception\FatalThrowableError]
  Type error: Too few arguments to function
  Illuminate\Foundation\Console\Kernel::command(), 1 passed in /app/Console/Kernel.php on line 33 and exactly 2 expected

Other Attempts at Chained / Series Commands
Tried various methods to chain commands using a then function - none seem to work (either running the command or output):
Option 1 - try to include output into a common email
Result = commandB not performed, only emails the commandA output:
protected function schedule(Schedule $schedule) {
    $schedule   ->command('commandA:myoption')
                ->then(function(Schedule $schedule) {
                    return $schedule->command('commandB:myoption');
                })
                ->emailOutputTo('myemail@gmail.com');
}

Option 2 - try to include output into a separate email
(by sending separate email outputs in the primary and 2nd commands)
Result = commandB not performed, only emails the commandA output:
protected function schedule(Schedule $schedule) {
    $schedule   ->command('commandA:myoption')
                ->then(function(Schedule $schedule) {
                    $schedule->command('commandB:myoption')
                            ->emailOutputTo('myemail@gmail.com');
                })
                ->emailOutputTo('myemail@gmail.com');
}

Option 3 - another variation injecting $schedule - with no success (same result)
protected function schedule(Schedule $schedule) {
    $schedule   ->command('commandA:myoption')
                ->then(function() use($schedule) {
                    return $schedule->command('commandB:myoption')
                                ->emailOutputTo('myemail@gmail.com');
                })
                ->emailOutputTo('myemail@gmail.com');
}

Questions
How do you chain commands in the scheduler and send the output from all commands to either

*

*a common email ?

*separate emails (if common isn't possible) ?

...as an aside, why is everyone so excited by Laravel when the documentation is so pathetically incomplete !!?

A: In the documentation it says:

By default, multiple tasks scheduled at the same time will execute
sequentially based on the order they are defined in your schedule
method.

In my use case where I only have three tasks which needs to run only once each day (read: morning), I just created three scheduler to run at the same time.
In your case, that might not work as one of your tasks may run over 5 minutes.
Mine ended up looking like this:
// $schedule->command('inspire')->hourly();
        $schedule->command('command:first')
            ->dailyAt('12:34')
        ->timezone('Europe/Oslo');
        $schedule->command('command:second')
            ->dailyAt('12:34')
            ->timezone('Europe/Oslo');
        $schedule->command('command:third')
            ->dailyAt('12:34')
            ->timezone('Europe/Oslo');

This solution works only if you have multiple tasks that must run in a specific order, and where it is supposed to run only once a day (or week).
I tried using the then closure, but it only ran one of the commands inside the function.

redpajama_set_name: RedPajamaStackExchange


text:
Q: angular 5 application is working on edge but failing on ie11 My angular 5 application which is running on angular cli is not working on ie11. What makes me wonder is the application is fine on edge. I have my ployfills set for both ie and edge. On ie11 application is throwing 'ERROR TypeError: Object doesn't support property or method' errors. Please look at my ployfills.ts, tsConfig and angular-cli and let me know what is missing.
I tried commenting web-animations polyfills but no luck.

polyfill.ts
/**
 * This file includes polyfills needed by Angular and is loaded before the app.
 * You can add your own extra polyfills to this file.
 *
 * This file is divided into 2 sections:
 *   1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
 *   2. Application imports. Files imported after ZoneJS that should be loaded before your main
 *      file.
 *
 * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
 * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
 * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
 *
 * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html
 */

/***************************************************************************************************
 * BROWSER POLYFILLS
 */

/** PhantomJS Polyfills  **/
// import 'core-js/es6/object';
// import 'intl';

if (typeof Object.assign !== 'function') {
    Object.assign = function(target) {
      'use strict';
      if (target == null) {
        throw new TypeError('Cannot convert undefined or null to object');
      }

      target = Object(target);
      for (let index = 1; index < arguments.length; index++) {
        const source = arguments[index];
        if (source != null) {
          for (const key in source) {
            if (Object.prototype.hasOwnProperty.call(source, key)) {
              target[key] = source[key];
            }
          }
        }
      }
      return target;
    };
  }

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/set';

/** IE10 and IE11 requires the following for NgClass support on SVG elements */
import 'classlist.js';  // Run `npm install --save classlist.js`.

/** IE10 and IE11 requires the following to support `@angular/animation`. */
import 'web-animations-js';  // Run `npm install --save web-animations-js`.

/** Evergreen browsers require these. **/
import 'core-js/es6/reflect';
import 'core-js/es7/reflect';
// import 'core-js/client/shim'; // PhantomJS dependency

import 'hammerjs/hammer'; // Needed for tests to run without errors.

/** ALL Firefox browsers require the following to support `@angular/animation`. **/
// import 'web-animations-js';  // Run `npm install --save web-animations-js`.

/***************************************************************************************************
 * Zone JS is required by Angular itself.
 */
import 'zone.js/dist/zone';  // Included with Angular CLI.

/***************************************************************************************************
 * APPLICATION IMPORTS
 */

/**
 * Date, currency, decimal and percent pipes.
 * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10
 */
import 'intl';  // Run `npm install --save intl`.

tsConfig.json
{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

angular-cli.json
{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "SampleApp"
  },
  "apps": [
    {
      "root": "client-app",
      "outDir": "wwwroot",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "nee",
      "styles": [
        "styles.scss",
        "neer-theme.scss"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "client-app/tsconfig.app.json"
    },
    {
      "project": "client-app/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "scss",
    "component": {}
  }
}


text:
Q: Track Changes to MySQL table using Node.js I am trying to integrate node.js app into an existing PHP/MySQL system. node-mysql is used to allow node.js to access the MySQL database. A table named tableA in the MySQL database updates with new data every 10 minutes.
Problem: Using node, I need the node server to continuously check tableA for changes whenever tableA gets updated. What is a good way to achieve this?
I am thinking if I used setInterval(checkDb(tableA), 10*60*1000), or an infinite loop, the checkDbquery function may not coincide with the database update.
I also happen to be using socket.io so will a good method be for the PHP system to emit('dbUpdated') to the node server if it is even possible for PHP to send a message to node.js?
Node Code
var dbCheckQueue = function(callback) {
    client.query('SELECT * from tableA',
                    function(error, results, fields) {
                        if error
                            throw error;
                        callback(results);
                    });
}

// 10mins-interval checking of table
setInterval(function() {
    dbCheckQueue(function(results) {
        console.log('Fresh meat!')
    });
}, 10*60*1000);

A: Ideally you would trigger the event from the where ever the update is being made from after completion.
Since you are using sockets you could create an "Events" connection or similar (authenticate or some other method to indicate it is connecting to trigger an event) which would connect to your socket and trigger an update and disconnect. This could be called from anywhere regardless of platform as long as you are able to create the connection. Once connected the script would send whichever command you want to be triggered and disconnect/finish the updating process.
You could either do this directly from where the update is made or setup a trigger on mysql with sys_exec() to execute another script which does the same as above.


text:
Q: Meeting request timing mismatch with full VS lite outlook version I am creating meeting request with java code and sending it to full as well as lite version of outlook as shown below:
final SimpleDateFormat iCalendarDateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmm'00'");
                final long uid =System.currentTimeMillis();
                iCalendarDateFormat.setTimeZone(TimeZone.getTimeZone(MRBSConstants.TIMEZONE));
final String calendarContent = "BEGIN:VCALENDAR\n"
                                            + "METHOD:REQUEST\n"
                                            + "PRODID: BCP - Meeting\n"
                                            + "VERSION:2.0\n"
                                            + "BEGIN:VEVENT\n"
                                            + "DTSTAMP:"+ iCalendarDateFormat.format(meetingEndTime) + "\n"
                                            + "DTSTART:" + iCalendarDateFormat.format(meetingStartTime) + "\n"
                                            + "DTEND:"+ iCalendarDateFormat.format(meetingEndTime) + "\n"
                                            + "SUMMARY:test request\n"
                                            + "UID:" + uid + "\n"
                                            + "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:" + Arrays.toString(recipetList) + "\n"
                                            + "ORGANIZER:MAILTO:" + from+ "\n"
                                            + "LOCATION:" +loc + "\n"
                                            + "DESCRIPTION:" + body+ "\n"
                                            + "SEQUENCE:0\n" + "PRIORITY:5\n" + "CLASS:PUBLIC\n" + "STATUS:CONFIRMED\n" + "TRANSP:OPAQUE\n" + "BEGIN:VALARM\n"
                                            + "ACTION:DISPLAY\n" + "DESCRIPTION:REMINDER\n" + "TRIGGER;RELATED=START:-PT00H15M00S\n" + "END:VALARM\n" + "END:VEVENT\n" + "END:VCALENDAR";

And it is working fine with lite version of outlook means it giving correct time in lite version but in full version of outlook it showing different timings.?why
Here MRBSConstants.TIMEZONE value is GMT-5:30.
I have also tried adding VTIMEZONE COMPONENT but in that case outlook cant recognize the ics file as correct.
Do we have any general ics object which can work on both version?


text:
Q: bash printf giving me Invalid String operator I've got a script that calculates the numerical value of the previous month by assigning a variable to the current month, checks if that value is '01', and if so, assign a previous_month variable to '12', or subtract 1 from the value and assign that new value to the previous_month
Here is a snippet of the code in question: a variable declaration and an if statement
# Set current month
current_month=`date +"%m"`

# Check if current month = Jan
if [ $current_month -eq "01" ]
    then
        previous_month=12
    else
        previous_month=$(printf %02d $(expr $current_month - 1))
fi

Here is the output from running /bin/sh -x myScript.sh
+ [ 09 -eq 01 ]
+ expr 09 - 1
+ printf %02d Invalid string operator
+ previous_month=00

Whats really bugging me is that this a) used to work, and b) works if I write the code in a shell (copy / paste)
I can't find a way to get this to work and I need to have the previous_month variable two characters with a leading zero if the month is < 10

A: Problem is with the Number being interpreted as OCTAL by printf. Since i am not able to reproduce the issue.Can you check if this work around helps.
previous_month=$(printf "%0*d\n" 2 $(expr $current_month - 1))

or
value=$(expr $current_month - 1)
previous_month=$(printf %02d "${value#0}")

A: @skr didn't have the answer 100%, but they gave me something to work with and test.
I had to use the curly braces around the current_month variable and add #0, not sure what this does, exactly, but I'm assuming its allowing printf to see that value as an integer instead of a string.
The variable previous_month needed to be assigned as follows:
previous_month=$(printf %02d $(expr ${current_month#0} - 1))

And this is the output of running /bin/sh -x myScript.sh
+ [ 09 -eq 01 ]
+ expr 9 - 1
+ printf %02d 8
+ previous_month=08


text:
Q: Reshaping data table for plotting that has variable name and value int he same row I'm in the process of building a Shiny app but need help with some data transformation in order to generate the plot. The SQL query and filter gives me the desired result, but the shape of the data is presenting a roadblock as everything is on a single row and the desired feature names are inside the columns. Currently the data table is shaped as follows

aName
aValue
bName
bValue

FeatureNameA
FeatureValueA
FeatureNameB
FeatureValueB

My goal is to have a Feature Importance plot but I don't want the feature labels to be the generic names (aName, bName), I'd like for them to be FeatureNameA and tied to FeatureValueA etc.
Thank you!
I tried melt() and t() but these are not getting the desired results. The desired result would be a reshaped table that looks like this:

Name
Value

FeatureNameA
FeatureValueA

FeatureNameB
FeatureValueB

Hoping I can get help on writing a function to transform the table to get the desired result for a bar plot.

A: We can use pivot_longer
library(tidyr)
pivot_longer(df1, cols = everything(),
    names_to = c(".value"), names_pattern = ".(.*)")

-output
# A tibble: 2 × 2
  Name         Value
  <chr>        <chr>
1 FeatureNameA FeatureValueA
2 FeatureNameB FeatureValueB

Or with base R
 data.frame(Name = unlist(df1[c(TRUE, FALSE)]),
    Value = unlist(df1[c(FALSE, TRUE)]))

data
df1 <- structure(list(aName = "FeatureNameA", aValue = "FeatureValueA",
    bName = "FeatureNameB", bValue = "FeatureValueB"),
class = "data.frame", row.names = c(NA,
-1L))

A: library(data.table)
data.table::rbindlist(
  split.default(mydata, f = gsub("(.).*", "\\1", names(mydata))))

#           aName        aValue
# 1: FeatureNameA FeatureValueA
# 2: FeatureNameB FeatureValueB

A: library(data.table)

melt(setDT(df1),,patterns('Name','Value'))

   variable       value1        value2
1:        1 FeatureNameA FeatureValueA
2:        2 FeatureNameB FeatureValueB


text:
Q: Modify selected object values in ES6 I have an array that looks like this :
let arr = [{
  x: 2,
  y: 2,
  z: 2,
  w: 2,
  name: 'John Doe',
  occupation: 'student'
}]

Every object in the array has about 30 fields. And I have some fields that are of type Number, that I want to modify, something like this:
arr.forEach(data => {
  data.x += 5
  data.y += 5
  data.z += 5
  data.w += 5

  return data
})

This works, but I have about 10 params (the number might increase in the future) in the object that I will add 5 to, and I don't like the look of it. I was wondering if there is a shorter way of doing this?
And, I want to return the whole object, not just the params that I modify.

A: arr.forEach(data => {
    Object.keys(data).forEach(key => {
        if (typeof data[key] === "number") {
            data[key] += 5;
        }
    })
    return data;
});

A: You could create a function that takes an array of properties that you want to change and value that you want to add and the use map and reduce methods to return new array of objects.

let arr = [{
  x: 2,
  y: 2,
  z: 2,
  w: 2,
  name: 'John Doe',
  occupation: 'student'
}]

const add = (arr, props, value) =>
  arr.map(o => props.reduce((r, e) => {
    r[e] += value
    return r;
  }, { ...o }))

const result = add(arr, ['x', 'y', 'z', 'w'], 5)
console.log(result)

A: If it is possible for you, I'd advise not to mix keys-to-mutate with keys-to-persist in one object:
const arr = [{
  name: "John Doe",
  occupation: "student",
  coords: {
    x: 2,
    y: 2,
    z: 2,
    w: 2,
  },
}];

… and then simply:
for (const item of arr) {
  for (const coord in item.coords) {
    item.coords[coord] += 5;
  }
}

… or:
arr.forEach((item) => {
  Object.keys(item.coords).forEach((coord) => {
    item.coords[coord] += 5;
  });
});

If that's not possible (for example, if you don't define items' shapes), you'll have to have an additional list of keys of properties that you want to change:
const keys = [ "x", "y", "z", "w" ];

for (const item of arr) {
  for (const key of keys) {
    item[key] += 5;
  }
}

… or vice versa, the list of keys not to mutate (much less performant solution):
const keys = [ "name", "occupation" ];

for (const item of arr) {
  for (const key in item) {
    if (!keys.include(key)) {
      item[key] += 5;
    }
  }
}

Keep in mind though, that this approach is not completely DRY.

A: One way you can do this is by writing a generic map function -

const map = (o, f) =>
  Array.isArray(o)
    ? o.map(f)
    : Object.fromEntries(Object.entries(o).map(([k, v]) => [k, f(v)]))

const data =
  { x: 2, y: 2, z: 2, w: 2, name: 'John Doe', occupation: 'student' }

const result =
  map(data, v => Number(v) === v ? v + 5 : v)

console.log(result)

Output -
{
  "x": 7,
  "y": 7,
  "z": 7,
  "w": 7,
  "name": "John Doe",
  "occupation": "student"
}


text:
Q: How should I work with MELPA and MELPA-stable using Emacs? I often run into a problem when I install packages with Emacs: what can I do if one of the packages is broken in melpa and the other is broken in melpa-stable? For example if I use melpa-stable elscreen fails on startup:
run-hooks: Symbol's function definition is void: elscreen-start

but if I run on melpa elscreen works but cider-nrepl fails to start up. I checked their github profile and their build is currently failing. Is there a way to work around this?

A: You can use both melpa and melpa-stable, and pin certain packages to certain repositories by customizing package-pin-packages:
(require 'package)

(add-to-list 'package-archives
         '("melpa-stable" . "http://stable.melpa.org/packages/") t)
(add-to-list 'package-archives
         '("melpa" . "https://melpa.org/packages/") t)

(setq package-pinned-packages
      '((imenu-anywhere . "melpa-stable")
        (spaceline . "melpa-stable")
        (clj-refactor . "melpa-stable")
        (cider . "melpa-stable")
        (clojure-mode . "melpa-stable")
        (linum-relative . "melpa-stable")
        (aggressive-indent . "melpa-stable")
        (evil-leader . "melpa-stable")
        (evil-visualstart . "melpa-stable")
        (evil-jumper . "melpa-stable")
        (evil-snipe . "melpa-stable")
        (evil . "melpa-stable")
        (evil-commentary . "melpa-stable")))


text:
Q: How to get Holo Light theme working in my Xamarin application I'm trying to get my app to use the Holo.Light theme. I've created a custom theme for Holo and put it in
Resourses\values-v11\FsmTheme.xml
<?xml version="1.0" encoding="utf-8" ?>
<resources>
    <style name="FsmTheme" parent="@android:style/Theme.Holo.Light">
    </style>
</resources>

I've also created one for older versions and put it in
Resourses\values\FsmTheme.xml
<?xml version="1.0" encoding="utf-8" ?>
<resources>
    <style name="FsmTheme" parent="@android:style/Theme.Light.NoTitleBar">
    </style>
</resources>

Then I added it to my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto" android:versionCode="001" android:versionName="001" package="futurestate.app.droid">
    <uses-sdk android:minSdkVersion="12" android:targetSdkVersion="14" />
    <application android:label="FutureState App Demo" android:icon="@drawable/Icon" Theme="@style/FsmTheme" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

I'm not sure what else I would need to do to get the theme to take in the app.

A: The breakdown is on this line.
<application android:label="FutureState App Demo" android:icon="@drawable/Icon" Theme="@style/FsmTheme" />

Some of the tutorials out there show
Theme="@style/ThemeName"

but you should actually structure it the same as the rest of the element
android:theme="@style/ThemeName"

So the final structure will read
<application android:label="FutureState App Demo" android:icon="@drawable/Icon" android:theme="@style/FsmTheme" />

A: You can use Attributes to modify values in the AndroidManifest.xml, for example this changes the theme to holo light:
[Activity(
    Label = "Foobar",
    MainLauncher = true,
    Theme = "@android:style/Theme.Holo.Light"
)]
public class MainActivity : Activity { ... }

You can also do this at the Application level.
But for your specific problem, it seems that you are naming your style files FsmTheme.xml. That is incorrect. You must name any styling resources styles.xml, so if you rename your files to Resources/values/styles.xml and Resources/values-v11/styles.xml everything should work as expected.


text:
Q: Python: How to search a value in a log using identifier So I want to make a program that can grab a numerical value from a log (.txt). Each value is associated with a log identifier. So here is the contents of my log file (named test.txt):
Log:

ID        Key           Value_1 Value_2
f1     time (sec)       1000     2000
f2     # of people       20       31
f3   # tickets written   27       87

So I want to grab the value 27 from ID f3. Is there a way to do this? I have an idea using readlines() and looping line by line until the ID is found but not sure what to do from there. Here's what I have so far:
with open('test.txt') as f:
    data = f.readlines()

for line in data:
    if 'f3' in line:
        # Code to retrieve value 27

A: You can use regex
import re

with open('test.txt') as f:
    for line in f:
        if line[0:2] == "f3":
            print(re.search("\d+", line[2:]).group(0))

27

Regex is a string matching tool. The pattern \d+ tells regex to look for at least one digit. So Regex (re) searches line[2:] (2: skips the first 2 letters) and saves all matches (numbers). Then .group(0) fetches the first result. which is 27

Online demo


text:
Q: Get iterator for const reference I'm developing a class that must return an iterator with the begin() method. Also, I have to develop a function that receives a const reference of this class and iterates over it.
When I try to get an iterator from this method, I have the following compilation error: "the object has type qualifiers that are not compatible with the member function."I can't understand why this error appears.
Here is the code that I have written:
// ------------ class Neuron -------------
class Neuron { ... };
// ---------------------------------

// ------------ class AbstractLayer -------------
class AbstractLayer {
public:

    class Iterator : public std::iterator<std::input_iterator_tag, Neuron> {
        public:
            Iterator(Neuron *neurons) : _neurons(neurons) {}
        private:
            Neuron *_neurons;
    };

    virtual Iterator begin() = 0;
    virtual const Iterator begin2() = 0;
};
// ----------------------------------------

// ------------ class Layer -------------
class Layer : AbstractLayer {

public:
    Layer(){};
    Iterator begin(){ return Iterator(_neurons); }
    const Iterator begin2(){ return (const Iterator)begin(); }

private:
    Neuron *_neurons;
    int _size;
};
// --------------------------------

// ------------ Method where the problem is -------------------
void method(const AbstractLayer &layer){
    // Error in both methods:
    // "the object has type qualifiers that are not compatible with the member function."
    layer.begin();
    layer.begin2();
}
// -------------------------------------------------------------

A: In the method function, layer references a constant object. That means you can only call functions marked as const. Like e.g.
class AbstractLayer {
public:
    ...
    virtual const Iterator begin() const = 0;  // <- Note use of `const` here
    ...
};

A: Your function accepts a const AbstractLayer which means that only const member functions can be called on it. However, begin and begin2 are not const. In fact, given that only begin2 returns a const Iterator, it wouldn't make sense to try and call begin anyway in this method.
Change
virtual const Iterator begin2() = 0;

to
virtual const Iterator begin2() const = 0;

and
const Iterator begin2()

to
const Iterator begin2() const

Finally, returning a const Iterator is actually meaningless in your code, as the const is discarded on account of an rvalue being returned. Regardless, you shouldn't need to perform casting to const Iterator when you call begin; just return an Iterator and the compiler will take care to make it const.
Finally, your Layer class needs to derive publicly from AbstractLayer:
class Layer : public AbstractLayer

Live Demo

A: You do not need begin and begin2. What you need is two versions of begin - const and non-const. A const one would return const iterator. You also might want a cbegin (const only) which would always return const iterator.

A: In method, the layer argument is const which prevents you from calling non-const methods on it.  If you take layer by non-const reference (void method(AbstractLayer &layer)), you will be able to call both methods.
You should probably provide a const begin method that returns a const_iterator so you can iterate over a const AbstractLayer.


text:
Q: Шахматы на JS . Ошибка - Cannot read property 'appendChild' of null var cherssarr = [['','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', ''],

['8', '♜', '♞', '♝', '♛', '♔', '♝', '♞','♜','8'],

['7', '♟', '♟','♟','♟','♟', '♟','♟', '♟','7'],

['6', '', '', '', '', '', '','', '', '6'],
['5', '', '', '', '', '', '','', '', '5'],
['4', '', '', '', '', '', '','', '', '4'],
['3', '', '', '', '', '', '','', '', '3'],
['2', '♟', '♟','♟','♟','♟','♟','♟', '♟','2'],

['1', '♜', '♞', '♝', '♛', '♔', '♝', '♞','♜','1'],
[ '','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', '' ]];
for(var i = 0; i < 10; i++){
    var tr = document.createElement('tr');
    document.querySelector('#new-table').appendChild(tr);
    for(var j=0; j<10; j++){
    td.innerHTML = cherssarr[i][j];
    tr.appendChild ('td');

A: Такой результат нужен?

const cherssarr = [
  ['','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', ''],
  ['8', '♜', '♞', '♝', '♛', '♔', '♝', '♞','♜','8'],
  ['7', '♟', '♟','♟','♟','♟', '♟','♟', '♟','7'],
  ['6', '', '', '', '', '', '','', '', '6'],
  ['5', '', '', '', '', '', '','', '', '5'],
  ['4', '', '', '', '', '', '','', '', '4'],
  ['3', '', '', '', '', '', '','', '', '3'],
  ['2', '♟', '♟','♟','♟','♟','♟','♟', '♟','2'],
  ['1', '♜', '♞', '♝', '♛', '♔', '♝', '♞','♜','1'],
  [ '','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', '' ]
];

for(let i = 0; i < 10; i++){
    let tr = document.createElement('tr');
    document.querySelector('#new-table').appendChild(tr);
    for(let j=0; j<10; j++){
      let td = document.createElement('td');
      tr.appendChild(td);
      td.innerHTML = cherssarr[i][j];
    }
 }
table {
  border-collapse: collapse;
}
td {
  padding: 10px;
  text-align: center;
  border: 1px solid gray;
}
td:last-child,
tr:first-child td {
  transform: rotate(180deg);
}


text:
Q: jQuery replacetext Can somebody help me please?
I would like to replace 'text' words with 'TEXT' just 3 times, how this can be done?
$('#test *').replaceText( /\btext\b/gi, 'TEXT' );

That is example #1 on this page
http://benalman.com/code/projects/jquery-replacetext/examples/replacetext/
Even If I delete 'g' modifier noting happens, still all 'text' words are replaced with 'TEXT'

A: replaceText doesn't work that way. It loops over all the child textnodes, and replaces the text in them. If you remove the "g", it replaces only the first instance of text, but it does so in every child textnode. I don't know if there's a way to limit the number of replacements in javascript if you use g, but I don't think so, so you'll need to do it manually.


text:
Q: Random variables and $\sigma$-algebras I came across this problem.
If we throw two dice the sample space is $\Omega = \{ (i, j), 1 \leq i, j \leq 6 \}$. The $\sigma$-algebra is generated by the events $A_k = \{ (i,j) : \max(i,j) = k \}$
Show that $x_1=max(i,j)$ is a random variable and $X_2=i+j$ isn't a random variable
There's a short explanation which explains the relation within the borel sets of the random variable and their preimages.
"Actually, a function $X$ from some measurable space $(\Omega, \Sigma)$ to $\mathbb{R}$ equipped with the Borel $\sigma$-algebra is defined as a random variable if it's measurable; that is, for every Borel set B, the preimage $X^{-1}(B) = \{\omega : \omega \in \Omega, X(\omega) ∈ B\}$ is measurable."
"Notice the focus on $X^{-1}(B)$ (preimages of Borel sets) rather than $X^{-1}(x)$(preimages of individual real numbers)"
1) Whenever you have a random variable, are the events of the random variable always borel sets?
I mean if we have that the probability space of the random variable is $(\Omega_X,F_X,P_X)$, then for all the random variables, the family of events $F_X$ is always the $\sigma$-borel algebra?
2) If the preimages $X_1^{-1}(x)$ are $\left \{ 1,2,3,4,5,6 \right \}$, what are the preimages $X_2^{-1}(x)$? And what would be the preimages of $X_1^{-1}(B)$ and $X_2^{-1}(B)$?
How would you show that $X_1$ is a random variable and $X_2$ isn't?

Generators of the $\sigma$-algebra, first case:
$A_1=\{(1,1)\}$
$A_2=\{(1,2),(2,2),(2,1)\}$
$A_3=\{(1,3),(2,3),(3,3),(3,2),(3,1)\}$
$A_4=\{(1,4),(2,4),(3,4),(4,4),(4,3),(4,2),(4,1)\}$
$A_5=\{(1,5),(2,5),(3,5),(4,5),(5,5),(5,4),(5,3),(5,2),(5,1)\}$
$A_6=\{(1,6),(2,6),(3,6),(4,6),(5,6),(6,6),(6,5),(6,4),(6,3),(6,2),(6,1)\}$
Here $A_k:=\{(i,j)\in\Omega\mid\max(i,j)=k\}$

Generators of the $\sigma$-algebra, second case
$B_2=\{(1,1)\}$
$B_3=\{(1,2),(2,1)\}$
$B_4=\{(1,3),(2,2),(3,1)\}$
$B_5=\{(1,4),(2,3),(4,1),(3,2)\}$
$B_6=\{(1,5),(2,4),(3,3),(5,1),(4,2)\}$
$B_7=\{(1,6),(2,5),(3,4),(4,3),(5,2),(6,1)\}$
$B_8=\{(2,6),(3,5),(4,4),(5,3),(6,2)\}$
$B_9=\{(3,6),(4,5),(6,3),(5,4)\}$
$B_{10}=\{(4,6),(5,5),(6,4)\}$
$B_{11}=\{(5,5),(6,5)\}$
$B_{12}=\{(6,6)\}$
Here $B_k:=\{(i,j)\in\Omega\mid i+j=k\}$

A: 1)
If by $\Omega_X$ you mean $\mathbb R$ and by $P_X$ you mean the probability measure prescribed by $B\mapsto P(X\in B)$ then: "yes, we usually go for $\mathcal F_X=\mathcal B(\mathbb R)$".
$X$ is usually by definition a random variable if it is a function that takes real values and is measurable wrt the Borel $\sigma$-algebra.
2)
Looking at $X_1$ the preimage of $B\in\mathcal B(\mathbb R)$ wrt $X_1$ is the set:$$X_1^{-1}(B)=\{(i,j)\in\{1,2,3,4,5,6\}^2\mid max(i,j)\in B\}$$
If you take singleton $B=\{x\}$ then we get:$$X_1^{-1}(B)=\{(i,j)\in\{1,2,3,4,5,6\}^2\mid max(i,j)=x\}$$
For $X_2$ you will get similar expressions where $\max(i,j)$ is replaced by $i+j$.

You cannot speak of "the preimages of $X_1^{-1}(B)$".
The correct wording is that "$X_1^{-1}(B)$ is the preimage of $B$ under (or with respect to) $X_1$".

The $\sigma$-algebra generated by the events $A_k$ is formally the smallest $\sigma$-algebra on $\Omega$ that contains these sets
Now observe that every preimage $X_1^{-1}(B)$ can be written as a union of these sets. This tells us that $X_1$ is measurable wrt to this $\sigma$-algebra. That means that $X_1$ can be classified as a random variable if $\Omega$ is equippes with the $\sigma$-algebra. Actually the $\sigma$-algebra generated by the $A_k$ can be shown to be  the collection $$X_1^{-1}(\mathcal B(\mathbb R)):=\{X_1^{-1}(B)\mid B\in\mathcal B(\mathbb R)\}=$$$$\{\{(i,j)\in\Omega\mid \max(i,j)\in B\}\mid B\in\mathcal B(\mathbb R)\}\tag1$$
However it is not possible to write e.g. $X_2^{-1}(\{4\})=\{(i,j)\mid i+j=4\}$ as an element of this $\sigma$-algebra.
That's why $X_2$ cannot be classified as a random variable.

edit:
Working $(1)$ out we find that for every $B\in\mathcal B(\mathbb R)$ we can find a set $I=I_B\subseteq\{1,2,3,4,5,6\}$ such that: $$X_1^{-1}(B)=\bigcup_{i\in I}A_i$$
So actually: $$X_1^{-1}(\mathcal B(\mathbb R))=\left\{\bigcup_{i\in I}A_i\mid I\subseteq\{1,2,3,4,5,6\}\right\}$$
For e.g. preimage $X_2^{-1}(\{4\})=\{(1,3),(2,2),(3,1)\}$ we cannot find such a set $I$.


text:
Q: Reading order for the Lensman books I tried to read Triplantary when I was younger, and gave up on the book pretty quickly. I've recently found out that the first two books in the series, Triplanetary and First Lensman, were written as prequels.
I'd like to give E. E. Smith's writing another chance, and I'm considering starting with the third book, Galactic Patrol, as it was the first one written. Was the series intended to be read with the prequels first? Are there any spoilers to the later books in the prequels?

A: I can only address a small part of your question, about the spoilers: there are two versions of Triplanetary, one of which has an extensive introduction added on.  This introduction pretty much spoils the entire Arisia-Boskone-Eddore backstory that's gradually unfolded through the main series.

A: The actual sequence for "reading" the series should start with Triplanetary and move straight through to Masters of the Vortex.

*

*Triplanetary - (you can "skim" the history if you must, as long as you get the underlying story of Atlantis and the assorted other characters in play throughout human history opposing civilization as he describes it)

*First Lensman - This development of Triplanetary is important to defining the origins of the Galactic Patrol

*Galactic patrol - great story

*Gray Lensan - Same

*Second Stage Lensman

*Children of the Lens - I love this story - the four girls are truly fun characers to visualize.

*Masters of the Votex.
Also worth noting - There are THREE authorized post- E.E.Doc Smith books that are worthy of reading by David A. Kyle :   The lnesman from Rigel, The Dragon Lensman and Z-Lensman.  They just work the stories for these three non-human lensmen without distracting from the incredible work of E.E. "Doc" Smith.
I just started reading the series again a week ago and have ripped through to The Children of the Lens" already.  Fun stuff.
Good luck.

A: The lensman series started with Galactic Patrol as a serial in Astounding Science Fiction in 1937-38. It was followed by Gray Lensman in 1939-40, Second Stage Lensmen in 1941-42 and years later Children of the Lens in 1947-48.
I am sure the original order of publication is the right reading order today. The other books are just not up the the standard of the original four.
If you can find the original issues of the Astounding magazine in which they appeared , so much the better. For you will find yourself experiencing the Golden Age of science fiction in which Doc Smith was  the most popular author.

A: Three possible orders:
The fictional order of fictional events is:
1) Triplanetary billions of years in the past to centuries in the future.
2) First Lensman  soon after Triplanetary
3) Galactic Patrol  Centuries after First Lensman.
4) Gray Lensman instantaneous sequel to Galactic Patrol.
5) Second Stage Lensman instantaneous sequel to Gray Lensman.
?) Masters of the Vortex  Some say it happens after Children of the Lens but most say that it happens between Second Stage Lensman and Children of the Lens which is my opinion.
6) Children of the Lens  About a generation after Second Stage Lensman.
However, some people might want to read them in an order that avoids spoilers.
That order should be
1) Galactic Patrol  centuries after First Lensman.
2) Gray Lensman instantaneous sequel to Galactic Patrol.
3) Second Stage Lensman instantaneous sequel to Gray Lensman.
4) Masters of the Vortex.
5) Triplanetary.
6) First Lensman.  Think of Triplanetary and First Lensman as secret history lessons taught by the Arisians to the Children of the Lens as they grow up.
7) Children of the Lens.
Or a compromise order:
1) Triplanetary Omitting the first sections with the backstory.
2) First Lensman  Soon after Triplanetary
3) Galactic Patrol  Centuries after First Lensman.
4) Gray Lensman instantaneous sequel to Galactic Patrol.
5) Second Stage Lensman instantaneous sequel to Gray Lensman.
?) Masters of the Vortex  Some say it happens after Children of the Lens but most say that it happens between Second Stage Lensman and Children of the Lens which is my opinion.
5a) Then read the first sections of Triplanetary with the backstory that the Arisians would tell the children of the Lens as they grew up.
6) Children of the Lens  About a generation after Second Stage Lensman.
And I don't know the fictional order of:

Also worth noting - There are THREE authorized post- E.E.Doc Smith books that are worthy of reading by David A. Kyle : The lensman from Rigel, The Dragon Lensman and Z-Lensman. They just work the stories for these three non-human lensmen without distracting from the incredible work of E.E. "Doc" Smith.

But it would be really good to have them listed in their proper fictional order as well as the books by E.E. Smith.

A: You'll be fine to start with Galactic Patrol, and in fact if you start with Triplanetary (as I did, many years ago) you'll get confused when you get to Galactic Patrol and things get quite different (and somewhat inconsistent).

A: The situation is even worse than that; Dr Smith originally set Galactic Patrol in a universe explicitly different from Triplanetary.  There are other differences as well; the Arisians are not omniscient and infallible in the original Lensman series, for instance.  He seems to have ret-conned Triplanetary while writing Children of the Lens, but changed the Arisians for the book versions, making rather a fuss about their omniscience (implausibly, IMHO) in First Lensman.  The changes to the Arisians were not thought through, however; there's no justification for their needing four bloodlines, with three as backups, in the ret-conned version, though it makes sense in the original.  Æsthetically, in my opinion, the ret-con changes are even worse, so read the original magazine versions if you can.  I'm recording the differences at Differences between the original and ret-con versions of the series on Wikipedia's talk page about the series.

A: I only recently realized there were different versions.  The original order was Galactic Patrol, Gray Lensman, Second Stage Lensman and Children of the Lens.  When they were published in book form, Doc Smith apparently decided they needed more of a background so he wrote Triplanetary and First Lensman.  I started with Triplanetary and thought it was fine and then First Lensman and thought it was great.  Ironically, it was Galactic Patrol that lost me with an endless battle that went on forever and endless technobabble.  Later, I was prepared for that and managed to go back and finish it.  But where you start depends on what you find the most interesting.  I found the trip through history to be fascinating.

A: I'd go with "Skip the first half of Triplanetary (mostly the Kinnison family history) & pick up which the space battle against Grey Roger. Then read them in order to Second Stage Lensman. Then read the 3 by David Kyle & Master of The Vortex (skippable). Finally, Children Of The Lens.
2 caveats for modern readers.

*

*Smith was probably the most pro military writer this side of Heinlein.

*Smith lived 1890-1965. Those days, the USA had no woman combat troops. He explicitly states in several places "Lenses are as masculine as whiskers.". Clarissa McDougall Kinnison is the only woman lensman in several centuries.

He mentions "The interpassage of galaxies" in several places. This is because back then one of the theories of planet formation  was the close passage of stars & this was known to be pretty rare.
Still, he did invent FTL flight (Skylark Of Space) & is considered The Father of Space Opera. IMO, you like the early Star Wars movies, you'll like the Lensman series.


text:
Q: insertAdjacentHTML is not a function in svg element I have some code where I want to insert some HTML on the click of the button. But when I click that button, I get the following error:

TypeError: piecesLocation.insertAdjacentHTML is not a function

When inspecting the underlying code in the browser, I get this:

The code that gets triggered when I click a button is this:
function showValues() {
const piecesLocation = document.getElementsByClassName('pieces');
piecesLocation.insertAdjacentHTML('afterend', '<g class="values"></g>');
}

What is wrong with my code that causes it to trigger this error?


text:
Q: Configure Microsoft.AspNet.Identity to allow email address as username I'm in the process of creating a new application and started out using EF6-rc1, Microsoft.AspNet.Identity.Core 1.0.0-rc1, Microsoft.AspNet.Identity.EntityFramework 1.0.0-rc1, Microsoft.AspNet.Identity.Owin 1.0.0-rc1, etc and with the RTM releases yesterday, I updated them via NuGet this evening to RTM.
Apart from a couple of code changes to the work I'd done so far, all seemed to be going well, until I tried to create a local user account for the app.
I had been working on e-mail addresses being the username format which with the release candidate worked great, but now when creating a user with an email address for a username, it throws up the following validation error:

User name xxxxx@xxxx.com is invalid, can only contain letters or digits.

I've spent the last hour or so searching for a solution or documentation on configuration options for it, but to no avail.
Is there a way I can configure it to allow e-mail addresses for usernames?

A: In my case, running in VS 2013 C#, MVC 5.2.2, using ASP.NET Identity 2.0, the solution was to update the ApplicationUserManager constructor inside App_Start\IdentityConfig.cs like so:
public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
        this.UserValidator = new UserValidator<ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false };
    }

A: For people on AspNet.Identity.Core 2.1 and up, these validators in the UserManager are readonly. Email addresses as usernames are allowed by default but if you need further customisation of the characters in your usernames, you can do so in Startup.cs like this:
public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentity<ApplicationUser, IdentityRole>(options => {
        options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+/";
    });

    // ... etc
}

(I needed a '/' for legacy reasons.)

A: If you are using ASP.Net webforms and are trying to accomplish this, simply open up your IdentityModels.vb/cs file and under Public Class UserManager, have it look as so:
Public Class UserManager
Inherits UserManager(Of ApplicationUser)

Public Sub New()
    MyBase.New(New UserStore(Of ApplicationUser)(New ApplicationDbContext()))
    Users = store
    UserValidator = New UserValidator(Of ApplicationUser)(Me) With {.AllowOnlyAlphanumericUserNames = False}
End Sub

Public Property Users() As IUserStore(Of ApplicationUser)
    Get
        Return m_Users
    End Get
    Private Set(value As IUserStore(Of ApplicationUser))
        m_Users = value
    End Set
End Property
Private m_Users As IUserStore(Of ApplicationUser)

End Class

A: Since coding my own ApplicationUserManager : UserManager class didn't work for me (maybe bc I use Razor Pages, not MVC), here's another solution: In Startup.cs in CofigureServices() you can configure Identity Options, for example:
services.Configure<IdentityOptions>(options =>
{
  options.User.AllowedUserNameCharacters =
  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@";
  options.User.RequireUniqueEmail = true;
});

More on this topic in Microsoft docs: https://learn.microsoft.com/de-de/aspnet/core/security/authentication/identity-configuration?view=aspnetcore-2.2

A: You can allow this by plugging in your own UserValidator on the UserManager, or just by turning it off on the default implementation:
UserManager.UserValidator = new UserValidator<TUser>(UserManager) { AllowOnlyAlphanumericUserNames = false }

A: The C# version of this (in App_Code\IdentityModels.cs) is
public UserManager()
        : base(new UserStore<ApplicationUser>(new ApplicationDbContext()))
    {
        UserValidator = new UserValidator<ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false };
    }

A: I had the same problem, when I tried to change the code for make the UserName was the real name of the person and not the email the system show me the same error message  "User name ABC DEF is invalid, can only contain letters or digits." I solved the problem adding the space character (In my case at the end) to AllowedUserNameCharacters.
Im using Asp.Net Core 2.2 and VS2017
This is my code
Go to Startup.cs  and edit or add the line  under "//user settings":
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.Configure<IdentityOptions>(options =>
        {
            // Password settings.
            options.Password.RequireDigit = true;
            options.Password.RequireLowercase = true;
            options.Password.RequireNonAlphanumeric = true;
            options.Password.RequireUppercase = true;
            options.Password.RequiredLength = 6;
            options.Password.RequiredUniqueChars = 1;

            // Lockout settings.
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
            options.Lockout.MaxFailedAccessAttempts = 5;
            options.Lockout.AllowedForNewUsers = true;

            // User settings.
            options.User.AllowedUserNameCharacters =
                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+ ";
            options.User.RequireUniqueEmail = false;
        });

        services.ConfigureApplicationCookie(options =>

A: As you will have probably found out (and was to be expected), ASP.NET Identity 2.0.0, released March 2014, adds this functionality in the framework.
Announcement: http://blogs.msdn.com/b/webdev/archive/2014/03/20/test-announcing-rtm-of-asp-net-identity-2-0-0.aspx
Full example and tutorial, including account confirmation: http://www.asp.net/identity/overview/features-api/account-confirmation-and-password-recovery-with-aspnet-identity

A: If you cannot find IdentityConfig.cs then replace your AccountController constructor with this code.
public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager)
  {
      AllowOnlyAlphanumericUserNames = false
  };
}

A: In my case i had a repository class working with authentication, that didn't let me use a "-" inside usernames.. The fix was inside the constructor here:
//-------------------------------------------------------
public AuthRepository()
//-------------------------------------------------------
{
    _ctx = new AuthContext();
    _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx));
    _userManager.UserValidator = new UserValidator<IdentityUser>(_userManager)
    {
        AllowOnlyAlphanumericUserNames = false
    };
}

A: I was also stuck with this because most of the time usernames are E-mails these days, I can understand the reasoning of a separate E-mail field though. These are purely my thoughts / experience as I also could not find Microsoft's say on this.
Remember, Asp Identity is purely to identify someone, you don't have to have an E-mail to be identified but they allow us to store it because it forms part of an identity. When you create a new web project in visual studio, you are given the option for authentication options.
If you select a non empty project type such as MVC and set authentication to "Individual accounts" then you are given the basic underpinnings for user management. One of which includes a sub class looking like this within App_Start\IdentityConfig.cs:
 // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };
    }
    //N.B rest of code removed
}

What this tells us is that Microsoft intend us to store more complex usernames (refer to AllowOnlyAlphaNumericUserNames = false), so really we have mixed signals.
The fact this is generated from a default web project gives us a good indication / direction from Microsoft (and a clean way) to enable us to enter E-mails for the username field. It's clean because the static create method is used within the App_Start\Startup.Auth.cs when bootstrapping the application with the Microsoft.OWIN context.
The only down side to this approach is you end up storing the E-mail twice.... Which is not good!

A: If you are using IOC of some sort ( I am using StructureMap) in your account controller, you will need to apply the fix mentioned above by Hao Kung when the Usermanager is passed in:
(I had to). There may be a way to do it in the IOC setup, but I don't know how.
public AccountController(ApplicationUserManager userManager)
    {
        _userManager = userManager;
        _userManager.UserValidator = new UserValidator<ApplicationUser>(_userManager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

A: I have faced the same problem . but finally I resolved the issue by adding bellow part in to my method , not the constructor .
public void MyMethod(){

     UserManager<ApplicationUser> manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

                    // Configure validation logic for usernames
                    manager.UserValidator = new UserValidator<ApplicationUser>(manager)
                    {
                        AllowOnlyAlphanumericUserNames = false,
                        RequireUniqueEmail = true

                    };

}


text:
Q: Turn off Windows 10 Task View sliding animation I actually use the new task view tool provided in Windows 10 and I was wondering if there is a way to disable the sliding animation between different desktops. I find this kind of annoying and it seems to take a second each time for the animation to play. It would be great if there was a way to disable this so each time I switch to a desktop, it switches instantly instead of playing the animation.

A: Control panel  →  System  →  Advanced system settings  →  Performance settings.
Uncheck "Animate windows when minimizing and maximizing".

A: Only with OFFICE 2016 products, windows weirdly slid around when they were selected and moved - far delayed behind the mouse movement.  I had to use WINDOWS-U first, to turn off 'Show Animations in Windows' - this deselected several things in the Performance settings dialog mentioned above.  This helped 90%, but the window movement was still slightly delayed behind mouse movement when dragging.  The final change that worked was the Show Window Contents While Dragging getting turned off.  Performance is now snappy like it ought to be (as it IS for ALL other apps on the machine!).  Turned off: Animate controls and elements inside Windows, Animate windows when minimizing and maximizing, Fade or slide menus into view, Fade or slide ToolTips into view, Fade out menu items after clicking, Show window contents while dragging, Slide open combo boxes, and Smooth-scroll list boxes.


text:
Q: Locating records not in selection using ArcPy? I have a list of addresses that I need to contact. Some are listed in the attribute table, and some aren't. I'm trying to find the ones that aren't.
The list:
contacted = ['123 STOWE ST', '123 ROSE DR', '124 ROSE DR', '125 ROSE DR', etc.]

The attribute table has a Property_Street field that lists addresses. I want to figure out which addresses are in the contacted list and are not in the Property_Street field.
The only thing I've figured out so far is to isolate the records that have been confirmed as contacted based on the 'Contacted' field in the attribute table. But it returns a layer, not a field, and I don't know how to isolate the Property_Street field from that layer.
query = "\"CONTACTED\" = 1"
contacted_in_tbl = arcpy.SelectLayerByAttribute_management("hot_zone", "NEW_SELECTION", query)

A: If you want to use python then use sets:

A set object is an unordered collection of distinct hashable objects.
  Common uses include membership testing, removing duplicates from a
  sequence, and computing mathematical operations such as intersection,
  union, difference, and symmetric difference

contacted = ['123 STOWE ST', '123 ROSE DR', '124 ROSE DR', '125 ROSE DR']
attr = ['123 STOWE ST', '123 ROSE DR', '124 ROSE DR']

print(list(set(contacted)-set(attr)))
#Same as
print(list(set(contacted).difference(attr)))

['125 ROSE DR']
['125 ROSE DR']

List all adresses using da.SearchCursor and list comprehension:
import arcpy
in_attribute_table = [i[0] for i in arcpy.da.SearchCursor(fc,'PROPERTY_STREET')]
diff = list(set(contacted)-set(in_attribute_table))


text:
Q: Python / Pandas: problem with column headers from an Excel CSV UTF-8 file This is my first venture into UTF-8 in Pandas, so maybe a newbe error.
I have a simple test table in Excel which I saved as UTF-8 CSV. Looking at the file with "less" on Linux gives me this:
<U+FEFF>sample;chead
1;test

while a "hexdump -C" this:
00000000  ef bb bf 73 61 6d 70 6c  65 3b 63 68 65 61 64 0d  |...sample;chead.|
00000010  0a 31 3b 74 65 73 74 0d  0a                       |.1;test..|

So far, so good, I will assume that this is a correct UTF-8 file.
I now want to read that file into a pandas dataframe and check the name of the first column to be "sample" or "probe".
#!/usr/bin/env python3

import pandas as pd

df = pd.read_csv("sample1.csv", encoding="utf-8", sep=None, engine="python")

cols = [x.lower() for x in df.columns.values]
print("Columns:", cols)
print("Columns[0]:", cols[0])
print("type Columns[0]:", type(cols[0]))

# I expect this not to print, but it does
if cols[0] not in ["sample", "probe"]:
     print("Ouch, cols[0] is not 'sample' or 'probe'???")

And the output of the above program is:
Columns: ['\ufeffsample', 'chead']
Columns[0]: sample
type Columns[0]: <class 'str'>
Ouch, cols[0] is not 'sample' or 'probe'???

From the first line of the output I do understand (somehow) that the cols[0] value is '\ufeffsample', but as the output via print() statement is "sample", I do not understand why the "if" triggers.
What do I need to change so that the "if" statement works?

A: <U+FEFF> is a byte order mark, see https://en.wikipedia.org/wiki/Byte_order_mark.
To read in a file in pandas with those, you can set the encoding to utf-8-sig as suggested in https://github.com/pandas-dev/pandas/issues/4793.


text:
Q: Repeat beamer presentation automatically I have a beamer presentation which should run automatically on its own during an exhibition. I already added \transduration{5}\transblindshorizontal to show the next slide automatically after 5 seconds, but I still need to figure out how to jump back to the very first slide after the very last slide has been shown. I can't find anything in the beamer manual.
PS: I'm not looking for anything like \againframe. The whole presentation should repeat itself over and over again for almost a whole day.

A: As one option, outside of LaTeX, you could set up Adobe Reader to do this. Under Preferences -> Full Screen, select the Loop after last page option:

A: Because of Werner's answer I now found the comp.text.tex post
https://groups.google.com/d/msg/comp.text.tex/kYnAVKbuq50/vZZFuBK1mlMJ
which provides the following code. It uses PDF low-level commands to loop after the last page. This is basically the same as the viewer setting in Werner's answer, but part of the PDF. It works for me under Ubuntu Linux 11.04 with Adobe Reader 9.4.2. No idea if this is viewer dependent. At the very least the viewer must support some basic javascript.
Put the following in the preamble of the beamer document:
\hypersetup{pdfstartpage=1}
\pdfcatalog{
/AA <<
/WC <<
/S/JavaScript/JS (app.fs.loop=false;)
>>
>>
}
\pdfpageattr{
/AA <<
/O <<
/S/JavaScript/JS (app.fs.loop=true;)
>>
>>
}

An alterntive solution I figured by browsing other beamer questions is to use
impressive to show the PDF file. Using the -w option the PDF is repeated and the transient time can be set using -a 5. However, this tool converts the PDF to an image which adds some small but ugly white frame at the lower and right site. Also I really prefer to stay with only PDF to keep things simple.


text:
Q: is there a way to access javascript variable in code behind? here's my code
function qtyblur() {
    var textgettaxbaseid = document.getElementById("txttaxbase");
    var textgettaxbasevalue = textgettaxbaseid.value;
    var taxbase = parseFloat(textgetsubtotalid.value / 1.12).toFixed(2);
    textgettaxbaseid.value = taxbase;
}

I want to access my variables here and use it in my code behind. I am really new to this so bear with me.

A: To access what you have in client side (javascript) in code bahind you need to send a call to server. You call post the form or send an ajax call on server.
Usually we put the javascript variable values in some hidden field and get the hidden field in code behind and extract the values of javascript.

A: no you cannot. Instead, use a Hidden Field in you javascript function, assign a variable's value to it and use the Hidden Field in your code behind.

A: Use a Web-Method in your code-behind and pass your javascript variable to your web-method using jquery and json.


text:
Q: Apache CXF with Parameterized types I have a bunch of classes that all look the same and consist merely of an Id and a few String attributes. So I tried to generalize the creation of WebServices using Generics:
@WebService
public interface IBasicCRUDService<E extends AbstractEntity, D extends AbstractEntityDTO, ID, DAO extends IGenericDAO<E, ID>>{

    public List<D> findAll(BasicFilters filters);
    public D findById(ID id);

    @WebMethod(exclude = true)
    public void setBaseDao(DAO dao);
}

Implementation:
public abstract class BasicCRUDService<E extends AbstractEntity, D extends AbstractEntityDTO, ID, DAO extends IGenericDAO<E, ID>> extends AbstractService implements IBasicCRUDService<E, D, ID, DAO> {

    private IGenericDAO<E, ID> dao;
    private Class<E> persistentClass;
    private Class<D> dataTransferClass;

    public final DAO getDao() {
        return (DAO) dao;
    }

    public void setDao(DAO dao) {
        this.dao = (IGenericDAO<E, ID>) dao;
    }

    @SuppressWarnings("unchecked")
    public Class<E> getPersistentClass() {
        if (persistentClass == null) {
            this.persistentClass = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        }
        return persistentClass;
    }

    @SuppressWarnings("unchecked")
    public Class<D> getDataTransferClass() {
        if(dataTransferClass == null) {
            this.dataTransferClass = (Class<D>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
        }
        return dataTransferClass;
    }

    @Override
    @Transactional(readOnly=true)
    @WebMethod(operationName="findAll")
    public List<D> findAll(BasicFilters filters) {
        List<E> pList = dao.findAll(filters);
        List<D> dList = new ArrayList<D>();
        for(E e:pList) {
            dList.add(this.map(e, getDataTransferClass()));
        }
        return dList;
    }

    @Override
    @Transactional(readOnly=true)
    @WebMethod(operationName="findAll")
    public D findById(ID id) {
        return this.map(dao.findById(id), getDataTransferClass());
    }

}

And this would be a concrete implementation:
    @Service("metodologiaService")
    public class MetodologiaService extends BasicCRUDService implements IMetodologiaService {
    @Override
    @Autowired
    @Qualifier("metodologiaDAO")
    public void setBaseDao(IMetodologiaDAO dao) {
        super.setDao(dao);
    }

}

@WebService
public interface IMetodologiaService extends IBasicCRUDService<Metodologia, MetodologiaDTO, Integer, IMetodologiaDAO>{
    public List<MetodologiaDTO> findAll(BasicFilters filters);
    public MetodologiaDTO findById(Integer id);
}

The problem is when doing it like this it seems CXF is unable to properly map the attributes of the WebServices. For instance, when calling the findById method, I get this:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <soap:Fault>
         <faultcode>soap:Server</faultcode>
         <faultstring>com.sun.org.apache.xerces.internal.dom.ElementNSImpl cannot be cast to java.lang.Integer</faultstring>
      </soap:Fault>
   </soap:Body>
</soap:Envelope>

However, if I declare the methods directly in my IMetodologiaService, it works:
@WebService
public interface IMetodologiaService extends IBasicCRUDService<Metodologia, MetodologiaDTO, Integer, IMetodologiaDAO>{
    public List<MetodologiaDTO> findAll(BasicFilters filters);
    public MetodologiaDTO findById(Integer id);
}

So it seems somehow extending interfaces is not working when using Parameterized types. Is there any way around this?


text:
Q: Loading dynamically pages into div using angularJS I'm trying to load pages dynamically into a div using a select
My HTML code :

      <select ng-model="selectedType" class="form-control" ng-change="showContent()" ng-options="type as type.text for type in types"></select>

My JS code :
$scope.showContent= function() {
        $scope.getView = function() {
           return $scope.selectedType.value ;
        }
}

I got this error :
Error: [ng:areq] http://errors.angularjs.org/1.2.2/ng/areq?p0=Ctrl&p1=not%20a%20function%2C%20got%20undefined
P.S: My views use angularJS too, and the idea is to get my page(View) from the select.
"Ctrl" is the control name of the loaded page

A: src must evaluate to a String value, representing the URL to be included.
Still, your code is messy. You can:

*

*remove showContent listener at all

*remove getView function and leave the expression selectedType.value

*selectedType.value must be a string, representing the URL

See here: http://jsfiddle.net/E9rH4/1/
Watch the console error (see the url it tries to fetch).

A: Looks like $scope.selectedType.value is returning null. Try console.logging $scope.selectedType to see what you get. The function should return the full path.
Update
After reviewing the plnk, it appears that you're trying to load an entire Angular app via ng-include. That's not what ng-include does, it just includes small templates. Here is the working plnkr


text:
Q: How to customize todonotes not to be in the margin I would like to produce solved examples with comments like below.

I tried package todonotes with the following codes
\documentclass[12pt,openany,twoside,fleqn]{book}
\usepackage{amsmath}
%\usepackage[width=16cm,height=24cm,margin=5cm]{geometry}
\usepackage[textwidth=\marginparwidth,linecolor=red,bordercolor=yellow,backgr
oundcolor=yellow]{todonotes}
\usepackage{mathspec}
\setmainfont{Tekton Pro}
\everymath{\displaystyle}
\setmathsfont(Digits,Greek,Latin){Tekton Pro}
\usepackage{siunitx}
\begin{document}
\noindent
\(V=\frac{4}{3}\pi r^{3}\)\\[2ex]
\(\frac{dV}{dr}=4\pi r^{2}\)\todo{{\fontspec{ITC Berkeley Oldstyle
Std}Differentiate $V$ with respect to $r$. Remember that $\pi$ is a
constant.}}\\[2ex]
When $ r=5$, \(\frac{dV}{dr}=4\pi\times 5^{2}\)\todo{{\fontspec{ITC Berkeley
Oldstyle Std}Substitute $r=5$}}\\[2ex]
\hspace*{3.2cm}\(=314\) (3 s.f.)\\[2ex]
So the rate of change is 314 \si{\cubic\centi\meter} per
\si{\centi\meter}\todo{{\fontspec{ITC Berkeley Oldstyle Std}Interpret the
answer with units.}}
\end{document}

On compiling I got

I also realized that todonotes cannot work inside tcolorbox yet it's part of the target.
Apologies for this is looking to me like many questions in one.
I would be greatly happy to receive any kind help from the community.

A: You can do what you need without todonotes, you can use TikZ overlay, remember picture.
I don't have your font, but it isn't a problem to add it.
\documentclass[12pt,openany,twoside,fleqn]{book}
%\usepackage[width=16cm,height=24cm,margin=5cm]{geometry}
\usepackage{amsmath}

\usepackage{tikz}
\usetikzlibrary{positioning}
\tikzset{
    mypoint/.style={
        fill=red,
        circle,
        inner sep=1pt,
        xshift=5pt, yshift=3pt
        },
    myblock/.style={
        fill=yellow,
        text width=4cm,
        },
    }

\usepackage{tcolorbox}
\tcbuselibrary{skins}
\tcbset{
    enhanced,
    colframe=gray!30,
    colback=white,
    boxrule=10pt,
    sharp corners,
    width=.65\linewidth
    }

\usepackage{mathspec}
%\setmainfont{Tekton Pro}% I don't have this font
\everymath{\displaystyle}
%\setmathsfont(Digits,Greek,Latin){Tekton Pro}% I don't have this font
\usepackage{siunitx}

\begin{document}
\begin{tcolorbox}
\(\begin{aligned}
    V=\frac{4}{3}\pi r^{3}\\[2ex]
    \frac{dV}{dr}=4\pi r^{2}\tikz[overlay, remember picture]{\node[mypoint] (P1) {};}\\[2ex]
\end{aligned}\)

\(\begin{aligned}
  \text{When } r=5\text{, } \frac{dV}{dr}&=4\pi\times 5^{2}\tikz[overlay, remember picture]{\node[mypoint] (P2) {};}\\[2ex]
    &=314  \text{ (3 s.f.)}\\[2ex]
\end{aligned}\)

So the rate of change is 314 \si{\cubic\centi\meter} per
\si{\centi\meter}\tikz[overlay, remember picture]{\node[mypoint] (P3) {};}
\begin{tikzpicture}[overlay, remember picture]
    \node[myblock, xshift=20em, yshift=3ex] (B1) at (P1) {Differentiate $V$ with respect to $r$. Remember that $\pi$ is a constant.};
    \node[myblock] (B2) at (P2 -| B1) {Substitute $r=5$};
    \node[myblock] (B3) at (P3 -| B1) {Interpret the answer with units.};
    \draw[red] (P1) -- ++(1,0) |- (B1.west);
    \draw[red] (P2) -- (B2.west);
    \draw[red] (P3) -- (B3.west);
\end{tikzpicture}
\end{tcolorbox}

\end{document}


text:
Q: Ruby storing array into csv result in output with extra "" I have a script that is scrapping a website, generates a csv file and is storing raw data into this csv. Everything works well except when I am trying to store an array into the csv file :
tarif_jeune = []
tarif_adulte =[]
              html_doc.search("td table table table tr").each do |tr|
                unless (tr.css("td:nth-child(11)").text.squish == "") || (tr.css("td:nth-child(11)").text.squish.size > 5) || (tr.css("td:nth-child(11)").text.squish ==  "0,00")
                  tarif_adulte << tr.css("td:nth-child(11)").text.squish
                end
                unless (tr.css("td:nth-child(12)").text.squish == "") || (tr.css("td:nth-child(12)").text.squish.size > 5) || (tr.css("td:nth-child(12)").text.squish ==  "0,00")
                  tarif_jeune << tr.css("td:nth-child(12)").text.squish
                end
              end

then inserting tarif_jeune and tarif_adulte into csv file :
 csv << ["true", tr.css("td:nth-child(10)").text.squish, tr.css("td:nth-child(11)").text.squish, tr.css("td:nth-child(11)").text.squish, tr.css("td:nth-child(12)").text.squish, tr.css("td:nth-child(13)").text.squish, tr.css("td:nth-child(14)").text.squish, tr.css("td:nth-child(15)").text.squish,  tr.css("td:nth-child(1) a").attr("href").value, tarif_jeune.uniq, tarif_adulte.uniq, cat.uniq, address]

cat, tarif_jeune, tarif_adulte are all arrays. I would expect them to look like this in my csv ["poo", "faa", "foo"] but the outpout is quite different: "" are inserted everywhere and I get something like this :
tarif_jeune, tarif_adulte, cat
"[""15,00""]","[""20,00""]","[""Simple Messieurs 45"", ""Simple Dames Senior"", ""Simple Messieurs Senior""]"

Can someone explain where those extra "" come from and how to get rid of them.

A: The double quote " character is the default :quote_char in CSV class.
So, if you try to write a string that comprises of double quote characters, they will be escaped by CSV class and will be written as "" to the file.
In your case, you are writing an array of strings to CSV. When Array#to_s is called on a array of strings, the output will be a String that looks somewhat like below:
ary = ["a", "b", "c"]
puts "#{ary}"
#=> ["a", "b", "c"]

The double quotes in string representation of array will be escaped by CSV class, and the above ary will appear as "[""a"", ""b"", ""c""]" in csv file.
To solve this issue, look at why you need to store the output Array#to_s in CSV.  You most likely want to do ary.join(" ") or equivalent and then write to file.

A: This is perfectly valid csv.
Assuming you want your data to look like this (as you say in ["poo", "faa", "foo"]):
tarif_jeune, tarif_adulte, cat
["15,00"],["20,00"],["Simple Messieurs 45", "Simple Dames Senior", "Simple Messieurs Senior"]

Here, inside the fields, there is a comma, which is also your field seperator. Therefore the fields have to be surrounded with quotes. And because your fields also contain quotes inside, those quotes need to be escaped with another quote:
tarif_jeune, tarif_adulte, cat
"[""15,00""]","[""20,00""]","[""Simple Messieurs 45"", ""Simple Dames Senior"", ""Simple Messieurs Senior""]"

Any decent csv parser should be able to handle those extra quotes. In fact, without them, your csv would be malformed.


text:
Q: Super-weird issue triggering "Segmentation Fault" I won't go very deep into the issue (the codebase is already thousands of lines and quite complex), so I'll try to miniminise the... "window" to what I've spotted.
Here's the routine triggering the "Segmentation Fault" :
extern (C)
{
    void* Statements_new() { return cast(void*)(new Statements()); }
    void  Statements_add(Statements s, Statement st)
    {
        //writeln("In here");
        if (s is null) writeln("StatemenTS are null");
        else writeln("not null : "~ typeid(s).name);

        if (st is null) writeln("statement is null");
        else writeln("not null : " ~ typeid(st).name);

        s.add(st);

        //writeln("Out of here");

    }

}

A few notes :

*

*The declared methods are nothing but "bindings" so that native routines can be called directly from C code (Bison actually).

*The Statements_add function is called with a Statements object and a subclassed Statement object.

Now, the weirdness of it :

*

*The error doesn't happen all the time (actually it doesn't happen like 99% of the time), but when it does, the s.add(st); statement seems the culprit.

*Never ever is one of the 2 parameters (s,st) null.

*Now, if I comment the 2 if... writeln... typeid statements, the error is there.

*If I uncomment them (they don't do anything, huh?), it always works - fixed - bingo!

What's going on???

A few more details :

*

*Compiler : DMD64 D Compiler v2.065

*Debugger : lldb

*OS       : OSX 10.9.2

A: If you are passing the only reference of an object allocated in D code from the D heap to non-D code, then you must either register it as a GC root, or change your code to use malloc instead of allocating from the managed D heap. Otherwise, the GC will think that the object is unused, and collect it to free memory.


text:
Q: Getting values from Masked text box I've set MaskedTextBox's Mask to: "Fl\air H\al ###.## , something here: ####.##"
When user inputs the value final text looks something like this:
Flair Hal 987.67 , something here: 1234.12
What will be the best way to extract 976.67 and 1234.12 from the MaskedTextBox's Text. I am looking for a List which will have all the values of the mask (976.67, 1234.12).
There can be any number of masks in the mask string and the mask can be any valid mask.
I am thinking of first removing '\' from the Mask and then in a for loop keep comparing the Mask with the Text and detect changes and add them to the List. But this doesnt sound good to me and i think there probably is a better way of doing it.

A: There are four values of the mask in your example: 987, 67, 1234, 12. The fact that blocks separated by a . are treated as one is your own logic, so I think you will just have to write code to get the information yourself.
Have a look at the MaskedTextProvider property of the MaskedTextBox, and its EditPositions property. The EditPositions give you the positions within the Text that the user could enter.

A: Well i found out that there is no good way of doing it. As adrianbanks said i have to code myself to get this information.
I have written my own usercontrol which uses combination of labels and maskedtexboxes to get the input.
I use curly braces to indicate where i wan the masked textbox and the user control puts one masked textbox per pair of curly braces.
"Flair Hal {###.##} , something here: {####.##}"
Then I can use the values collection which has the values for the masks.

A: I would think that you would be to use TextMaskFormat to remove the literals and prompt characters from the .Text property. That way you'd only get the numbers (and spaces).

A: Use a regular expression. The following regex will work for your example, but you may have to tweak it depending on your actual mask:
\d*[.]\d{2}


text:
Q: Horizontal RecyclerView automaticly scrolls when editing EditText I am implementing horizontal RecyclerView with EditText which is inside. When I click on EditText or enter text to EditText, RecyclerView automaticly scrolls to the beginning. How to prevent this scroll issue?
In this my application where you can enter goals for your training.
I have tried setOnKeyStroke, onClick, setOnFocusChange on EditText.
I set RecyclerView setFocusable to false.
I also tried to set CoordinatorLayout with RecyclerView to android:descendantFocusability="blocksDescendants".
But none of this works.
Here is main_layout.xml

        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginStart="0dp"
            android:orientation="horizontal"
            app:layout_constraintStart_toStartOf="parent"
            android:id="@+id/goal_rv"
            android:background="@drawable/recycler_view_background"
            />
    </android.support.constraint.ConstraintLayout>

Here is recycleView item layout goal_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
  >
        <EditText
            android:inputType="text"
            android:id="@+id/generalEditText"
            android:layout_width="300dp"
            android:layout_height="63dp"
            android:background="@drawable/edit_text_general_background"
            android:foregroundGravity="fill_vertical"
            android:gravity="center|center_vertical"
            android:text="@string/add_goal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="1.0"
            />
</android.support.constraint.ConstraintLayout>

Here is main:
 goalRecyclerView = findViewById(R.id.goal_rv);

        goalRecyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        goalRecyclerView.setFocusable(false);
        goalRecyclerView.setOnClickListener(this);
        generalAdapter = new GoalListViewAdapter(this);
        generalAdapter.setOnItemClickListener(this);
        goalRecyclerView.setAdapter(generalAdapter);
        goalRecyclerView.setGoals(null);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);

Here is adapter:

    void setGoals(ArrayList<Goal> goals){
        if(goals != null && this.goals != null && goals.size() != this.goals.size()) {
            this.goals.clear();
            this.goals = goals;
        }
        if(this.goals !=null) {
            this.goals.add(EMPTY_GOAL);
            this.goals.add(EMPTY_GOAL);/*problem appears in second edittext*/

        }
    }

    ArrayList<Goal> getGoals(){
        return goals;
    }
    @NonNull
    @Override
    public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.goal_layout, null);
        viewHolder = new CustomViewHolder(view, listener);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull CustomViewHolder customViewHolder, int i) {
        Goal textAtPosition = goals.get(i);
        customViewHolder.fillView(textAtPosition);
    }

I expect no scrolling of RecyclerView during entering text in EditText. I got scrolling to the beggining after focusing and key stroke on editText.

A: I found the solution:
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false) {
            @Override
            public boolean requestChildRectangleOnScreen(RecyclerView parent, View child, Rect rect, boolean immediate, boolean focusedChildVisible) {

                if (((ViewGroup) child).getFocusedChild() instanceof EditText) {
                    return false;
                }

                return super.requestChildRectangleOnScreen(parent, child, rect, immediate, focusedChildVisible);
            }
        };
        goalRecyclerView.setLayoutManager(linearLayoutManager);

It was in here:
Android - How to disable RecyclerView auto scroll from clicking


text:
Q: How do I convert a list of Option to a list of T when T cannot be copied? How do I take a Vec<Option<T>>, where T cannot be copied, and unwrap all the Some values?
I run into an error in the map step. I'm happy to move ownership of the original list and "throw away" the Nones.
#[derive(Debug)]
struct Uncopyable {
    val: u64,
}

fn main() {
    let num_opts: Vec<Option<Uncopyable>> = vec![
        Some(Uncopyable { val: 1 }),
        Some(Uncopyable { val: 2 }),
        None,
        Some(Uncopyable { val: 4 }),
    ];

    let nums: Vec<Uncopyable> = num_opts
        .iter()
        .filter(|x| x.is_some())
        .map(|&x| x.unwrap())
        .collect();
    println!("nums: {:?}", nums);
}

Playground
Which gives the error
error[E0507]: cannot move out of borrowed content
  --> src/main.rs:17:15
   |
17 |         .map(|&x| x.unwrap())
   |               ^-
   |               ||
   |               |hint: to prevent move, use `ref x` or `ref mut x`
   |               cannot move out of borrowed content

A: You don't need to copy the Uncopyable at all, if you are OK with using a Vec of references into the original Vec:
let nums: Vec<&Uncopyable> = num_opts.iter().filter_map(|x| x.as_ref()).collect();
//            ^ notice the & before Uncopyable?

This may not do the trick for you if you have to work with an API that requires &[Uncopyable]. In that case, use Matthieu M.'s solution which can be reduced to:
let nums: Vec<Uncopyable> = num_opts.into_iter().filter_map(|x| x).collect();

A: In Rust, when you need a value, you generally want to move the elements or clone them.
Since move is more general, here it is, only two changes are necessary:
let nums: Vec<Uncopyable> = num_opts
    .into_iter()
//  ^~~~~~~~~~~~-------------- Consume vector, and iterate by value
    .filter(|x| x.is_some())
    .map(|x| x.unwrap())
//       ^~~------------------ Take by value
    .collect();

As llogiq points out, filter_map is specialized to filter out None already:
let nums: Vec<Uncopyable> = num_opts
    .into_iter()
//  ^~~~~~~~~~~~-------- Consume vector, and iterate by value
    .filter_map(|x| x)
//              ^~~----- Take by value
    .collect();

And then it works (consuming num_opts).
As pointed out by @nirvana-msu, in Rust 1.33 std::convert::identity was added which can be used instead of |x| x. From the documentation:

let filtered = iter.filter_map(identity).collect::<Vec<_>>();


text:
Q: Context Menu not displaying correct language with PyQt5 When I was trying to create a Qt application using PyQt5, I noticed that QPlainTextEdit standard context menu was being displayed in English , which is not the language of my system (Portuguese), despite its locale was correctly inherited from its parent widget. Is this the expected behavior? If so, how can i add a translation without having to rewrite the functions already present in that context menu (like cut/copy/paste)?
Example
This program reproduces the behavior described above; it shows a window (thus textEditor.locale().language() have the same value as QLocale.Portuguese) but  the context menu is shown in english.

import sys
from PyQt5.QtWidgets import QApplication, QPlainTextEdit, QMainWindow
from PyQt5.QtCore import QLocale

def main():
    app = QApplication(sys.argv)

    window = QMainWindow()

    assert(window.locale().language() == QLocale.Portuguese)
    textEditor = QPlainTextEdit(window)

    assert(textEditor.locale().language() == QLocale.Portuguese)
    window.setCentralWidget(textEditor)
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

A: You need to install a QTranslator to add the translations for your system locale.
import sys
from PyQt5.QtWidgets import QApplication, QPlainTextEdit, QMainWindow
from PyQt5.QtCore import QLocale, QTranslator, QLibraryInfo

def main():
    app = QApplication(sys.argv)

    # Install provided system translations for current locale
    translator = QTranslator()
    translator.load('qt_' + QLocale.system().name(), QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(translator)

    window = QMainWindow()

    assert(window.locale().language() == QLocale.Portuguese)
    textEditor = QPlainTextEdit(window)

    assert(textEditor.locale().language() == QLocale.Portuguese)
    window.setCentralWidget(textEditor)
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


text:
Q: Ограничение на ввод даты в DataGrid У меня есть таблица Timetable, которая представлена в виде DataGrid. В нем есть столбец "Date". Я хочу чтобы можно было вводить в этот столбец только дату не раньше текущей. Вот что я пробовал сделать, но это не работает. Подскажите как можно модифицировать код
private void timetableDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            string headerText = timetableDataGridView.Columns[e.ColumnIndex].HeaderText;

            if (!headerText.Equals("Date")) return;
            DateTime date;
            if (!DateTime.TryParse(e.FormattedValue.ToString(), out date) && date > System.DateTime.Now)
            {
                timetableDataGridView.Rows[e.RowIndex].ErrorText = "attention";
                e.Cancel = true;
            }
        }

        void timetableDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            // Clear the row error in case the user presses ESC.
            timetableDataGridView.Rows[e.RowIndex].ErrorText = String.Empty;
        }

A: Используй для сравнения DateTime метод CompareTo
https://docs.microsoft.com/ru-ru/dotnet/api/system.datetime.compareto?view=netframework-4.8


text:
Q: I cant access my Bootstrap modal I cant access my Bootstrap modal after making my modal save/update function. Here is my code. But when I comment out my .done(function(msg)) I can access it again
Hope you can help me guys.
var postId= 0;
var postBodyElement= null;
$('.post').find('.interaction').find('.edit').on('click', function(event) {
        event.preventDefault();

        postBodyElement= event.target.parentNode.parentNode.childNodes[1];
        var postBody= postBodyElement.textContent;
        postId= event.target.parentNode.parentNode.dataset['postid'];
        $('#post-body').val(postBody);
        $('#edit-modal').modal();
});

//saving the update of your post..
$('#modalSave').on('click', function() {
        $.ajax({
                method: 'POST',
                url: url,
                data: {post: $('#post-body').val(), postId: postId, _token: token}
        })
        .done(function(msg)) {
                $(postBodyElement).text(msg['new_body']);
                $('#edit-modal').modal('hide');
        };
});

and this is my modal form..

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Edit post

                <form>

                        Edit your post
                        <textarea class="form-control" name="post-body" id="post-body" rows="5"></textarea>

                </form>

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="modalSave">Save changes</button>

A: I made a mistake here at, .done(function(msg))  instead of .done(function(msg)
//exist of close parenthesis at .done(function(msg))
.done(function(msg)) {
        $(postBodyElement).text(msg['new_body']);
        $('#edit-modal').modal('hide');
});

instead of this.
.done(function(msg) {
        $(postBodyElement).text(msg['new_body']);
        $('#edit-modal').modal('hide');
});


text:
Q: Updating packages in Emacs I have the following setup for packages (not sure if there is a better recommended one):
(require 'package)
(setq package-archives '(("ELPA" . "http://tromey.com/elpa/")
                          ("gnu" . "http://elpa.gnu.org/packages/")
                          ("marmalade" . "http://marmalade-repo.org/packages/")))

; Apparently needed for the package auto-complete (why?)
(add-to-list 'package-archives
             '("melpa" . "http://melpa.milkbox.net/packages/") t)

(package-initialize)
(setq url-http-attempt-keepalives nil)

I have three questions related to the installation and updating of packages.
Q1. Is there a way to update the list of  available packages (and most recent versions) and update a specific package?
Q.2 What is the difference between the following package sources?:

*

*ELPA,

*GNU

*marmalade

*melpa

Q.3 Does it matter the order in which they are added to package-archives?

A: In terminal:
emacs

M-x list-packages

this puts you in the *packages* buffer
shift-u x

emacs will ask you (y/n), wait for updates
C-x k <ret>

this will kill the *packages* buffer and return you back to *scratch*
C-x-C-c

this will exit emacs, and let you relaunch via, but you might have to debug :(
emacs

my 2¢

A: This is more of an extended comment on jpkotta's answer.
This is an adjustment I am experimenting with for jpkotta's answer above:
(setq n 0)                                  ; set n as 0
(dolist (pkg pkgs-2b-present)               ; for each pkg in list
  (unless (or                               ; unless
           (package-installed-p pkg)        ; pkg is installed or
           (assoc pkg                       ; pkg is in the archive list
                  package-archive-contents))
    (setq n (+ n 1))))                      ; add one to n
(when (> n 0)                               ; if n > 0,
  (package-refresh-contents))               ; refresh packages

(replacing (when (not package-archive-contents) (package-refresh-contents))).
The package-list was not refreshing sufficiently often enough for my use-case.
I haven't considered if there is a more efficient solution to my problem; first, I've to see if the problem goes away with this adjustment.

A: *

*In order to automatically update the list of packages, only if there is no package list already, use the following:
(when (not package-archive-contents)
    (package-refresh-contents))

In order to update all installed packages, type package-list-packages, which will take you to the *Packages* buffer (and also update the list of packages), and then type U x.
package-refresh-contents unconditionally tries to download a package list from all repos you've added to package-archives; package-archive-contents is non nil if you have already downloaded the package list.

*ELPA is the original.  I don't think it's really maintained anymore, but I'm not sure.  I don't use it.
GNU is "official".  It's maintained along with Emacs, which means things should always work but updates and new packages don't come very often.
Marmalade is basically a website where you can upload a complete package, and it will be added to the marmalade repo.  You don't just submit a link to the package's upstream, and it doesn't quite automate the creation of the package completely.  I think this is the Right Thing, because you don't necessarily want to track upstream.  Unfortunately, it has been unmaintained for a while, but someone recently took it over so it should be back and better at some point.
Melpa takes a URL to e.g. the EmacsWiki lisp area or a github repo, and builds a package automatically from it.  Thus it is usually at most a day behind whatever it is tracking.  Although it tracks upstream, I've never had a problem in practice, and this is where most of my packages are from.  There is also Melpa Stable, which is like Melpa but grabs tagged revisions of the upstream repo instead of the latest revision.  Melpa stable has fewer packages than Melpa.
Org mode has its own package.el repo (http://orgmode.org/elpa/).
All of the package repos work the same, you just add them to your package-archives.
Here's a more in-depth blog post about this subject, which I mostly agree with.

*I'm not sure, but I think if a package is duplicated in different repos, the order the repos appear in in package-archives determines precedence.  I don't know if higher precedence is at the beginning or end of the list.
Update: In Emacs 25, there is a variable package-archive-priorities that you can use to prioritize your package repos (e.g. prefer ELPA over MELPA).

Here is the relevant section of my init.el, if you're interested:
(setq jpk-packages
      '(
        ac-dabbrev
        ...
        yasnippet
        ))

(package-initialize)
(add-to-list 'package-archives
             '("melpa" . "http://melpa.org/packages/"))
(add-to-list 'package-archives
             '("org" . "http://orgmode.org/elpa/"))

;; install any packages in jpk-packages, if they are not installed already
(let ((refreshed nil))
  (when (not package-archive-contents)
    (package-refresh-contents)
    (setq refreshed t))
  (dolist (pkg jpk-packages)
    (when (and (not (package-installed-p pkg))
             (assoc pkg package-archive-contents))
      (unless refreshed
        (package-refresh-contents)
        (setq refreshed t))
      (package-install pkg))))

(defun package-list-unaccounted-packages ()
  "Like `package-list-packages', but shows only the packages that
  are installed and are not in `jpk-packages'.  Useful for
  cleaning out unwanted packages."
  (interactive)
  (package-show-package-list
   (remove-if-not (lambda (x) (and (not (memq x jpk-packages))
                            (not (package-built-in-p x))
                            (package-installed-p x)))
                  (mapcar 'car package-archive-contents))))

A: Within Emacs, use M-x list-packages to list all packages which will automatically refresh the archive contents.  Afterwards use U to mark all upgradable packages to be upgraded, and x to actually perform the new updates.  Emacs will then fetch and install all upgrades, and ask you to whether to remove the old, obsolete versions afterwards.
You may also want to take a look at Carton which provides a more convenient way to manage your packages by declaring them in a dedicated file, and includes a convenient command line client to automatically install and upgrade packages declared in this way.

The order of package-archives does not matter.  Emacs aggregates the contents of all archives into a single coherent list of available packages and their versions, stored in package-archive-contents.
Upon package-install, Emacs will simply pick the newest version of a package, regardless of the originating archive.  For more control about package origin, MELPA provides the melpa package which allows to black- or whitelist packages from specified archives.