text:
Q: Facade a class without writing lots of boilerplate code? Let's say I have a class from a 3rd-party, which is a data-model. It has perhaps 100 properties (some with public setters and getters, others with public getters but private setters). Let's call this class ContosoEmployeeModel
I want to facade this class with an interface (INavigationItem, which has Name and DBID properties) to allow it to be used in my application (it's a PowerShell provider, but that's not important right now). However, it also needs to be usable as a ContosoEmployeeModel.
My initial implementation looked like this:
public class ContosoEmployeeModel
{
    // Note this class is not under my control. I'm supplied
    // an instance of it that I have to work with.

    public DateTime EmployeeDateOfBirth { get; set; }
    // and 99 other properties.
}

public class FacadedEmployeeModel : ContosoEmployeeModel, INavigationItem
{
    private ContosoEmployeeModel model;
    public FacadedEmployeeModel(ContosoEmployeeModel model)
    {
        this.model = model;
    }

    // INavigationItem properties
    string INavigationItem.Name { get; set;}

    int INavigationItem.DBID { get; set;}

    // ContosoEmployeeModel properties
    public DateTime EmployeeDateOfBirth
    {
        get { return this.model.EmployeeDateOfBirth; }
        set { this.model.EmployeeDateOfBirth = value; }
    }
    // And now write 99 more properties that look like this :-(
}

However, it's clear that this will involve writing a huge amount of boilerplate code to expose all the properties , and I'd rather avoid this if I can. I can T4 code-generate this code in a partial class, and will do if there aren't any better ideas, but I though I'd ask here to see if anyone had any better ideas using some super wizzy bit of C# magic
Please note - the API I use to obtain the ContosoEmployeeModel can only return a ContosoEmployeeModel - I can't extend it to return a FacededEmployeeModel, so wrapping the model is the only solution I can think of - I'm happy to be corrected though :)

A: The other approach may be suitable for you is to use  AutoMapper to map base class to your facade here is sample code:
class Program
    {
        static void Main(string[] args)
        {
            var model = new Model { Count = 123, Date = DateTime.Now, Name = "Some name" };

            Mapper.CreateMap<Model, FacadeForModel>();
            var mappedObject = AutoMapper.Mapper.Map<FacadeForModel>(model);

            Console.WriteLine(mappedObject);

            Console.ReadLine();
        }

        class Model
        {
            public string Name { get; set; }

            public DateTime Date { get; set; }

            public int Count { get; set; }
        }

        interface INavigationItem
        {
            int Id { get; set; }

            string OtherProp { get; set; }
        }

        class FacadeForModel : Model, INavigationItem
        {
            public int Id { get; set; }

            public string OtherProp { get; set; }
        }
    }

A: Resharper allows the creation of "delegating members", which copies the interface of a contained object onto the containing object and tunnels the method calls/property access through to the contained object.
http://www.jetbrains.com/resharper/webhelp/Code_Generation__Delegating_Members.html
Once you've done that, you can then extract an interface on your proxy class.


text:
Q: Laravel 5.5 - Envio de E-mail / Arquivo Env Estou migrando um site que tenho para Laravel 5 e me deparei com um problema.
Para enviar email no Laravel eu preciso preencher manualmente os dados de porta usuário e host no arquivo .env
Como no meu site eu tenho uma interface para o usuário interagir, eu acabo recebendo esses dados criptografados do banco de dados, por esse fato, se torna inviável preencher os dados MAIL_HOST, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD manualmente no arquivo .ENV, Por isso pergunto:
É possível repassar isso para o arquivo ENV ou acessar uma função na qual eu consiga passar diretamente esses dados e conseguir disparar o email?

A: Resolvi meu problema da seguinte forma:
O Lavavel possui uma forma de acesso na qual podemos setar em tempo de execução as propriedades diretamente usando config.
Como eu queria preencher as configurações de email,
precisei acessar as propriedades responsáveis pelo email que fica em Config\Mail.php.
Através do item acima consegui identificar o nome de cada propriedade para aí setar os valores dessa forma:
    config(['mail.host' => 'smtp.meusite.com.br']);
    config(['mail.port' => '587']);
    config(['mail.username' => 'usuario@meusite.com.br']);
    config(['mail.password' => 'senha']);

Abaixo o link da documentação para quem precisar!
https://laravel.com/docs/5.3/configuration#accessing-configuration-values

redpajama_set_name: RedPajamaStackExchange


text:
Q: AngularJs Directive gives undefined whole time I'm fairly new to angularjs directives, I've been struggling to get my directive to work the scope.durationTimeInput returns undefined no matter what I do.
(function () {
'use strict';

angular.module('BlurAdmin.theme')
    .directive('durationInput', durationInput);

/** @ngInject */
function durationInput($window) {
    var tpl = '
 \
          <input ng-model="duration_time.hours" type="number" class="hours" placeholder="00" min="0" max="3" step="1" style="width: 45px"> \
        : \
        <input ng-model="duration_time.minutes" type="number"  class="minutes" placeholder="00" min="0" max="59" step="1" style="width: 45px"> \

';

    return {
        restrict: 'A',
        template: tpl,
        replace: true,
        scope: {
            durationTimeInput: '='
        },
        link: function (scope, element, attrs) {
            console.log(scope);
            console.log(scope.durationTimeInput);
            scope.$watch('durationTimeInput', function (newValue) {
                var duration = moment.duration(newValue, 'minutes');

                scope.duration_time = {
                    hours: duration.hours(),
                    minutes: duration.minutes(),

                }
            });

            scope.$watchCollection('duration_time', function (newTime, oldTime) {
                if(scope.duration_time.hours==0&&scope.duration_time.minutes==0){
                    scope.duration_time.minutes=1;

                }
                scope.lapTimeInput = moment.duration(newTime, 'minutes').asMinutes();

            });
        }
    };
}

})();

I call it with div

The myIndex.duration is a variable.

A: Try

You need to add duration-time-input as per the scope you've defined


text:
Q: How to randomly sample elements between 2 rows in Pandas dataframe? I have a Pandas dataframe df in the following format:
   ColumnA.     ColumnB.      IsMatching
0 sadasdsad.    asdsadsad      True
1 asdsadsadas.  asdsadasd.     False
2 asdsadasd.    asdsadsad.     False
3 dfsdfsdfi     ijijiiijj.     False
4 sdasdsads.    asdsadsad      True
5 dfsdfsdfi     ijijiiijj.     False
6 jijijijij.    ijijijiji.     False
7 assdssads.    asd222sad      True

I would like to create a new dataframe, say new_df, which contains n randomly sampled rows with IsMatching == False from the original df between 2 True instances. For example, randomly select n rows between indices 0 and 4, similarly randomly select n rows between indices 4 and 7 etc.
A sample desired output for new_df would be (with sampling 2 rows randomly between the True instances in df). Note that it is possible that there is less than 2 rows between True instances - and in that case I would like the new_df to have whatever rows are there.
1 asdsadsadas.  asdsadasd.     False
3 dfsdfsdfi     ijijiiijj.     False
5 dfsdfsdfi     ijijiiijj.     False
6 jijijijij.    ijijijiji.     False

I searched about the df.sample() method in Pandas, but it doesn't seem to have a provision to sample between 2 rows. Any help and suggestion would be appreciated.

A: This should work:
from io import StringIO

data = StringIO("""
 ColumnA.     ColumnB.      IsMatching
0 sadasdsad.    asdsadsad      True
1 asdsadsadas.  asdsadasd.     False
2 asdsadasd.    asdsadsad.     False
3 dfsdfsdfi     ijijiiijj.     False
4 sdasdsads.    asdsadsad      True
5 dfsdfsdfi     ijijiiijj.     False
6 jijijijij.    ijijijiji.     False
7 assdssads.    asd222sad      True
""")

import pandas as pd
df = pd.read_csv(data, sep='\s+')

df['between_rows_group'] = df['IsMatching'].cumsum()

# take 1 sample
df.query('IsMatching==False').groupby('between_rows_group').sample(1)

# take samples with replacement
df.query('IsMatching==False').groupby('between_rows_group').sample(5, replace=True)

# take as many samples as are possible
df.query('IsMatching==False').groupby('between_rows_group').apply(lambda x: x.sample(min(5, len(x)))).reset_index(drop=True)


text:
Q: A polynomial counting some packings in $\mathbb Z/N\mathbb Z$ Given two integers $n$ and $N$ such that $N>{n+1\choose 2}$, we denote by $\alpha_n(N)$
the number of elements $(x_1,\dots,x_n)$ in $(\mathbb Z/N\mathbb Z)^n$ such that the
$2n$ elements $x_1,x_1+1,x_2,x_2+2,x_3,x_3+3,\dots,x_n,x_n+n$ of $\mathbb Z/N\mathbb Z$
are all distinct. The number $\alpha_n(N)$ is then a polynomial function of the form
$N^n-2nN^{n-1}+\dots$.
Is there a nice formula for the polynomial $\alpha_n(N)$?
Remark: The analogous problem such that $x_1,x_1+1,x_2,x_2+2,x_3,x_3+4,x_4,x_4+8,\dots,
x_n,x_n+2^{n-1}$ (and many similar variations and generalizations) is much easier and I have a solution (described in http://fr.arxiv.org/abs/1011.0975).


text:
Q: inconsistent behavior when using read or write parquette with pyarrow or without I just tried to write and read from a parquet file.
What i discovered is that based on the tried out combination, i should declare use_pyarrow=True on df.write_parquet, but false when reading for maximum performance.
If both are false ,reading the parquet is slower. Is this a bug?
Code to reproduce:
import time
import polars as pl
import numpy as np

df = pl.DataFrame(
    {
        f"{i}": np.random.randint(0, 120, size=3000000,)
        for i in ("A", "B", "C", "D", "E", "F", "G", "H", 'I', "J", 'K',)
    }
)

def repeat_read(arrow_read: bool, arrow_write: bool, n_times: int = 25) -> float:
    df.write_parquet('parquet', use_pyarrow=arrow_write)

    timings = []
    for i in range(n_times):
        time_start = time.time()
        some_var = pl.read_parquet('parquet', use_pyarrow=arrow_read)
        timings.append(time.time() - time_start)
    return sum(timings) / len(timings)

for i in range(3):
    print(f"Run {i}")
    read_write_false = repeat_read(arrow_read=False, arrow_write=False)
    print(f"Read-Write False: {read_write_false}")

    read_write_true = repeat_read(arrow_read=True, arrow_write=True)
    print(f"Read-Write Truee: {read_write_true}")

    read_false_write_true = repeat_read(arrow_read=False, arrow_write=True)
    print(f"Read False, Write True: {read_false_write_true}")

    read_true_write_false = repeat_read(arrow_read=True, arrow_write=False)
    print(f"Read True, Write False: {read_true_write_false}")
    print('---------------------------------------------------------\n')

Outcome:
Read-Write False: 0.11888686180114746
Read-Write Truee: 0.14296542167663573
Read False, Write True: 0.07793953895568848
Read True, Write False: 0.16698485374450683

The interesting thing is that while the performance boost still persists, it has diminishing returns when 'x' is equal to size in randint(0, x, size=1000000)


text:
Q: Using disabledDate in Antd Datepicker in table import React from "react";
import ReactDOM from "react-dom";
import { version, DatePicker, Table } from "antd";
import "antd/dist/antd.css";
import "./index.css";
import moment from "moment";

function disabledDate(current) {
  const now = moment();
  return (
    current &&
    (current < now.subtract(1, "day") || current > now.add(6, "months"))
  );
}

const columns = [
  {
    title: "date",
    dataIndex: "date",
    render: text => {
      return <DatePicker disabledDate={disabledDate} value={moment(text)} />;
    }
  }
];

const dataSource = [
  {
    key: "1",
    date: 1582863300000
  },
  {
    key: "2",
    date: 1583761200000
  }
];

ReactDOM.render(

antd version:{version}

,
  document.getElementById("root")
);

I'm using Antd Datepicker, and I want users can only select today and not after 6 months.But in table, the first row is okay, the second one can select yesterday.
Here is the codesandbox link:https://codesandbox.io/s/antd-reproduction-template-u1edz

A: It is not a problem with DatePicker as if you set the same two dates you will see the same result, the problem is with the second date you supply and with disabledDate logic.
const dataSource = [
  {
    key: '1',
    date: 1582863300000
  },
  {
    key: '2',
    // set the same date and see no diff date: 1582863300000
    date: 1583761200000
  }
];

As I understand, you want to implement the next logic:
today <= can be selected <= today + 6 months

Which is:
function disabledDate(current) {
  const now = moment();
  return (
    current && (now.endOf('day') > current || current > now.add(6, 'months'))
  );
}


text:
Q: Jquery Image like .. image replace on mouseover I would replace Pictures on mouseover.
I Found a nice script here, but the problem is all images on the page get replaced.
This way i would filter the images while selecting.
I added each picture the ending "_rep".
The code im using:
$("img")
  .mouseover(function() {
    var src = $(this).attr("src").match(/[^\.]+/) + "_akt.png";
    $(this).attr("src", src);
  })
  .mouseout(function() {
    var src = $(this).attr("src").replace("_akt.png", ".png");
    $(this).attr("src", src);
  });

Search for something like that:
$("img like %_rep%")
//code mouseover, mouseout

A: If I understand correctly, you want to replace images which end of names are _rep ?
In that case you can do that :
$('img[src$="_rep.png"]')

A: use this
$("img[src$='_rep.png']")

[src] means all tags with an src attribute. and [src$='_rep.png'] means all tags with an src attribute ending with '_rep.png'
and take a look here https://api.jquery.com/attribute-ends-with-selector/
I recommend you look through all different kinds of JQuery selectors in the provided link.


text:
Q: JRebel - sync new gradle jars on classpath Can jrebel detect a jar file has been added to maven/gradle and then automatically add it my libs folder and add it to the classpath?
For example I'm running IntelliJ and Jetty and I make a gradle change to add a new version of a jar dependency and then click "gradle refresh."
Can jrebel be set up to load that jar? Otherwise this requires a full restart which partially makes jrebel less useful.

A: The short answer is no.
JRebel works by reloading individual class files, but not whole JARs.
If you add a new dependency or update the version of an existing dependency then it won't get reloaded.
However, if this library you're updating or adding is your own internal library that you build yourself, then it is possible to reload the changes.
In that case you need to build a rebel.xml file into the root of that library jar and configure it to point to the build directory of the library.


text:
Q: How to get email from each line and send that line as email to same address, in csh I have a text file. I need to select the address mail from each line and send each line to the correspond address.
I try to use foreach and awk to select the address
set valuea = `awk '{print $3}' FichierNote`

Could you please give me a way how can i do this? This is the data in the file.
    8 mariamms maria@gmail.com (cto;MDG_MMS)
    7 lj16 jean-christophe@gmail.com (gnb;DIG_FMTRD)
    7 imbse emma.imbspi@gmail.com (gnb;MDG_MMS)
    6 viviens stephano.vien@gmail.com (gnb;IMD)
    5 alberghv vinco.alrghina@gmail.com (cto;ADG)

A: May be there is an simpler way, but this is what I could think of.
while read -r line; do echo "$line"|mail -s "your_subject" "$(echo "$line"|awk '{print $3}')"; done < emailList.txt

Replace your_subject with the main subject.
Assumption: The email is at 3rd column.
Explanation:

*

*while read -r line;do...done < file will read the file line by line
and each line will be stored in variable $line.

*"$(echo"$line"|awk '{print $3}')" will get the email address to pass to
mail command.

*do echo "$line"|mail -s "your_subject" "$(echo "$line"|awk '{print
$3}')"; will send the line as message body to the email address
derived in above step.

A: You need to create a script like below:-
    #!/usr/bin/csh

while read -r line
do
  mailId=$(echo "$line" | awk '{print $3}')
  #echo $mailId
  #here you have to put your mail command
  #example 'sendmail -f source_mail_id.com $mailId < mailContentFile.txt'
done < FichierNote

How will the above script work? In while loop it will read each line and awk command will cut the mail id each time and will store in mailId variable. Now you need to put your mail command and put $mailId variable as email address.

A: Here's the script I ended up using, with csh:
#!/bin/csh
foreach line ( "`cat FichierNote`" )
    echo $line | mail -s "Subject" `echo $line | awk '{print $3}'`

end


text:
Q: How to fix "AAPT: No resource identifier found for attribute 'appComponentFactory' in package 'android'" I've got a project more than 6 month. Early it built successful. But now i've got a error
...app/build/intermediates/manifests/full/debug/AndroidManifest.xml:56: AAPT: No resource identifier found for attribute 'appComponentFactory' in package 'android'
I've tried to change gradle versions, change node versions
There is my app/build.gradle file

import com.android.build.OutputFile

buildscript {
    repositories {
        maven { url 'https://plugins.gradle.org/m2/' } // Gradle Plugin Portal
    }
    dependencies {
        classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.1, 0.99.99]'
    }
}

apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'

/**
 * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
 * and bundleReleaseJsAndAssets).
 * These basically call `react-native bundle` with the correct arguments during the Android build
 * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
 * bundle directly from the development server. Below you can see all the possible configurations
 * and their defaults. If you decide to add a configuration block, make sure to add it before the
 * `apply from: "../../node_modules/react-native/react.gradle"` line.
 *
 * project.ext.react = [
 *   // the name of the generated asset file containing your JS bundle
 *   bundleAssetName: "index.android.bundle",
 *
 *   // the entry file for bundle generation
 *   entryFile: "index.android.js",
 *
 *   // whether to bundle JS and assets in debug mode
 *   bundleInDebug: false,
 *
 *   // whether to bundle JS and assets in release mode
 *   bundleInRelease: true,
 *
 *   // whether to bundle JS and assets in another build variant (if configured).
 *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
 *   // The configuration property can be in the following formats
 *   //         'bundleIn${productFlavor}${buildType}'
 *   //         'bundleIn${buildType}'
 *   // bundleInFreeDebug: true,
 *   // bundleInPaidRelease: true,
 *   // bundleInBeta: true,
 *
 *   // the root of your project, i.e. where "package.json" lives
 *   root: "../../",
 *
 *   // where to put the JS bundle asset in debug mode
 *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
 *
 *   // where to put the JS bundle asset in release mode
 *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in debug mode
 *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in release mode
 *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
 *
 *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
 *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
 *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
 *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
 *   // for example, you might want to remove it from here.
 *   inputExcludes: ["android/**", "ios/**"],
 *
 *   // override which node gets called and with what additional arguments
 *   nodeExecutableAndArgs: ["node"]
 *
 *   // supply additional arguments to the packager
 *   extraPackagerArgs: []
 * ]
 */

apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion 26
    buildToolsVersion '27.0.3'

    defaultConfig {
        applicationId "com.stationfive.wantfeed.dev"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    compile project(':react-native-svg')
    compile project(':react-native-linear-gradient')
    compile project(':react-native-image-picker')
    compile project(':react-native-code-push')
    compile project(':bugsnag-react-native')
    compile project(':react-native-onesignal')
    compile project(':react-native-fbsdk')
    implementation 'com.facebook.android:facebook-android-sdk:4.34.0'
    implementation project(':react-native-fbsdk')
    compile project(':react-native-google-signin')
    implementation project(':react-native-image-picker')
    implementation project(':bugsnag-react-native')
    implementation project(':react-native-svg')
    implementation project(':react-native-code-push')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    //noinspection GradleCompatible
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation 'com.google.firebase:firebase-core:16.0.5'
    implementation "com.facebook.react:react-native:0.20.1"  // From node_modules
    implementation project(':react-native-linear-gradient')
    compile project(':react-native-video')
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}
apply plugin: "com.google.gms.google-services"


text:
Q: Read/Write text files in Python I'm fairly new to Python and don't fully understand all items and I've been given a base for a programme and I need to alter bits, here's what I have so far:
    import sys, os

    filename   = 'C:\main\in.txt'
    resultFile = 'C:\main\out.txt'

    try:
       file = open( filename, "w" )
    except Exception, e:
        logger.critical( "Failed to create file \"%s\" : %s" % ( filename, e )

    for name, value in brg.iteritems():
        if -1 == string.find( name, "CTRL" ) and name not in [ "name", "type" ]:
            file.write( "%s = %s\n" % ( name, value ) )
            file.close()

   # run the Fortran programme

    resultCode = os.system( '%sC:\main\Debug\main.exe -i %s -o %s.result' % ( options[ OPTION_script_path ], filename, filename ) )

    # Read the results

    try:
        file = open( resultFile, "r" )
    except Exception, e:
        logger.critical( "Failed to create file \"%s\" : %s" % ( resultFile, e )

        regexp = re.compile( "^(?P<name>.*)\\s*=\\s*(?P<value>.*)$" )
        for row in file.xreadlines():
        row = row.strip( "\\r\\n \\t" )
        m = regexp.match( row )
        if m:
                name = m.group( "name" )
                value = m.group( "value" )
                brg[ name ] = value

I am completely lost as to why it doesn't currently work as it's finding a Syntax error with: for name, value in bearing.iteritems():
I'm not sure whether some mistakes are due to indentation..
I also don't quite understand the last part. I have an output text file and this is what the final part is reading. I have however don't understand (in particular) this line:
regexp = re.compile( "^(?P<name>.*)\\s*=\\s*(?P<value>.*)$" )

With the RE's, I don't understand exactly what it means by 'matching' what is the ^, $ and ?P matching to what? Also what does 'regexp' represent?
Thank you for your time =)

A:         logger.critical( "Failed to create file \"%s\" : %s" % ( filename, e )

Has 2 left ( and only 1 right ).  This appears to be a syntax error.
Since the statement isn't complete, Python continues parsing.  The error message shows up on the following line.

Read this: http://docs.python.org/library/re.html#regular-expression-syntax.  Then update your question with more specific aspects of the regular expression which confuse you.  Regular expressions are a (potentially) deep topic.


text:
Q: How can I use special characters (i.e., mu symbols) in a GitHub R package? I have an R Cran package that I have served on GitHub. Some of the scripts have a mu symbol embedded in the code. When I try to load the script using devtools,
I receive the following error message:

install_github("user/flamer")
  Downloading github repo user/flamer@master
  Installing flamer
  "C:/PROGRA~1/R/R-31~1.2/bin/x64/R" --no-site-file --no-environ --no-save  \
    --no-restore CMD INSTALL  \
    "C:/Users/Luke/AppData/Local/Temp/RtmpOgPoCC/devtools245043733096/thejohncrawford-flamer-af78ede"  \
    --library="C:/Users/Luke/Documents/R/win-library/3.1" --install-tests

*

*installing source package 'flamer' ...
** R
Error in parse(outFile) :
C:/Users/Luke/AppData/Local/Temp/RtmpOgPoCC/devtools245043733096/thejohncrawford-flamer-af78ede/R/tau_correct.R:27:28: unexpected input
26: #SpCond
27: X<-instrument_table$SpCondμ
                           ^
ERROR: unable to collate and parse R files for package 'flamer'

The error occurs on line 27, where there is suppose to a mu symbol rather than "μ" It should read "...SpCondμ"
I believe the error occurs as R studio pulls scripts off of git. Has anyone else encountered this problem and know to allow special characters to load from git?
Thanks


text:
Q: PHP mysql duplicated rows I have a query in MySQL using php. The query is below
$sql = "select m.id, s_1.username player_1, s_2.username player_2, current_step, won
from {$table_prefix} match m left join {$table_prefix}session s_1 on s_1.id = player_1
left join {$table_prefix}session s_2 on s_2.id = player_2
where current_step < 10";

The problem I'm having the query works great but when it needs to be executed quickly(back to back) I'm getting duplicated rows. How would I go about preventing duplicate rows.
Thank you.

A: You will need to use a DISTINCT to get only unique return rows.
$sql = "select DISTINCT m.id, s_1.username player_1, s_2.username player_2, current_step, won from {$table_prefix}match m left join {$table_prefix}session s_1 on s_1.id = player_1 left join {$table_prefix}session s_2 on s_2.id = player_2 where current_step < 10";

http://dev.mysql.com/doc/refman/5.0/en/distinct-optimization.html


text:
Q: How to add new items in listview at the top in android I am having a ListView in which i am showing list items fetched from shared preference, now when every time new list item includes it includes below the first one, is there any way to update listview in such a way that new item included will be at the top. In short incoming item should be at top. Below is my code base :
I tried
Collections.reverse(yourList);

before setting adapter but it works sometimes and sometimes when again i open activity it won't work

A: Can you try by replacing the
items.add(new EntryItem(first, second));

in addItems() by
items.add(0, new EntryItem(first, second));

A: You can use the following attribute in your XML in your ListView node, however I might be wrong, but I actually think ListView stacks on top already by default...
android:stackFromBottom

Used by ListView and GridView to stack their content from the bottom.

Must be a boolean value, either "true" or "false".

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol stackFromBottom.

http://developer.android.com/reference/android/widget/AbsListView.html#attr_android%3astackFromBottom


text:
Q: How to improve Flask development workflow I have just started learning how to build small Web apps with Python and Flask but am having some issues with the workflow. The way I am currently developing is:

*

*Make a change to the app (HTML, CSS, JS, Python Flask code etc)

*Stop the server

*Clear the browser cache to remove the old static assets

*Start the server

*Reload my app in the browser

This is becoming a complete chore. I have come from developing with Node/Express and React where I have been using nodemon (https://www.npmjs.com/package/nodemon) to monitor any application changes. The server restarts automatically as soon as you save your app, with any changes detected immediately being reflected in the browser.
Is there something like this for Flask?

A: From the answers given in the comments above, the solution is to run the Flask development server using the Flask CLI like so:
export FLASK_ENV=development
flask run

This runs the Flask reloader so changes to the Flask application and any HTML are updated when the page reloads.
To fix the problem of the browser caching css files which have to be cleared to see any changes, I referred to this Flask css not updating SO question and the comment by @Aylen.
Simply reload the Web page for your app using
Ctrl+shift+R

This reloads the page and clears the cache at the same time.


text:
Q: Split multiple JSON string into strucutred table using Google App Script I am trying to split a data set with an ID and JSON string into a structured table.
The difficult part is I need it to be dynamic, the JSON string varies often and I want headings to be determined by the unique values in the input column at that time. I need the script to be able to create headings if the string changes without needed to recode the script.
We have about 150 different JSON strings we are hoping to use this script on, without recoding it for each one. Each string has lots of data points.
I have a script working but it splits them one by one, need to build something that will do bulk in one go, by looping through all outputs in B and creating a column for each unique field in all the strings, then populating them.
The script works if I paste the additional info straight in, however I am having trouble reading from the sheet

  var inputsheet = SpreadsheetApp.getActive().getSheetByName("Input");
  var outputsheet = SpreadsheetApp.getActive().getSheetByName("Current Output");

  var additionalinfo = inputsheet.getRange(1,1).getValue()
  Logger.log(additionalinfo)

  var rows = [],
      data;

    for (i = 0; i < additionalinfo.length; i++) {
        for (j in additionalinfo[i]) {

          dataq = additionalinfo[i][j];

          Logger.log(dataq);

          rows.push([j, dataq]);
    }
      dataRange = outputsheet.getRange(1, 1, rows.length, 2);
      dataRange.setValues(rows);
  }
}

Here is a link to the sample data. Note that in Sample 1 & 2 there are different headings, we need the script to identify this and create headings for both
https://docs.google.com/spreadsheets/d/1BMiVuAgDbibLw6yUG3IZ9iw4MZTaVVegkw_k3ItQ4mU/edit#gid=0

A: Try this script that produces dynamic headers based on the json that has been read. It collects all json data, get its keys, and remove the duplicates.
Script:
function JSON_SPLITTER() {
  var spreadsheet = SpreadsheetApp.getActive();
  var inputsheet = spreadsheet .getSheetByName("Input");
  var outputsheet = spreadsheet .getSheetByName("Current Output");
  var additionalinfo = inputsheet.getDataRange().getValues();
  var keys = [];

  // prepare the additionalInfo  data to be parsed for later
  var data = additionalinfo.slice(1).map(row => {
    // collect all keys in an array
    if (JSON.parse(row[1]).additionalInfo) {
      keys.push(Object.keys(JSON.parse(row[1]).additionalInfo));
      return JSON.parse(row[1]).additionalInfo;
    }
    else {
      keys.push(Object.keys(JSON.parse(row[1])));
      return JSON.parse(row[1]);
    }
  });

  // unique values of keys, modified to form header
  var headers = [...new Set(keys.flat())]
  // Add A1 as the header for the ids
  headers.unshift(additionalinfo[0][0]);
  // set A1 and keys as headers
  var output = [headers]

  // build output array
  additionalinfo.slice(1).forEach((row, index) => {
    var outputRow = [];
    headers.forEach(column => {
      if(column == 'Contract Oid')
        outputRow.push(row[0]);
      else
        outputRow.push(data[index][column]);
    });
    output.push(outputRow)
  });
  outputsheet.getRange(1, 1, output.length, output[0].length).setValues(output);
}

Output:

Update:

*

*Modified script for no-additionalInfo key objects.


text:
Q: Building a product page with gallery using jQuery I'm helping a client build a product site, one of the pages displays the details of the products their selling. One of the requirements of the product detail page is to have multiple images of the product (which I'm fine with, going to implement a slider) however the product images will also be in different colours. Depending on the colour the user selects the relevant product images are shown. I'm having trouble with how implement the colour select option.
I am using BX-Slider (http://bxslider.com/) on another page so would like to be able to reuse the same slider. Anyone give me any pointers?
I've included the design of the product page here:

Would much appreciate any help!!

A: I've never used bxslider, but it looks like you could use this to your advantage:
http://bxslider.com/examples/custom-next-prev-selectors
If you create custom prev/next selectors then you can create an index, so that you know which colour is currently selected in the slider and then display the corresponding image. With the custom selectors, this would be done in the JQuery.click() functions of the two spans (in the example).
$("#slider-next").click(...change image to index + 1...);
$("#slider-prev").click(...change image to index - 1...);


text:
Q: Lorentz scalar of chiral fermions In lectures on Gauge Theory by David Tong (sec. 5.6.1), the author suggests a Lorentz scalar $\epsilon^{\alpha\beta} \psi_{+\alpha}\psi_{+\beta}$ where $\psi_+$ is a right-handed fermion and $\alpha,\beta$ are spinor indices.

We can take a pair of left- or right-handed fermions and form a Lorentz scalar $\epsilon^{\alpha\beta}\psi_{+\alpha}\psi_{+\beta}$ where, for once, we've explicitly written the $\alpha,\beta$, spinor indices. This means that it's possible to contract the spinor indices such that each baryon above is left-handed.

I wonder how to derive it and I think we need a Dirac conjugate fermion $\bar{\psi}$ or $\bar{\psi}_-$ to form a Lorentz scalar quantity. Do you have any ideas?


text:
Q: Cannot add instance of type 'MultiBinding' to a collection of type 'DoubleCollection' Error: I am trying to use a IMultiValueConverter I wrote, but Intellisense is giving me this error "Cannot add instance of type 'MultiBinding' to a collection of type 'DoubleCollection'. Only items of type 'double' are allowed."
Q: I do not understand what this error means. I've used other converters to modify the StrokeDashArray properties in other paths; however, I am not sure how to use a multibinding. Can someone explain why I am getting this error, and how I remove this error?
Details: The converter is named "DashedWhenValue1ArrayEqualsValue2ArrayConverter" and I have defined it above as a StaticResource. Here are the interesting parts of my converter
. . .
public DoubleCollection DoubleCollectionWhenEqual { get; set; }
public DoubleCollection DoubleCollectionWhenNotEqual { get; set; }
public DoubleCollection DoubleCollectionWhenValueIsNull { get; set; }

. . .

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{

  if (values == null || values.Length < 2)
  {
    return this.DoubleCollectionWhenValueIsNull;
  }

  if ( !(values[0] is Array) || !(values[1] is Array) )
  {
    return this.DoubleCollectionWhenNotEqual;
  }

  object[] array1 = values[0] as object[];
  object[] array2 = values[1] as object[];

  if (array1.Length != array2.Length)
  {
    return this.DoubleCollectionWhenNotEqual;
  }

  for (int i = 0; i < array1.Length; i++)
  {
    if (array1[i] != array2[i])
    {
      return this.DoubleCollectionWhenNotEqual;
    }
  }

  return this.DoubleCollectionWhenEqual;

}
. . .

I use my converter in the view here
<Path x:Name="some_Path" Data="M7,4.167 L7,162.08887" HorizontalAlignment="Right" Margin="0,0,-391.5,-871" StrokeStartLineCap="Square" StrokeEndLineCap="Square" Stroke="#FF33CC33" StrokeThickness="10" Width="10.5" RenderTransformOrigin="0,0" Height="167.167" VerticalAlignment="Bottom" >
      <Path.StrokeDashArray>
        <MultiBinding Converter="{StaticResource DashedWhenValue1ArrayEqualsValue2ArrayConverter}"> <!-- Error starts here -->
          <Binding Path="ModelViewProperty1" />
          <Binding Path="ModelViewProperty2" />
        </MultiBinding> <!-- Error ends here -->
      </Path.StrokeDashArray>
    </Path>

A: I was able to replicate your error in Visual Studio 2015. It does appear to be simply a bug with the XAML editor, not an actual problem with your XAML or converter. When I run the app, I get different dashing depending on whether ModelViewProperty1 and ModelViewProperty2 both have values and are equivalent.
So, my advice would be to ignore this particular error.
P.S. Just for fun, here is a more succinct way to write your Convert method using LINQ:
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
    var arrays = values
        .OfType<Array>()
        .Select(x => x.OfType<object>())
        .ToList();
    if (arrays.Count != 2) return DoubleCollectionWhenValueIsNull;
    return arrays[0].SequenceEqual(arrays[1]) ? DoubleCollectionWhenEqual : DoubleCollectionWhenNotEqual;
}


text:
Q: SQL Hasmany Query select 1 I have two tables which I am trying to query.
Stock_Table

*

*Stock_Code

*Stock_Name

*Physical_Stock

Order_Table

*

*Order_Date

*Quantity

*Stock_Code

I'm after all stock records where the physical stock is greater than 0 and the last date it was ordered.
I thought the following query would do it but this duplicates the stock records per how many orders there are.
SELECT
    Stock_Code,
    Physical_Stock,
    Order_Date
FROM Stock_Table
INNER JOIN Order_Table
    ON Stock_Table.Stock_code = Order_Table.Stock_Code
WHERE Physical_Stock <> 0

A: Greater than 0 or <> 0 which is it?
You just need to use aggregate function max() to get the max order date since multiple orders could be placed for a given stock code.  and since you use aggregation, a group by is needed for the non-aggregated columns.
SELECT Stock_Code, Physical_Stock, max(Order_Date)
FROM Stock_Table
INNER JOIN Order_Table
  ON Stock_Table.Stock_code = Order_Table.Stock_Code
WHERE Physical_Stock <> 0
GROUP BY Stock_Code, Physical_Stock

A: --So, what is happening, we use ROW_NUMBER() OVER and PARTITION BY
--ROW_NUMBER() Adds in the number for that particular record based on the PARTITION BY
--stock_code then orders the records by the order_date Descending
--Then selects from the subquery each record with row number = 1
--This produces the first record for each unique stock_code
--and since it is ordered by order_date descending, you get the most
--recent purchase
SELECT *
FROM
(
   SELECT st.stock_code, physical_stock, order_date, ROW_NUMBER() OVER(PARTITION BY
   st.[stock_code] ORDER BY [order_date] DESC) AS [Row_Number]
   FROM Stock_Table AS st
   INNER JOIN Order_Table AS ot
   ON st.stock_code = ot.stock_code
) AS x
Where x.physical_stock <> 0 AND x.[Row_Number] = 1

A: Here's the cross apply top 1 solution:
SELECT Stock_Code, Physical_Stock, Order_Date
FROM
    Stock_Table
    CROSS APPLY
    (
        SELECT TOP 1 Order_Date
        FROM Order_Table
        WHERE Stock_Table.Stock_code = Order_Table.Stock_Code
        order by Order_Date desc
    )q
Where Physical_Stock <> 0

This enables you to bring more columns from the most recent orderdate if you wish, too.

A: Using GroupBy
SELECT
  Stock_Table.Stock_Code,
  Max(Physical_Stock) As Stock,
  Max(Order_Date) As LastDate
FROM
  Stock_Table INNER JOIN
  Order_Table ON Stock_Table.Stock_code = Order_Table.Stock_Code
Where Physical_Stock > 0
Group By Stock_Table.Stock_Code


text:
Q: AngularJS ng-options custom attribute I currently have the following directive on my select.
ng-options="option.value as option.title for option in exportTypes"
$scope.exportTypes = an array of objects each with title, value, and generatesFile attributes. I'd like the generatesFile attribute to be added as a data-generates-file attribute on each <option> that is generated for this select.
Any thoughts on how to do this?

A: Maybe someone will correct me but I'm pretty sure you won't get this kind of control out of ng-options. Angular manages the select behind the scenes for you when you use this, which is nice 90% of the time but can be limiting in situations like yours. I'm not sure what benchmarks you're looking at but I'd be willing to bet an ng-repeat on the option elements is comparable in performance to using ng-options.
I'd go with something like this:
<select ng-model="selectedExportType">
    <option ng-repeat="exportType in exportTypes" data-generates-file="{{exportType.generatesFile}}" value="{{exportType.value}}">
        {{exportType.title}}
    </option>
</select>

Edit:
Of course, this assumes you really do need that attribute on there. If all you need is access to that attribute on select then this is where ng-options shines. Simply remove the option.value as bit from your select and then you get the whole object back from your array when you make a selection.
http://plnkr.co/edit/6XPaficTbbzozSQqo6uE?p=preview
You can see in that demo that the selected item is the whole object, complete with someAttr property which was never used in the select at all. If you inspect the DOM you won't see it. Angular tracks all this behind the scenes.

A: Here is a directive which can be used to add custom attributes when using ng-options with <select>, so you can prevent using ng-repeat
.directive('optionsCustomAttr', function ($parse) {
        return {
            priority: 0,
            require: 'ngModel',
            link: function (scope, iElement, iAttrs) {
                scope.addCustomAttr = function (attr, element, data, fnDisableIfTrue) {
                    $("option", element).each(function (i, e) {
                        var locals = {};
                        locals[attr] = data[i];
                        $(e).attr(iAttrs.customAttrName ? iAttrs.customAttrName : 'custom-attr', fnDisableIfTrue(scope, locals));
                    });
                };
                var expElements = iAttrs['optionsCustomAttr'].match(/(.+)\s+for\s+(.+)\s+in\s+(.+)/);
                var attrToWatch = expElements[3];
                var fnDisableIfTrue = $parse(expElements[1]);
                scope.$watch(attrToWatch, function (newValue) {
                    if (newValue)
                        scope.addCustomAttr(expElements[2], iElement, newValue, fnDisableIfTrue);
                });
            }
        };
     })

And then in your select,
<select ng-model="selectedExportType" ng-options="option.value as option.title for option in exportTypes"
                  options-custom-attr="option.generatesFile for option in exportTypes"
                  custom-attr-name="data-generates-file">
</select>

Note:  This is a modified version of optionsDisabled directory mentioned here

A: Or a simpler solution:
<select ng-model="selectedItem" ng-options="item as item.name for item in items" option-style="items"></select>

And the directive which inserts whatever you want in each option tag.
angular.directive('optionStyle', function ($compile, $parse) {
    return {
        restrict: 'A',
        priority: 10000,
        link: function optionStylePostLink(scope, elem, attrs) {
            var allItems = scope[attrs.optionStyle];
            var options = elem.find("option");
            for (var i = 0; i < options.length; i++) {
                angular.element(options[i]).css("color", allItems[i].yourWantedValue);
            }
        }
    };
});


text:
Q: Run query in TFS from another server without visual studio installed I try run query take details from TFS but i get this error
"System.NullReferenceException: Object reference not set to an instance of an object.
   at TFSWebService.WorkItemQuery.GetWorkItemForReleaseState()"
I add this DLL to my bin
Microsoft.TeamFoundation.Client.dll
Microsoft.TeamFoundation.Common.dll
Microsoft.TeamFoundation.Common.Library.dll
Microsoft.TeamFoundation.dll
Microsoft.TeamFoundation.VersionControl.Client.dll
Microsoft.TeamFoundation.VersionControl.Common.dll
Microsoft.TeamFoundation.VersionControl.Common.Integration.dll
Microsoft.TeamFoundation.WorkItemTracking.Client.dll
Microsoft.TeamFoundation.WorkItemTracking.Proxy.dll

but still same error
NOTE: need to fixed without install visual studio

A: You can try to install a small package. Download and more Information:
Team Foundation Server 2012 Update 1 Object Model Installer
Stand-alone installer for TFS object model


text:
Q: My Win32 application won't exit the main loop This is my main loop:
    while(TRUE)
    {

    PeekMessage(&msg,hWnd,0,0,PM_REMOVE);
        if (msg.message==WM_QUIT)
            break;
        TranslateMessage(&msg);
        DispatchMessage(&msg);

    }

and this is my callback procedure:
 LRESULT CALLBACK WinProc(HWND hWnd,UINT msg1,WPARAM wParam,LPARAM lParam)
 {
    switch(msg1)
    {
        case WM_DESTROY  :
        {
            PostQuitMessage(0);
            return 0;
        }
        break;
    }

    return DefWindowProc(hWnd,msg1,wParam,lParam);
}

I found out that when I press Close button  WM_NCLBUTTONDOWN will be returned by the PeekMessage function in the next loop, and no WM_QUIT!

A: The correct way to do a message loop is
BOOL bRet;
MSG msg;
while ((bRet = GetMessage(&msg, hWnd, 0, 0)) != 0)
{
    if (bRet == -1)
    {
        // handle the error and possibly exit
    }
    else
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

You can use PeekMessage if you really need to... but why are you ignoring the return value?
Also, note that this is specific to a window. I believe PostQuitMessage is for a thread... I don't remember it off the top of my head, but you might need to pass NULL instead of hWnd.
If you have any other windows, that may hijack their message loop as well -- I don't think it's usually an issue, but it might potentially be one; keep that in mind.

A: Here's some code I found. It should give you something to work with.
    // Main message loop:
do
{
    while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
    {
        if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    // Run game code here.
    gTradeApp->ExecuteNextAction();
}
while (msg.message != WM_QUIT);

and the WndProc
LRESULT CALLBACK WndProc(HWND aHWnd, UINT aMessage, WPARAM aWParam, LPARAM aLParam)
{
    switch (aMessage)
    {
    case WM_COMMAND:
        return HandleCommand(aHWnd, aMessage, aWParam, aLParam);

    case WM_DESTROY:
        PostQuitMessage(0);
        break;

    default:
        return DefWindowProc(aHWnd, aMessage, aWParam, aLParam);
    }

    return 0;
}

A: I recommend sticking with this, to ensure errors (-1) returned by GetMessage can be handled properly:
while(GetMessage(&Msg, NULL, 0, 0) > 0) {
    TranslateMessage(&Msg);
    DispatchMessage(&Msg);
}

Also, another error is not handling WM_CLOSE properly. Try this instead to make your program actually listen to WM_CLOSE (the close button):
LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) {
    switch(Message) {
        case WM_CLOSE: {
            DestroyWindow(hwnd); // this
            break;
        }
        case WM_DESTROY: {
            PostQuitMessage(0);
            break;
        }
        default:
            return DefWindowProc(hwnd, Message, wParam, lParam);
    }
    return 0;
 }


text:
Q: Is the reflector $\mathcal{E} \rightarrow \text{Sep}_j \mathcal{E}$ left exact? (j is a local operator) According to Mac Lane & Moerdijk, Ch V, Ex 4, the left adjoint $\mathcal{E} \rightarrow \text{Sep}_j\,\mathcal{E}$ of the inclusion is left exact, but the proof is left as an exercise for the reader. I think it is not, and have what I think is a simple counter-example (below). For the purposes of this post, let the functor be called $M$.
Attempting to produce a proof (which hinges on the preservation of equalisers) led me to attempt to adapt the proof in V.3 of the mentioned book and the closest I got was that $M E \subseteq K \subseteq \overline{M E}$ in $\text{Sub}(M A)$, where $E \rightarrowtail A$ is the equaliser of arbitrary $f,g : A \rightarrow B$ and $K \rightarrowtail M A$ is a known equaliser of $M f, M g$.
I ventured into Sketches of an Elephant for comparison's sake and found the following in the comments after A.4.4.8: "We saw in 4.4.7 that the separated reflector $M$ preserves monomorphisms but it is not cartesian in general. [...]". (and by cartesian I suppose Prof. Johnstone means "left exact"), hence I am inclined to believe that the question in MacLane and Moerdijk is wrong.
The simple counterexample: Let $2$ be the category with objects $\bot$ and $\top$ and an arrow $\bot \rightarrow \top$. Let $\mathcal{E}$ be the category of presheaves on $2$. Let $j$ be the local operator corresponding to the "atomic topology". Let $B$ be the pre-sheaf for which $B \top = \{1,2\}$ and $B \bot = \{1\}$ and let $E$ be the pre-sheaf for which $E \top = \{\}$ and $E \bot = \{1\}$. Then there are precisely two arrows $f,g : 1_\mathcal{E} \rightarrow B$ and $E \rightarrowtail A$ is the equaliser of $f,g$. But passing through the functor $M$, and one notes that $E \rightarrowtail 1_\mathcal{E}$ is not the equaliser of two copies of the identity $1_\mathcal{E} \rightarrow 1_\mathcal{E}$.
For the record, here is the exact text of the question, i have not yet attempted the rest of it:

*Consider, for the topology $j$ on a topos $\mathcal{E}$, the subcategories $\text{Sh}_j\,\mathcal{E} \subseteq \text{Sep}_j\,\mathcal{E} \subseteq \mathcal{E}$. First prove that the left adjoint $\mathcal{E} \rightarrow \text{Sep}_j\,\mathcal{E}$ of Corollary 3.6 is left exact. Next prove that if $\text{Sep}_j\,\mathcal{E}$ is also a topos, then it must co-incide with $\text{Sh}_j\,\mathcal{E}$. (Hint: prove that the subobject classifier of $\text{Sep}_j\,\mathcal{E}$ must be a sheaf).


text:
Q: problems deploying a maven application with mvn command I have a maven application under eclipse . The jsp pages and WEB-INF folder are located under the path NomeMiaApplicazione\src\main\webapp. I run these commands : mvn clean ,
mvn eclipse: eclipse and mvn compile under the root folder of the application, and in all three cases, the build is successful. However when I access the folder ( into the workspace )
. metadata.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\NomeMiaApplicazione
, there are no jsp pages . what would be the solution for this problem ? thks !

A: It is necessary to clarify the role of the commands you used and their impact on Eclipse.
The mvn eclipse:eclipse command creates the Eclipse project files, in order to save you the hassle of configuring a new project and identifying all the sources for it. This command is also equivalent to creating a new Eclipse project from an existing Maven project using the m2e Eclipse plugin. See also this page regarding the eclipse:eclipse command. That being said, you only need to run such command once, and then import the resulting project into Eclipse.
Secondarily, mvn compile builds your source files into the target directory of your NomeMiaApplicazione root folder. This command does not involve Eclipse in any way. Also, web resources are still not packaged.  To package them, you need to issue mvn package: you will then find the <artifact>-<version>.war file again under target, and the pre-packaged content under target\<artifact>-<version>. Beware that, in order to account for the webapp content, your Maven packaging must be of type war. Check the pom.xml for the <packaging> tag.
Finally, deployment is still another issue. If you actually need to move your .war file from the target directory to somewhere else (namely, an autodeploy folder of a servlet container), you can configure the Maven Deploy Plugin and issue mvn deploy. I'd rather suggest you to search SO for deploy war eclipse and/or deploy war maven, since there's plenty of related stuff. In the first case, you will find how to use Eclipse as a facility for deployment, while the second case leverages the command line to provide a more portable/flexible deployment procedure.

A: That's because mvn compile ends on compile phase of Maven's default lifecycle. Do mvn package and check then. And by the way, default Maven output directory is target so rather check it instead of kind of WTP temporary dirs.


text:
Q: SQL Select, selecting a row off of a column condition Division    Department  Dept. Head
1              1             Mr. Anon
2              1              NULL
3              1              NULL

1              2              NULL
2              2              NULL
3              2              NULL

I am trying to write a query that will select rows based on conditions for the 3rd column (Dept. Head).
If there is a row in the department head that is not null (Mr. Anon) select that row.  If there are no rows in the department head with a non null value, select any row.
So out of the two groups i have in the above table, i want to select only one row from each.

A:   select division, department, depthead
    from tbl
   where depthead is not null
   union all
  select min(division) any_division, department, NULL
    from tbl
group by department
  having count(depthead) = 0;

Sample Data
create table tbl (
    division int, department int, depthead varchar(100),
    primary key(department, division));
insert into tbl values (1, 1, null);
insert into tbl values (2, 1, 'Mr Head');
insert into tbl values (3, 1, null);
insert into tbl values (1, 2, null);
insert into tbl values (2, 2, null);
insert into tbl values (3, 2, null);

Result:
division    department  depthead
----------- ----------- ------------
2           1           Mr Head
1           2           NULL

A: select  *
from    (
        select  row_number() over (
                    partition by department
                    order by case when depthead is not null then 1 else 2 end
                    ) as rn
        ,       yt.*
        from    YourTable yt
        ) SubQueryAlias
where   rn = 1

Example at SQL Fiddle.


text:
Q: Haskell: Escaped character from character I'm writing a parsec parser which reads in strings and converts escaped characters, as part of exercise 3 here.
For that exercise I am using this function:
escapedCharFromChar :: Char -> Char
escapedCharFromChar c = read $ concat ["'\\",[c],"'"]

I am not to impressed with the use of read to convert the character x into the escape character with the name x. Can anyone suggest a more elegant function of type Char -> Char to do this?

A: One way is to lay out the cases exhaustively:
charFromEscape :: Char -> Char
charFromEscape 'n' = '\n'
charFromEscape 't' = '\t'
--- ... --- Help!

You could also use lookup:
-- this import goes at the top of your source file
import Data.Maybe (fromJust)

charFromEscape :: Char -> Char
charFromEscape c = fromJust $ lookup c escapes
  where escapes = [('n', '\n'), ('t', '\t')] -- and so on

The fromJust bit may look strange. The type of lookup is
lookup :: (Eq a) => a -> [(a, b)] -> Maybe b

which means for a value of some type over which equality is defined and a lookup table, it wants to give you the corresponding value from the lookup table—but your key isn't guaranteed to be present in the table! That's the purpose of Maybe, whose definition is
data Maybe a = Just a | Nothing

With fromJust, it assumes you got Just something (i.e., c has an entry in escapes), but this will fall apart when that assumption is invalid:
ghci> charFromEscape 'r'
*** Exception: Maybe.fromJust: Nothing
These examples will move you along in the exercise, but it's clear that you'd like better error handling. Also, if you expect the lookup table to be large, you may want to look at Data.Map.

A: read (or rather, Text.Read.Lex.lexCharE) is how you get at GHC's internal table, which is defined as:
 lexEscChar =
   do c <- get
      case c of
        'a'  -> return '\a'
        'b'  -> return '\b'
        'f'  -> return '\f'
        'n'  -> return '\n'
        'r'  -> return '\r'
        't'  -> return '\t'
        'v'  -> return '\v'
        '\\' -> return '\\'
        '\"' -> return '\"'
        '\'' -> return '\''
        _    -> pfail

Eventually, you have to define the semantics somewhere.  You can do it in your program, or you can reuse GHC's.

A: I just used pattern matching for the few escapes I cared about - i.e. 't' -> '\t'etc. The solution other readers suggested were similar. Not very generic, but very straight-forward.

A: You should consider implementing a proper Parser Char function instead of a Char -> Char.
(Or, if you're doing that anyway, consider using a Char -> Maybe Char instead.)

The Char -> Char approach only works if escape sequences consist of only a backslash and a single other character. Some languages have more complex character escapes that consist of a longer sequence of characters. For example, C++ supports multi-character escape sequences such as \u005C (which represents the unicode code point U+005C).
parseEscapeSequence :: Parser Char
parseEscapeSequence = do
    c <- get
    case c of
        '\' -> return '\\'
        '0' -> Just '\0'
        't' -> return '\t'
        'f' -> return '\f'
        'r' -> return '\r'
        'n' -> return '\n'
        -- ...
        'u' -> parseUnicodeEscape4
        'U' -> parseUnicodeEscape8
        -- ...
        _ -> fail "Unrecognised escape sequence"

Whereby parseUnicodeEscape4 and parseUnicodeEscape8 would each parse a fixed number of hexadecimal digits and convert them into a unicode character, likely by first converting the digits into integers in the 0..15 range, then combining those 'nibbles' into a larger integer, and then converting that integer into a unicode character.
You could alternatively offload the simple escape sequences to another function that does pattern matching, but that function should ideally have a type of Char -> Maybe Char, to allow for proper error reporting.
parseEscapeSequence :: Parser Char
parseEscapeSequence = do
    c <- get
    case c of
        -- ...
        'u' -> parseUnicodeEscape4
        'U' -> parseUnicodeEscape8
        -- ...
        _ ->
            case maybeCharFromEscape c of
                Just result -> return result
                Nothing -> fail "Unrecognised escape sequence"

maybeCharFromEscape :: Char -> Maybe Char
maybeCharFromEscape c =
    case c of
        '\' -> Just '\\'
        '0' -> Just '\0'
        't' -> Just '\t'
        'f' -> Just '\f'
        'r' -> Just '\r'
        'n' -> Just '\n'
        _ -> Nothing

For the maybeCharFromEscape function you could alternatively implement it via lookup or a Map (as other answers point out), but even then you're still going to have to explicitly write down all the possibilities and the result might be less efficient (though you may find it more readable).


text:
Q: Unable to pick the inner tag value of xml by parsing in android I am working on to parse this xml's inner tag's value but didn't succeed. I have used the DOM parser and SAX parser.
<XML>
       <VersionStatus>0</VersionStatus>
       <VersionUrl>NA</VersionUrl>
       <photo>http://demo.stellans.com/posterduck/images/Android_Images/</photo>
       <size>
         <options>4X11</options><options>8X11</options>
       </size>
       <category>
         <options>sticker</options>
         <options>card</options>
       </category>
       <Noofprints>
         <options>1</options>
         <options>2</options>
         <options>3</options>
         <options>4</options>
         <options>5</options>
         <options>6</options>
      </Noofprints>
      <selectaddress/>
    </XML>

and here is , My Main Activity
and  My Connection Class to parse xml
Guide me where i am doing wrong. Any help is appreciated.


text:
Q: Adding custom widget dynamically to a list - Flutter I have a simple custom widget trans() (short for transaction) that just takes a number and a Boolean and displays a row, and I have a list:
 List<trans> transactions=[
      trans(false, 20),
      trans(true, -50),
      trans(false, 110),
      trans(false, 35.5),

    ];

and display it using a ListView :
ListView.builder(
 itemCount: transactions.length,
  itemBuilder: (context, index){
  return(
  transactions[index]
  );
 },
),

But how can I add a new widget to the list using a button and update the screen dynamically ?

A: You may try the following code :
import 'package:flutter/material.dart';
import 'dart:math' as math;

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

extension Ex on double {
  double toPrecision(int n) => double.parse(toStringAsFixed(n));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text("Flutter Demo App"),
        ),
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatefulWidget {
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  final List<Trans> transactions = [
    const Trans(myBool: false, myDouble: 20),
    const Trans(myBool: true, myDouble: -50),
    const Trans(myBool: false, myDouble: 110),
    const Trans(myBool: false, myDouble: 35.5),
  ];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          height: MediaQuery.of(context).size.height * .7,
          child: Scrollbar(
            showTrackOnHover: true,
            child: ListView.builder(
              itemCount: transactions.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: transactions[index],
                );
              },
            ),
          ),
        ),
        RaisedButton(
          onPressed: () {
            final rnd = math.Random();
            setState(
              () {
                transactions.add(
                  Trans(
                    myBool: rnd.nextBool(),
                    myDouble:
                        rnd.nextDouble().toPrecision(2) + rnd.nextInt(100),
                  ),
                );
              },
            );
          },
          child: const Text("Add Transaction"),
        ),
      ],
    );
  }
}

class Trans extends StatelessWidget {
  final myBool;
  final myDouble;

  const Trans({Key key, this.myBool, this.myDouble}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Text("Transaction: ${myBool.toString()}  ${myDouble.toString()}")
      ],
    );
  }
}

A: Try
 List<Widget> transactions=[
      trans(false, 20),
      trans(true, -50),
      trans(false, 110),
      trans(false, 35.5),
      Button(child:Text('This is button in the list')),

    ];


text:
Q: Basis of a vectorspace If $V$ is a vectorspace with basis $\{e_1,e_2,e_3\}$, and $W = vct\{e_1,e_2\}$. Is it in general true that there exists a basis $\{v_1,v_2,v_3\}$ of $V$ with $v_i \notin W$ for $i=1,2,3$?
I thought yes, first I considered the canonical example of $\mathbb{R}^3$ with the standard basis $\{e_1,e_2,e_3\}$. Then if you take $vct\{e_1,e_2\}$, and take a basis for $\mathbb{R}^3$, $\{v_1,v_2,v_3\}$, as
$$
\{(1,1,1),(0,1,1),(0,0,1)\}
$$
none of which is in $vct\{e_1,e_2\}$.
So intuitively to me it seems plausible that it is true in general but how to prove this in general? One option I thought of: given $\mathbb{R}^3$ and any basis, we can make a basis transformation to $\{e_1,e_2,e_3\}$ and then apply the above. given any $V$ with dimension 3, it is isomoprhic to $\mathbb{R}^3$, so the same procedure works.
However, firstly, I'm not sure if this is correct?
Secondly, this is a question that appears after a chapter when isomorphisms, linear maps, and basis transformations have not yet been introduced, so there should be a way to do it without?

A: Hint: What can be said about $\{e_1+e_3, e_2+e_3, e_3\}$?

A: It is true in general.

Let $V$ be a finite-dimensional vector space and $W$ its subspace. Then there exists a basis for $V$ not intersecting $W$.

Assume $\dim V = n$ and $\dim W = k$. Let $\{w_1, \ldots, w_k\}$ be a basis for $W$ and $\{w_1, \ldots, w_k, v_{k+1}, \ldots, v_n\}$ its extension to a basis for $V$. Let's check that $$B = \{w_1 + v_{k+1}, w_2 + v_{k+1}, \ldots, w_n + v_{k+1}, v_{k+1}, v_{k+2}, \ldots, v_n\}$$ is a basis for $V$ and that $B \cap W = \emptyset$.
Since $\mathrm{card} \,B = n$, to show that $B$ is a basis it is enough to check that it is linearly independent.
Indeed, let $\alpha_1, \ldots, \alpha_k, \beta_{k+1}, \ldots, \beta_n$ be scalars such that:
$$0 = \sum_{i=1}^k \alpha_i(w_i + v_{k+1}) + \sum_{j=k+1}^n \beta_jv_j = \sum_{i=1}^k \alpha_iw_i + \left(\sum_{i=1}^k \alpha_i + \beta_{k+1}\right)v_{k+1} + \sum_{j=k+2}^n \beta_jv_j$$
This is a linear combination of vectors from the basis $\{w_1, \ldots, w_k, v_{k+1}, \ldots, v_n\}$ so we have $\alpha_i = 0$ for $i = 1, \ldots, k$, then $\sum_{i=1}^k \alpha_i + \beta_{k+1} = 0$ and finally $\beta_j = 0$ for $j = k + 2, \ldots n$. The equation $\sum_{i=1}^k \alpha_i + \beta_{k+1} = 0$ implies $\beta_{k+1} = 0$. Therefore, all scalars are $0$.
Thus, $B$ is a basis. Now assume $w_i + v_{k+1}\in W$. Then we would also have $v_{k+1} = -w_i + (w_i+v_{k+1}) \in W$, which is a contradiction because $v_{k+1} \notin W$ (otherwise $\{w_1, \ldots, w_k, v_{k+1}, \ldots, v_n\}$ would not be linearly independent.)

In your case, we can use this result to conclude that $\{e_1 + e_3, e_2 + e_3, e_3\}$ is a basis for $V$ disjoint with $W$.


text:
Q: How to edit source csv file data using pandas I have a csv file that contains large amount of data,but the data that contained in csv file is not cleaned.The example of csv data is as follows
country     branch      no_of_employee     total_salary    count_DOB   count_email
  x            a            30                 2500000        20            25
  x            b            20                 350000         15            20
  y            c            30                 4500000        30            30
  z            d            40                 5500000        40            40
  z            e            10                 1000000        10            10
  z            f            15                 1500000        15            15

after applying the group by i am not getting the proper result .
df = data_df.groupby(['country', 'customer_branch']).count()

the result is in the form of
country  branch    no of employees
x          1           30
x          1           20
y          1           30
z          3           65

country x is repeating twise.This is because of source file data,in source file the country field contains   "X"   and "X                 ". That is  why it display X twise .How can i ignore this problem using pandas

A: You can call the vectorised str.strip to trim leading and trailing whitespaces:
df['country'] = df['country'].str.strip(' ')

So the above should work to clean your data and then you can call groupby to get the desired results or set_index so you can sum on an index level which looks like what you really want
Example:
In [4]:
df = pd.DataFrame({'country':['x', 'x ','y','z','z','z'], 'branch':list('abcdef'), 'no_of_employee':[30,20,30,40,10,15]})
df

Out[4]:
  branch country  no_of_employee
0      a       x              30
1      b      x               20
2      c       y              30
3      d       z              40
4      e       z              10
5      f       z              15

In [9]:
df['country'] = df['country'].str.strip()
df.set_index(['country', 'branch']).sum(level=0)

Out[9]:
         no_of_employee
country
x                    50
y                    30
z                    65


text:
Q: Return a specific dictionary from an array of dictionaries in Swift I'm getting an array of dictionaries back from an API that changes in order, and I'm trying to work out how to identify the element that I need.
If I knew which element I needed, I'd do it like this:
let DataDictionary = DataArray[0] as NSDictionary

But the issue is that the order of the array does not stay the same, so instead of accessing by index, I need to 1) search through the array, 2) return the dictionary with the matching key value pair. Such as: "if 'id = 98765' then return this dictionary" :
    for element in DataArray as Array<Dictionary<String,String>> {

        if element["id"] == "987654" {

        println("\(element)")
        }

    }

I don't think I can typecast in this way though, and I wouldn't be at all surprised if I'm making a ton of other mistakes as well...
If anyone can provide any guidance on this, that would be amazing. If my explanation is not detailed enough, I'll be happy to provide more details - this is my first Stack Overflow post!
All the best,
oli

A: Looping works, as does the filter function, but this is what NSPredicates were made for:
let array = [
    ["id": "1", "theOne": "no"],
    ["id": "2", "theOne": "no"],
    ["id": "98765", "theOne": "yes"],
    ["id": "4", "theOne": "no"]
]

let predicate = NSPredicate(format: "(id == '98765')")!
let theOne = (array as NSArray).filteredArrayUsingPredicate(predicate).first

Edit
On second thought, filter is a little less verbose:
let theOne = array.filter { $0["id"] == "98765" }.first

A: For swift 3.0 ("filteredArrayUsingPredicate(predicate)"
) updated as below:
let array = [
["id": "1", "theOne": "no"],
["id": "2", "theOne": "no"],
["id": "98765", "theOne": "yes"],
["id": "4", "theOne": "no"]
]
let predicate = NSPredicate(format: "(id == '98765')")!
let theOne = (array as NSArray).filtered(using: predicate).first

Thanks

A: I think this can work... haven't tested.
var dictionaryId: Int?
for dictionary in DataArray {
   if let dictionary as? NSDictionary {
      dictionaryId = dictionary["id"] as? Int
      if dictionaryId != nil && dictionaryId ==98765
      {
         return dictionary;
      }
   }
}
return nil;


text:
Q: dafny how to bound set comprehension resolver? Trying to write an algorithm involving paths from a root of a binary tree to a leaf. I ran into the following error for the ghost var I was trying to define. I had intended to try to show that some other path was in this set. How do I resolve this error?

the result of a set comprehension must be finite, but Dafny's
heuristics can't figure out how to produce a bounded set of values for
'px'Resolver

datatype TreeNode = Nil | Cons(val: nat, left: TreeNode, right: TreeNode)

predicate isPath(paths: seq<TreeNode>, root: TreeNode)
    requires root != Nil && root == paths[0] ==> root !in paths[1..]
{
    if |paths| == 0 then false else match paths[0] {
        case Nil => false
        case Cons(val, left, right) => if |paths| == 1 then root == paths[0] else root == paths[0] && (isPath(paths[1..], left) || isPath(paths[1..], right))
    }
}

method Test(root: TreeNode) {
   ghost var ps := set px: seq<TreeNode> | isPath(px, root) ;
}

I thought that perhaps Dafny implied that there could be a loop in the tree which would result in infinite paths, so I wrote the following to try to assert it was not possible. However, it still did not resolve the issue. I believe there should be a finite albeit large number of paths.
function TreeSet(root: TreeNode): set<TreeNode> {
    match root {
        case Nil => {}
        case Cons(val, left, right) => TreeSet(left)+{root}+TreeSet(right)
    }
}

function ChildSet(root: TreeNode): set<TreeNode> {
    match root {
        case Nil => {}
        case Cons(val, left, right) => {left}+ChildSet(left)+{right}+ChildSet(right)
    }
}

method Test(root: TreeNode)
    requires forall node :: node in TreeSet(root) ==> node !in ChildSet(node)
{
   ghost var ps := set px: seq<TreeNode> | isPath(px, root) ;
}

A: Dafny enforces finiteness of set using syntactic scan and fixed set of heuristics, as a result it is not exhaustive. Following example give same error
predicate test(i: int)
{
   i >= 10 && i <= 20
}

method Test(){
  ghost var s := set i | test(i);
}

Also no language construct exists to convince dafny that set constructed using set comprehension is finite set.
[1] https://github.com/dafny-lang/dafny/issues/13#issuecomment-286909795
[2] https://github.com/dafny-lang/dafny/issues/1366#issuecomment-906785889

A: This is not the end of the story.
You can definitely use iset that don't have the constraint to check that they are finite.
The following code snippet works, modulo the fact that there are still unsatisfied preconditions in the recursive calls to isPath:
datatype TreeNode = Nil | Cons(val: nat, left: TreeNode, right: TreeNode)

predicate isPath(paths: seq<TreeNode>, root: TreeNode)
    requires root != Nil && root == paths[0] ==> root !in paths[1..]
{
    if |paths| == 0 then false else match paths[0] {
        case Nil => false
        case Cons(val, left, right) => if |paths| == 1 then root == paths[0] else root == paths[0] && (isPath(paths[1..], left) || isPath(paths[1..], right))
    }
}

method Test(root: TreeNode) {
   ghost var ps := iset px: seq<TreeNode> | |px| > 0 && root != Nil && root == px[0] ==> root !in px[1..] && isPath(px, root) ;
}


text:
Q: GDB Compatibility Issue on OSX Mojave I was using gdb before Mojave update but now it is throwing errors:
(gdb) file a.out
BFD: /Users/aliomerkeser/Desktop/a.out: unknown load command 0x32
BFD: /Users/aliomerkeser/Desktop/a.out: unknown load command 0x32
"/Users/aliomerkeser/Desktop/a.out": not in executable format: File format not recognized
Is that a compatibility issue or a configuration issue of mine?
I tried downgrading gdb and re-codesigning gdb.

A: Known bug with gdb on Mojave. Still not resolved. In the thread below there is a solution proposed which involves rebuilding gdb with some changes.
gdb 8.2 can't recognized executable file on macOS Mojave 10.14
Update:
8.2 has officially incorporated these changes, so doesnt have to be done manually.

A: Valgrind still doesn't work on OSX Mojave but I am using heapusage an it is a pretty good alternative to valgrind
heapusage


text:
Q: How to do remote debugging with Browser-sync? I have installed browser sync with npm. On their website, they have mentioned that it also allows remote debugging. But they have not mentioned that how to do remote debugging.
I have used below command to run mysite on browser-sync.
browser-sync start --proxy localhost:8080/mysite
how can I remote debug that?

A: Though this was quite a tricky process in versions before Browser-sync 2.0, but with Browser-sync 2.0 you now have a brand new Web UI, which makes this process a whole lot easier.
Firstly you need to update Browser-sync to it's latest version

npm install -g browser-sync@latest

Then run any command like you would.
eg:

browser-sync start --proxy "myproject.dev" --files "css/*.css"

To open this Web UI open

http://localhost:3001

Below are links to articles that talk about Remote Debuggging in Browser-Sync:

*

*http://www.wearejh.com/news/browsersync-2-0/

*http://www.sitepoint.com/improve-workflow-browsersync-2-0/


text:
Q: If this possible to convert geoJson to KML file and export it in react native? Hi everyone I need to convert geoJson data to KML file and export it in React native, Is this possible, and how do I do it, This possible to implement only front-end (or have any open API to solve this feature?)

A: to convert a geoJson file to kml i used the tokml library
to download it works using the react-native-fs library

A: Use tokml library & Follow given steps

*

*install tokml package by using this command npm install tokml

*

import tokml from 'tokml';

const geoJsonData = {
  "type": "FeatureCollection",
  "features": [{
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [102.0, 0.5]
    },
    "properties": {
      "name": "Dinagat Islands"
    }
  }]
};

const kmlData = tokml(geoJsonData);
console.log(kmlData);


text:
Q: Search between Specific Times I have a date field and 2 time fields(Start Time and End Time). I have to get Data from the date and entered in that date field and between Start and end times.
I am using Linq query.
result = result.Where(x => x.CreatedDate.ToLocalTime() > search.StartTime &&
x.CreatedDate.ToLocalTime() < search.EndTime);

I am using this but I am getting the following error.
LINQ to Entities does not recognize the method 'System.DateTime ToLocalTime()' method, and this method cannot be translated into a store expression
Please Help.

A: As Panagiotis Kanavos pointed out there may be no equivalent argument.  When you do have the correct type though you are essentially doing a conversion of one DateTime to another.  Both the predicate values and the set should have their values preferably stored in the same TimeZone.  Here is a simple console example to show what I mean.
    public class TestData
    {
        public DateTime Dt { get; set; }
        public TestData(DateTime dt)
        {
            Dt = dt;
        }

        public override string ToString() => Dt.ToString();
    }

    static void Main(string[] args)
    {
        var dt = new DateTime(2018, 1, 11);
        var s = dt;
        var e = dt.AddHours(3);
        var dts = new List<TestData>();
        for (int i = 0; i < 10; i++)
        {
            dts.Add(new TestData(dt.AddHours(i)));
        }

        Console.WriteLine("Dates as are");
        dts.ForEach(Console.WriteLine);
        Console.WriteLine(Environment.NewLine);

        Console.WriteLine("Dates to local time are");
        dts.ForEach(x => Console.WriteLine(x.Dt.ToLocalTime()));
        Console.WriteLine(Environment.NewLine);

        Console.WriteLine("searches are");
        Console.WriteLine(s);
        Console.WriteLine(e);
        Console.WriteLine(Environment.NewLine);

        Console.WriteLine("searches to local time are");
        Console.WriteLine(s.ToLocalTime());
        Console.WriteLine(e.ToLocalTime());
        Console.WriteLine(Environment.NewLine);

        Console.WriteLine("Weird results as one set is cast to local and other is not.  Plus the cast is now performed on presentation");
        dts.Where(x => x.Dt.ToLocalTime() >= s && x.Dt.ToLocalTime() <= e).ToList().ForEach(Console.WriteLine);
        Console.WriteLine(Environment.NewLine);

        Console.WriteLine("expected results as both are uniform");
        dts.Where(x => x.Dt >= s && x.Dt <= e).ToList().ForEach(Console.WriteLine);

        Console.ReadLine();
    }

Since different posters on SO are in different timezone the second result set will vary.  But essentially I am in PST in the US so I see times for the second set eight hours prior to my first.  You generally in .NET perform operations of storage to be UTC if your application is going to be worldwide or even country wide.  Then you just deal with DateTimes and would only do a conversion on the client end for presentation to a potential end user.  But most of the time not in the logic for predicates.

A: You can't use ToLocalTime() for Linq to Entities. Because it can't be translated to SQL. There is no equivalent to apply it.
So, why don't you convert your startTime and endTime by considering required time zone which is stored in the database. Opposite conversion should be like that;
//I use utc time to provide example.
//Convert your dates with required timezones which is stored in the database
var startTime = search.StartTime.ToUtcDateTime();
var endTime = search.EndTime.ToUtcDateTime();
result = result.Where(x => x.CreatedDate > startTime &&
                            x.CreatedDate < endTime);


text:
Q: Is there any difference between "right" or "correct" for confirmation? The question revolves around 'right?' at the end added when the speaker is not sure about her/his understanding.
I think it is common to use "..., right?" where "..." is the speaker's understanding (of the topic under discussion) while it is possible to use correct in the same way.
Do right and correct make the sentence(s) sound different in formality or implied attitudes of the speaker?
A related question is about right/correct for answering. Does it make any difference just to say "(That is) Correct." or "(That is/That's) Right." as a response to a "..., right?" statement?

Related questions:

*

*Is "right English" correct?

*Can I say "It's right answer" instead of "It's correct answer"?

A: Both ..., right? and ..., correct? are laconic. The first is informal and, to my ageing UK ears, American, though it's widely used here now. The second is less colloquial and is somewhat brusque: like an army officer questioning his men. If instead you were to ask, in a new sentence, "Is that right/correct?" it would be colloquial, less brusque and - with "correct" - more formal.
Alternatively, and with unimpeachable grammar,  we might seek confirmation by asking, "aren't you?" or "didn't it?" or "haven't they?" or whatever is appropriate. For example:

You're Jones, aren't you?It rained, didn't it?They've lost
the game, haven't they?

On your related question, the standard informal responses to the informal ..., right? are "Yeah", "Yes", "Right" and (a little more formally) "That's right". Saying "(That is) correct" might be perceived as snooty: your formality drawing attention to his/her informality.


text:
Q: Angular 4: How to create reusable module of base classes I have some abstract/base classes, which are inherited by other modules in other applications. These are not services, nor components - just contain some common features that are used by different components - and these components would be used in several different projects.
For example i have a base input class, that is inherited by alphanumeric input class, which is then inherited by an alphabetic and alphanumeric input component having their own separate modules and npm packages ready to be used in future projects.
My plan was to create a base module: a collection of base classes which the component modules could import and extend, but i cannot declare or provide a normal class without @Component/@Pipe/@Directive or @Injectable decorators.
It seems the code would compile if i decorated each base class with @Injectable - but these are not services just code to be inherited later so i dont know if this is the proper/an acceptable approach.
What is the best way to define a such base module with a generic collection of classes to be used in several other independent components?
Ideally each such component should have its own module and npm package, with a dependency on the base class collection package.

A: From my experience using extend keyword in Angular is a very bad idea because it goes against the concept that the framework tries to represent and can be considered an anti-pattern. You're basically trying to avoid using Dependency Injection which is a critical part of this framework.
What you really want to do is create your own module consisting of Pipes, Components and Injectables (also referred as Services).
If you want to add functionality to one of the components/services/pipes etc. you should create a service which is going to be injected making testing and maintenance way easier.
e.g. Whenever I'm using momentjs I start with creating a service which wraps library's functionality.


text:
Q: How to refactor a Python "god class"? Problem
I'm working on a Python project whose main class is a bit "God Object".  There are so friggin' many attributes and methods!
I want to refactor the class.
So Far…
For the first step, I want to do something relatively simple; but when I tried the most straightforward approach, it broke some tests and existing examples.
Basically, the class has a loooong list of attributes—but I can clearly look over them and think, "These 5 attributes are related…These 8 are also related…and then there's the rest."
getattr
I basically just wanted to group the related attributes into a dict-like helper class.  I had a feeling __getattr__ would be ideal for the job.  So I moved the attributes to a separate class, and, sure enough, __getattr__ worked its magic perfectly well…
At first.
But then I tried running one of the examples.  The example subclass tries to set one of these attributes directly (at the class level).  But since the attribute was no longer "physically located" in the parent class, I got an error saying that the attribute did not exist.
@property
I then read up about the @property decorator.  But then I also read that it creates problems for subclasses that want to do self.x = blah when x is a property of the parent class.
Desired

*

*Have all client code continue to work using self.whatever, even if the parent's whatever property is not "physically located" in the class (or instance) itself.

*Group related attributes into dict-like containers.

*Reduce the extreme noisiness of the code in the main class.

For example, I don't simply want to change this:
larry = 2
curly = 'abcd'
moe   = self.doh()

Into this:
larry = something_else('larry')
curly = something_else('curly')
moe   = yet_another_thing.moe()

…because that's still noisy.  Although that successfully makes a simply attribute into something that can manage the data, the original had 3 variables and the tweaked version still has 3 variables.
However, I would be fine with something like this:
stooges = Stooges()

And if a lookup for self.larry fails, something would check stooges and see if larry is there.  (But it must also work if a subclass tries to do larry = 'blah' at the class level.)
Summary

*

*Want to replace related groups of attributes in a parent class with a single attribute that stores all the data elsewhere

*Want to work with existing client code that uses (e.g.) larry = 'blah' at the class level

*Want to continue to allow subclasses to extend, override, and modify these refactored attributes without knowing anything has changed

Is this possible?  Or am I barking up the wrong tree?

A: Having written and then refactored a python "God object", I sympathize. What I did is break the original object down into sub sections based upon methods. For instance, the original looked like this pseudo code:
method A():
    self.bla += 1

method B():
    self.bla += 1

do stuff():
    self.bla = 1
    method A()
    method B()
    print self.bla

The stuff method is a self contained "unit" of work. I migrated it out to a new class which the original instantiates. This pulled out the necessary properties as well. Some were used only by the sub class and could move straight across. Others were shared, and got moved into a shared class.
The "God object" creates a new copy of the shared class at start up, and each of the new sub classes accepts a pointer as part of their init method. For example, here's a stripped version of the mailer:
#!/usr/bin/env python
# -*- coding: ascii -*-
'''Functions for emailing with dirMon.'''

from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os
import smtplib
import datetime
import logging

class mailer:
    def __init__(self,SERVER="mail.server.com",FROM="support@server.com"):
        self.server = SERVER
        self.send_from = FROM
        self.logger = logging.getLogger('dirMon.mailer')

    def send_mail(self, send_to, subject, text, files=[]):
        assert type(send_to)==list
        assert type(files)==list
        if self.logger.isEnabledFor(logging.DEBUG):
            self.logger.debug(' '.join(("Sending email to:",' '.join(send_to))))
            self.logger.debug(' '.join(("Subject:",subject)))
            self.logger.debug(' '.join(("Text:",text)))
            self.logger.debug(' '.join(("Files:",' '.join(files))))
        msg = MIMEMultipart()
        msg['From'] = self.send_from
        msg['To'] = COMMASPACE.join(send_to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
        msg.attach( MIMEText(text) )
        for f in files:
            part = MIMEBase('application', "octet-stream")
            part.set_payload( open(f,"rb").read() )
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
            msg.attach(part)
        smtp = smtplib.SMTP(self.server)
        mydict = smtp.sendmail(self.send_from, send_to, msg.as_string())
        if self.logger.isEnabledFor(logging.DEBUG):
            self.logger.debug("Email Successfully Sent!")
        smtp.close()
        return mydict

It is created once and shared between the different classes that need mailing capabilities.
So for you, create a class larry with the properties and methods you need. Everywhere the client says larry = blah replace it with larryObj.larry = blah. This migrates things to sub projects without breaking the current interface.
The only other thing to do is look for "units of work". If you were going to turn part of the "God Object" into it's own method, do so. But, put the method outside it. This forces you to create an interface between the components.
Laying that groundwork allows everything else to follow it. For example, a piece of the helper object demonstrating how it interfaces with the mailer:
#!/usr/bin/env python
'''This module holds a class to spawn various subprocesses'''
import logging, os, subprocess, time, dateAdditionLib, datetime, re

class spawner:
    def __init__(self, mailer):
        self.logger = logging.getLogger('dirMon.spawner')
        self.myMailer = mailer

Concentrate on the smallest individual unit of work possible, and move it out. This is easier to do, and lets you play with the setup quickly. Don't look at properties for moving stuff, they are ancillary to the tasks being done with them in most cases. Whatever is left over after you have dealt with the methods should probably stay in the original object, since it is part of the shared state.
But, the new objects should now accept the properties they need as init variables, not touching the caller objects property. They then return any necessary values, which the caller can use to update the shared properties as necessary. This helps to decouple the objects and makes for a more robust system.