问:
Cannot change number of clusters in KMeansClustering Tensorflow
I found this code and it works perfectly. THe idea - split my data and train KMeansClustering on it. So I create InitHook and iterator and use it for training.

```<code>class _IteratorInitHook(tf.train.SessionRunHook):
    """Hook to initialize data iterator after session is created."""

    def __init__(self):
        super(_IteratorInitHook, self).__init__()
        self.iterator_initializer_fn = None

    def after_create_session(self, session, coord):
        """Initialize the iterator after the session has been created."""
        del coord
        self.iterator_initializer_fn(session)

# Run K-means clustering.
def _get_input_fn():
    """Helper function to create input function and hook for training.
    Returns:
        input_fn: Input function for k-means Estimator training.
        init_hook: Hook used to load data during training.
    """
    init_hook = _IteratorInitHook()

    def _input_fn():
        """Produces tf.data.Dataset object for k-means training.
        Returns:
            Tensor with the data for training.
        """
        features_placeholder = tf.placeholder(tf.float32,
                                                my_data.shape)
        delf_dataset = tf.data.Dataset.from_tensor_slices((features_placeholder))
        delf_dataset = delf_dataset.shuffle(1000).batch(
            my_data.shape[0])
        iterator = delf_dataset.make_initializable_iterator()

        def _initializer_fn(sess):
            """Initialize dataset iterator, feed in the data."""
            sess.run(
                iterator.initializer,
                feed_dict={features_placeholder: my_data})

        init_hook.iterator_initializer_fn = _initializer_fn
        return iterator.get_next()

    return _input_fn, init_hook

input_fn, init_hook = _get_input_fn()

output_cluster_dir = 'parameters/clusters'

kmeans = tf.contrib.factorization.KMeansClustering(
    num_clusters=1024,
    model_dir=output_cluster_dir,
    use_mini_batch=False,
)

print('Starting K-means clustering...')
kmeans.train(input_fn, hooks=[init_hook])
</code>```

But if I change num_clusters to 512 or 256 I get next error:

InvalidArgumentError: segment_ids[0] = 600 is out of range [0, 256)

  [[node UnsortedSegmentSum (defined at
  /home/mikhail/.conda/envs/tf2/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/estimator.py:1112)
  ]]     [[node Squeeze (defined at
  /home/mikhail/.conda/envs/tf2/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/estimator.py:1112)
  ]]

Look like I have some problems on splitting data to batches OR my KMeans use 1024 clusters on default even I set another value!

I can't figure out what to change to make it work correctly.
Traceback is huge, if its needed I can attach as a file.

答:
I found the problem:
as you can see I save codebook to parameters/clusters. When it have created tensorflow save graph here too.
So default behaviour for tensorflow - DO NOT CREATE new graph if it already exist!

So every time I tried to run KMeansClustering it still use graph, loaded from codebook.
I solved the issue by deleting folder clusters every time I run KMeansClustering.

I still have some issues: I create new clusters, and start 2 scripts in parallel to create features using it: one of them creates for old codebook and one for new! Still forcing it, but my recommendation here is to restart everything after you created new codebook (maybe some info still loaded in tensorflow).

Body:
I found this code and it works perfectly. THe idea - split my data and train KMeansClustering on it. So I create InitHook and iterator and use it for training.

class _IteratorInitHook(tf.train.SessionRunHook):
    """Hook to initialize data iterator after session is created."""

    def __init__(self):
        super(_IteratorInitHook, self).__init__()
        self.iterator_initializer_fn = None

    def after_create_session(self, session, coord):
        """Initialize the iterator after the session has been created."""
        del coord
        self.iterator_initializer_fn(session)

# Run K-means clustering.
def _get_input_fn():
    """Helper function to create input function and hook for training.
    Returns:
        input_fn: Input function for k-means Estimator training.
        init_hook: Hook used to load data during training.
    """
    init_hook = _IteratorInitHook()

    def _input_fn():
        """Produces tf.data.Dataset object for k-means training.
        Returns:
            Tensor with the data for training.
        """
        features_placeholder = tf.placeholder(tf.float32,
                                                my_data.shape)
        delf_dataset = tf.data.Dataset.from_tensor_slices((features_placeholder))
        delf_dataset = delf_dataset.shuffle(1000).batch(
            my_data.shape[0])
        iterator = delf_dataset.make_initializable_iterator()

        def _initializer_fn(sess):
            """Initialize dataset iterator, feed in the data."""
            sess.run(
                iterator.initializer,
                feed_dict={features_placeholder: my_data})

        init_hook.iterator_initializer_fn = _initializer_fn
        return iterator.get_next()

    return _input_fn, init_hook

input_fn, init_hook = _get_input_fn()

output_cluster_dir = 'parameters/clusters'

kmeans = tf.contrib.factorization.KMeansClustering(
    num_clusters=1024,
    model_dir=output_cluster_dir,
    use_mini_batch=False,
)

print('Starting K-means clustering...')
kmeans.train(input_fn, hooks=[init_hook])

But if I change num_clusters to 512 or 256 I get next error:

InvalidArgumentError: segment_ids[0] = 600 is out of range [0, 256)

  [[node UnsortedSegmentSum (defined at
  /home/mikhail/.conda/envs/tf2/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/estimator.py:1112)
  ]]     [[node Squeeze (defined at
  /home/mikhail/.conda/envs/tf2/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/estimator.py:1112)
  ]]

Look like I have some problems on splitting data to batches OR my KMeans use 1024 clusters on default even I set another value!

I can't figure out what to change to make it work correctly.
Traceback is huge, if its needed I can attach as a file.


来源: stackexchange

问:
Vue - Array dosen't update
On click, I want to push to array. It works if I manually refresh the Vue extension in the console of Google Chrome but otherwise not</p>

```<code>            completeStep(index, key) {
                let currentSet = index + key

               if (this.exercise_completed[index].indexOf(currentSet) === -1) {
                    this.exercise_completed[index].push(currentSet)
                } else {
                    this.exercise_completed[index].splice(this.exercise_completed[index].indexOf(currentSet), 1)
                }
            }
</code>```

答:
maybe try to use this.$forceUpdate(); when you make the change.

https://v2.vuejs.org/v2/api/#vm-forceUpdate

Hope this helps

ContentLicense: CC BY-SA 4.0

Title: Vue - Array dosen't update

Body:
On click, I want to push to array. It works if I manually refresh the Vue extension in the console of Google Chrome but otherwise not

            completeStep(index, key) {
                let currentSet = index + key

               if (this.exercise_completed[index].indexOf(currentSet) === -1) {
                    this.exercise_completed[index].push(currentSet)
                } else {
                    this.exercise_completed[index].splice(this.exercise_completed[index].indexOf(currentSet), 1)
                }
            }


问:
How do you pass an image to a styled component?
I'm using styled-components in ReactJS and I'm trying to create a component that can take in the background-image as a prop. After some research, I've tried this:

```<code>import SpeechBubble1 from '../images/home_images/Speech 1.png';
...

const SpeechBubble = styled.div`
    background-image: url(${props => props.background});
`;

...

<SpeechBubble background={SpeechBubble1} />
</code>```

But it doesn't work. Checking in the browser element window, I can see I'm getting an Invalid property value for background-image.

What am I doing wrong?

Edit:
I also tried doing this, which hasn't worked:

```<code><SpeechBubble style={{background: `url(${SpeechBubble1})`}} />
</code>```

答:
Make sure you are including a height for the styled component, otherwise, it won't display anything (unless it has children that define its dimensions).

Working example:

components/Container

```<code>import styled from "styled-components";

const Container = styled.div`
  height: 100vh;
  background-image: url(${({ background }) => background});
  background-repeat: no-repeat;
  background-size: cover;
`;

export default Container;
</code>```

index.js

```<code>import React, { Fragment } from "react";
import { render } from "react-dom";
import reactbg from "./images/reactbg.png";
import Container from "./components/Container";
import GlobalStyles from "./components/GlobalStyles";
import Title from "./components/Title";

const App = () => (
  <Fragment>
    <GlobalStyles />
    <Container background={reactbg}>
      <Title>Hello World</Title>
    </Container>
  </Fragment>
);

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

Body:
I'm using styled-components in ReactJS and I'm trying to create a component that can take in the background-image as a prop. After some research, I've tried this:

import SpeechBubble1 from '../images/home_images/Speech 1.png';
...

const SpeechBubble = styled.div`
    background-image: url(${props => props.background});
`;

...

<SpeechBubble background={SpeechBubble1} />

But it doesn't work. Checking in the browser element window, I can see I'm getting an Invalid property value for background-image.

What am I doing wrong?

Edit:
I also tried doing this, which hasn't worked:

<SpeechBubble style={{background: `url(${SpeechBubble1})`}} />

Body:
Make sure you are including a height for the styled component, otherwise, it won't display anything (unless it has children that define its dimensions).

Working example:

components/Container

import styled from "styled-components";

const Container = styled.div`
  height: 100vh;
  background-image: url(${({ background }) => background});
  background-repeat: no-repeat;
  background-size: cover;
`;

export default Container;

index.js

import React, { Fragment } from "react";
import { render } from "react-dom";
import reactbg from "./images/reactbg.png";
import Container from "./components/Container";
import GlobalStyles from "./components/GlobalStyles";
import Title from "./components/Title";

const App = () => (
  <Fragment>
    <GlobalStyles />
    <Container background={reactbg}>
      <Title>Hello World</Title>
    </Container>
  </Fragment>
);

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


问:
EF Linq- Dynamic Lambda expression trees
I have a generic repository that uses generic expressions for returning data from Entity Framework Core.

```<code>public async Task<T2> GetFieldsAsync<T2>(Expression<Func<T, T2>> expression)
  {
            return await context.Set<T>()
                                .Select(expression)
                                .FirstOrDefaultAsync();
  }
</code>```

Now if I want to select specific fields, at compile time I can write the following statement:

```<code>var test = await _repositoryBase.GetFieldsAsync(x => new { x.Id, x.Name });
</code>```

I want to be able to do above at run time instead. I can create an expression at run time that returns a single parameter as follows:

```<code>var expression = Expression.Parameter(typeof(Ingredient), "ingr");
var param1 = Expression.Property(expression, "Id");
var lambda = Expression.Lambda<Func<Ingredient, Guid>>(param1, expression);
var test = await _repositoryBase.GetFieldsAsync(lambda);
</code>```

The above lambda only returns a single property from the Ingredient class. Is it possible to create a run time lambda that returns an anonymous object using expression trees? I.e.

```<code>x => new { x.Id, x.Name }
</code>```

Note that users might request different fields (e.g. Name, Description, DateCreated, etc.) so need to dynamically create the lambda expression.

I know I can use https://github.com/StefH/System.Linq.Dynamic.Core to pass in strings to select statements via its built-in IQueryable extension methods. I am wondering if there is a way to dynamically select specific fields at run time via a list of fields passed in by the user.

Currently, my approach is to get all properties of the class from the database, and use an ExpandoObject to only select the fields that user requests. The issue here is that although it works, I am returning more data from the database than is required. I'd like to avoid this by only selecting the required data.

```<code>//user did not provide any fields so include all fields
    if (string.IsNullOrEmpty(field))
     {
         myPropertyInfoList.AddRange(typeProperties);
     }
    else
      {
        foreach (var item in fields)
        {
            myPropertyInfoList.Add(type.GetProperty(item, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance));
        }

    var expandoObj = (IDictionary<string, object>)new ExpandoObject();

        foreach (var item in myPropertyInfoList)
        {
            expandoObj.Add(item.Name, item.GetValue(ingrView));
        }
</code>```

答:
This is a simplified anonymous type creator. It uses public fields instead of building properties, it has no methods implemented (it gets a default constructor).

First, a simple extension method I use later:

```<code>public static class StringExt {
    public static string Join(this IEnumerable<string> strings, string sep) => String.Join(sep, strings);
}
</code>```

Here, the code to create a new anonymous type from a Dictionary<string,Type> that describes the anonymous type. A generic type with type parameters for the type of every field (property) is generated and then fixed to the actual types being used - which is how the C# compiler generates anonymous types. This code creates (once) a dynamic Assembly and Module, then adds new types as needed. It uses a cache to (attempt) to prevent creating the same type more than once.

```<code>public static class AnonymousExt {
    private static readonly CustomAttributeBuilder CompilerGeneratedAttributeBuilder = new CustomAttributeBuilder(typeof(CompilerGeneratedAttribute).GetConstructor(Type.EmptyTypes), new object[0]);
    private static ModuleBuilder AnonTypeMB;
    private static int AssemCount = 25;

    // create a pseudo anonymous type (POCO) from an IDictionary of property names and values
    // using public fields instead of properties
    // no methods are defined on the type
    public static Type MakeAnonymousType(IDictionary<string, Type> objDict) {
        // find or create AssemblyBuilder for dynamic assembly
        if (AnonTypeMB == null) {
            var assemblyName = new AssemblyName($"MyDynamicAssembly{AssemCount}");
            var ab = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            AnonTypeMB = ab.DefineDynamicModule("MyDynamicModule");
        }
        // get a dynamic TypeBuilder
        var typeBuilder = AnonTypeMB.DefineType($"<>f__AnonymousType{AssemCount++}`{objDict.Keys.Count}", TypeAttributes.AnsiClass | TypeAttributes.Class | TypeAttributes.AutoLayout | TypeAttributes.NotPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit);
        typeBuilder.SetCustomAttribute(CompilerGeneratedAttributeBuilder);

        // create generic parameters for every field
        string gtpName(string fieldName) => $"<{fieldName}>j__TPar";
        var gtpnames = objDict.Keys.Select(k => gtpName(k)).ToArray();
        var gtpbs = typeBuilder.DefineGenericParameters(gtpnames);
        var gtpN2Bs = gtpnames.Zip(gtpbs, (n, pb) => new { n, pb }).ToDictionary(g => g.n, g => g.pb);

        // add public fields to match the source object
        var fbs = new List<FieldBuilder>();
        foreach (var srcFieldName in objDict.Keys)
            fbs.Add(typeBuilder.DefineField(srcFieldName, gtpN2Bs[gtpName(srcFieldName)], FieldAttributes.Public));

        // Fix the generic class
        var fieldTypes = objDict.Values.ToArray();
        return typeBuilder.CreateType().MakeGenericType(fieldTypes);
    }

    static string MakeAnonymousTypeKey(IDictionary<string, Type> objDict) => objDict.Select(d => $"{d.Key}~{d.Value}").Join("|");

    public static Dictionary<string, Type> PrevAnonTypes = new Dictionary<string, Type>();
    public static Type FindOrMakeAnonymousType(IDictionary<string, Type> objDict) {
        var wantedKey = MakeAnonymousTypeKey(objDict);
        if (!PrevAnonTypes.TryGetValue(wantedKey, out var newType)) {
            newType = MakeAnonymousType(objDict);
            PrevAnonTypes[wantedKey] = newType;
        }

        return newType;
    }
}
</code>```

And here is some sample code using it with a SQL Table named Accounts which has a class type named Accounts. Because my anonymous type doesn't have a constructor that takes the field values, I use a MemberInitExpression instead of the normal NewExpression (which seems unnecessarily complicated anyway?).

```<code>var objDescr = new Dictionary<string, Type> { { "Actid", typeof(Int32) }, { "Application", typeof(string) }, { "Username", typeof(string) }};
var aType = AnonymousExt.FindOrMakeAnonymousType(objDescr);

var parma = Expression.Parameter(typeof(Accounts), "a");
var fxbe = aType.GetFields().Select(fi => Expression.Bind(fi, Expression.Field(parma, fi.Name))).ToArray();
var mie = Expression.MemberInit(Expression.New(aType), fxbe);
var myf = Expression.Lambda<Func<Accounts, object>>(mie, parma);

var ans = Accounts.Select(myf).Take(2);
</code>```

Body:
I have a generic repository that uses generic expressions for returning data from Entity Framework Core.

public async Task<T2> GetFieldsAsync<T2>(Expression<Func<T, T2>> expression)
  {
            return await context.Set<T>()
                                .Select(expression)
                                .FirstOrDefaultAsync();
  }

Now if I want to select specific fields, at compile time I can write the following statement:

var test = await _repositoryBase.GetFieldsAsync(x => new { x.Id, x.Name });

I want to be able to do above at run time instead. I can create an expression at run time that returns a single parameter as follows:

var expression = Expression.Parameter(typeof(Ingredient), "ingr");
var param1 = Expression.Property(expression, "Id");
var lambda = Expression.Lambda<Func<Ingredient, Guid>>(param1, expression);
var test = await _repositoryBase.GetFieldsAsync(lambda);

The above lambda only returns a single property from the Ingredient class. Is it possible to create a run time lambda that returns an anonymous object using expression trees? I.e.

x => new { x.Id, x.Name }

Note that users might request different fields (e.g. Name, Description, DateCreated, etc.) so need to dynamically create the lambda expression.

I know I can use https://github.com/StefH/System.Linq.Dynamic.Core to pass in strings to select statements via its built-in IQueryable extension methods. I am wondering if there is a way to dynamically select specific fields at run time via a list of fields passed in by the user.

Currently, my approach is to get all properties of the class from the database, and use an ExpandoObject to only select the fields that user requests. The issue here is that although it works, I am returning more data from the database than is required. I'd like to avoid this by only selecting the required data.

//user did not provide any fields so include all fields
    if (string.IsNullOrEmpty(field))
     {
         myPropertyInfoList.AddRange(typeProperties);
     }
    else
      {
        foreach (var item in fields)
        {
            myPropertyInfoList.Add(type.GetProperty(item, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance));
        }

    var expandoObj = (IDictionary<string, object>)new ExpandoObject();

        foreach (var item in myPropertyInfoList)
        {
            expandoObj.Add(item.Name, item.GetValue(ingrView));
        }

Body:
This is a simplified anonymous type creator. It uses public fields instead of building properties, it has no methods implemented (it gets a default constructor).

First, a simple extension method I use later:

public static class StringExt {
    public static string Join(this IEnumerable<string> strings, string sep) => String.Join(sep, strings);
}

Here, the code to create a new anonymous type from a Dictionary<string,Type> that describes the anonymous type. A generic type with type parameters for the type of every field (property) is generated and then fixed to the actual types being used - which is how the C# compiler generates anonymous types. This code creates (once) a dynamic Assembly and Module, then adds new types as needed. It uses a cache to (attempt) to prevent creating the same type more than once.

public static class AnonymousExt {
    private static readonly CustomAttributeBuilder CompilerGeneratedAttributeBuilder = new CustomAttributeBuilder(typeof(CompilerGeneratedAttribute).GetConstructor(Type.EmptyTypes), new object[0]);
    private static ModuleBuilder AnonTypeMB;
    private static int AssemCount = 25;

    // create a pseudo anonymous type (POCO) from an IDictionary of property names and values
    // using public fields instead of properties
    // no methods are defined on the type
    public static Type MakeAnonymousType(IDictionary<string, Type> objDict) {
        // find or create AssemblyBuilder for dynamic assembly
        if (AnonTypeMB == null) {
            var assemblyName = new AssemblyName($"MyDynamicAssembly{AssemCount}");
            var ab = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            AnonTypeMB = ab.DefineDynamicModule("MyDynamicModule");
        }
        // get a dynamic TypeBuilder
        var typeBuilder = AnonTypeMB.DefineType($"<>f__AnonymousType{AssemCount++}`{objDict.Keys.Count}", TypeAttributes.AnsiClass | TypeAttributes.Class | TypeAttributes.AutoLayout | TypeAttributes.NotPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit);
        typeBuilder.SetCustomAttribute(CompilerGeneratedAttributeBuilder);

        // create generic parameters for every field
        string gtpName(string fieldName) => $"<{fieldName}>j__TPar";
        var gtpnames = objDict.Keys.Select(k => gtpName(k)).ToArray();
        var gtpbs = typeBuilder.DefineGenericParameters(gtpnames);
        var gtpN2Bs = gtpnames.Zip(gtpbs, (n, pb) => new { n, pb }).ToDictionary(g => g.n, g => g.pb);

        // add public fields to match the source object
        var fbs = new List<FieldBuilder>();
        foreach (var srcFieldName in objDict.Keys)
            fbs.Add(typeBuilder.DefineField(srcFieldName, gtpN2Bs[gtpName(srcFieldName)], FieldAttributes.Public));

        // Fix the generic class
        var fieldTypes = objDict.Values.ToArray();
        return typeBuilder.CreateType().MakeGenericType(fieldTypes);
    }

    static string MakeAnonymousTypeKey(IDictionary<string, Type> objDict) => objDict.Select(d => $"{d.Key}~{d.Value}").Join("|");

    public static Dictionary<string, Type> PrevAnonTypes = new Dictionary<string, Type>();
    public static Type FindOrMakeAnonymousType(IDictionary<string, Type> objDict) {
        var wantedKey = MakeAnonymousTypeKey(objDict);
        if (!PrevAnonTypes.TryGetValue(wantedKey, out var newType)) {
            newType = MakeAnonymousType(objDict);
            PrevAnonTypes[wantedKey] = newType;
        }

        return newType;
    }
}

And here is some sample code using it with a SQL Table named Accounts which has a class type named Accounts. Because my anonymous type doesn't have a constructor that takes the field values, I use a MemberInitExpression instead of the normal NewExpression (which seems unnecessarily complicated anyway?).

var objDescr = new Dictionary<string, Type> { { "Actid", typeof(Int32) }, { "Application", typeof(string) }, { "Username", typeof(string) }};
var aType = AnonymousExt.FindOrMakeAnonymousType(objDescr);

var parma = Expression.Parameter(typeof(Accounts), "a");
var fxbe = aType.GetFields().Select(fi => Expression.Bind(fi, Expression.Field(parma, fi.Name))).ToArray();
var mie = Expression.MemberInit(Expression.New(aType), fxbe);
var myf = Expression.Lambda<Func<Accounts, object>>(mie, parma);

var ans = Accounts.Select(myf).Take(2);


问:
Oracle Sql Developer "string literal too long" error
I have the following SQL that I would like to run in Oracle SQL Developer against an Oracle 10g server:

```<code>WITH openedXml AS (
  SELECT extractvalue(column_value, '/theRow/First') FIRST,
         extractvalue(column_value, '/theRow/Last') LAST,
         to_number(extractvalue(column_value, '/theRow/Age')) Age
    FROM TABLE(XMLSequence(XMLTYPE('
  <theRange>
    <theRow><First>Bob</First><Last>Smith</Last><Age>30</Age></theRow>
    <theRow><First>Sue</First><Last>Jones</Last><Age>34</Age></theRow>
...
...
...
    <theRow><First>Tom</First><Last>Anderson</Last><Age>39</Age></theRow>
    <theRow><First>Ali</First><Last>Grady</Last><Age>45</Age></theRow>
  </theRange>
  ').extract('/theRange/theRow')))
)
SELECT *
FROM openedxml
WHERE age BETWEEN 30 AND 35;
</code>```

When I attempt to run it I get the following error:

```<code>Error at Command Line:1 Column:0 Error report: SQL Error: ORA-01704: string literal too long
01704. 00000 -  "string literal too long"
*Cause:    The string literal is longer than 4000 characters.
*Action:   Use a string literal of at most 4000 characters.
           Longer values may only be entered using bind variables.
</code>```

My strings will occasionally be much longer than 4000 characters.  Any ideas about how I can get around this problem?

答:
You will need to use a CLOB as the input to XMLTYPE() instead of a VARCHAR.

Using either dbms_lob.loadclobfromfile to load the xml from a file, or by breaking up the xml into 32000 character chunks and appending to the CLOB.

```<code>DECLARE
   xmlClob CLOB;
BEGIN
/* Build Clob here */

WITH openedXml AS (
  SELECT extractvalue(column_value, '/theRow/First') FIRST,
         extractvalue(column_value, '/theRow/Last') LAST,
         to_number(extractvalue(column_value, '/theRow/Age')) Age
    FROM TABLE(XMLSequence(XMLTYPE(xmlClob).extract('/theRange/theRow')))
)
SELECT *
FROM openedxml
WHERE age BETWEEN 30 AND 35;
END;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have the following SQL that I would like to run in Oracle SQL Developer against an Oracle 10g server:

WITH openedXml AS (
  SELECT extractvalue(column_value, '/theRow/First') FIRST,
         extractvalue(column_value, '/theRow/Last') LAST,
         to_number(extractvalue(column_value, '/theRow/Age')) Age
    FROM TABLE(XMLSequence(XMLTYPE('
  <theRange>
    <theRow><First>Bob</First><Last>Smith</Last><Age>30</Age></theRow>
    <theRow><First>Sue</First><Last>Jones</Last><Age>34</Age></theRow>
...
...
...
    <theRow><First>Tom</First><Last>Anderson</Last><Age>39</Age></theRow>
    <theRow><First>Ali</First><Last>Grady</Last><Age>45</Age></theRow>
  </theRange>
  ').extract('/theRange/theRow')))
)
SELECT *
FROM openedxml
WHERE age BETWEEN 30 AND 35;

When I attempt to run it I get the following error:

Error at Command Line:1 Column:0 Error report: SQL Error: ORA-01704: string literal too long
01704. 00000 -  "string literal too long"
*Cause:    The string literal is longer than 4000 characters.
*Action:   Use a string literal of at most 4000 characters.
           Longer values may only be entered using bind variables.

My strings will occasionally be much longer than 4000 characters.  Any ideas about how I can get around this problem?

Body:
You will need to use a CLOB as the input to XMLTYPE() instead of a VARCHAR.

Using either dbms_lob.loadclobfromfile to load the xml from a file, or by breaking up the xml into 32000 character chunks and appending to the CLOB.

DECLARE
   xmlClob CLOB;
BEGIN
/* Build Clob here */

WITH openedXml AS (
  SELECT extractvalue(column_value, '/theRow/First') FIRST,
         extractvalue(column_value, '/theRow/Last') LAST,
         to_number(extractvalue(column_value, '/theRow/Age')) Age
    FROM TABLE(XMLSequence(XMLTYPE(xmlClob).extract('/theRange/theRow')))
)
SELECT *
FROM openedxml
WHERE age BETWEEN 30 AND 35;
END;

ContentLicense: CC BY-SA 3.0


问:
Npm missing script: dev
I am working on project that uses webapck , nodejs

I got npm error says

missing script: dev

I have already tried including dev attribute in package.json file

答:
Since you didn't post your package.json this is only a guess, but you need to add a "dev" attribute to your package.json below the "test" attribute in the "scripts" object. Since this is tagged in webpack and assuming you're running webpack v4, I'm guessing you're trying to run webpack-dev-server. Here is what I use as a "dev" script (feel free to change this to whatever you want):

```<code>"dev": "webpack-dev-server --hot --progress --colors --mode development --open",
</code>```

And then run either one of these commands in your terminal (depending on which package manager you're using:

```<code>npm run dev
yarn dev
</code>```

Title: Npm missing script: dev

Body:
Since you didn't post your package.json this is only a guess, but you need to add a "dev" attribute to your package.json below the "test" attribute in the "scripts" object. Since this is tagged in webpack and assuming you're running webpack v4, I'm guessing you're trying to run webpack-dev-server. Here is what I use as a "dev" script (feel free to change this to whatever you want):

"dev": "webpack-dev-server --hot --progress --colors --mode development --open",

And then run either one of these commands in your terminal (depending on which package manager you're using:

npm run dev
yarn dev


问:
Check if positive value exist in dataframe
I have dataframe:

```<code>A B C D
1 0 0 2
0 1 0 0
0 0 0 0
</code>```

I need to select all values which are greater then 0 and put them in a list.
if row doesnt contain any positive value 0 should be written to list.

So, the output for given dataframe should look like this:

```<code> [1,2,1,0]
</code>```

How this can be resolved?

答:
We can make extensive use of pandas + numpy here:

Mask all values which are greater than 0

```<code>m = df.gt(0)

       A      B      C      D
0   True  False  False   True
1  False   True  False  False
2  False  False  False  False
</code>```

Mask rows which dont contain any values above 0:

```<code>s1 = m.any(axis=1).astype(int).values
</code>```

Get all the values greater than 0 in an array:

```<code>s2 = df.values[m]
</code>```

Finally concat both arrays with each other:

```<code>np.concatenate([s2, s1[s1==0]]).tolist()
</code>```

Output

```<code>[1, 2, 1, 0]
</code>```

Body:
I have dataframe:

A B C D
1 0 0 2
0 1 0 0
0 0 0 0

I need to select all values which are greater then 0 and put them in a list.
if row doesnt contain any positive value 0 should be written to list.

So, the output for given dataframe should look like this:

 [1,2,1,0]

How this can be resolved?

Body:
We can make extensive use of pandas + numpy here:

Mask all values which are greater than 0

m = df.gt(0)

       A      B      C      D
0   True  False  False   True
1  False   True  False  False
2  False  False  False  False

Mask rows which dont contain any values above 0:

s1 = m.any(axis=1).astype(int).values

Get all the values greater than 0 in an array:

s2 = df.values[m]

Finally concat both arrays with each other:

np.concatenate([s2, s1[s1==0]]).tolist()

Output

[1, 2, 1, 0]


问:
How to change 1,000,000.00 into 1.000.000,00 with ASP classic?
I want to change number 1,000,000.00 into 1.000.000,00 with ASP classic. Please help

```<code>a=1000000
response.write formatnumber(a,0)
</code>```

It shows

```<code>1,000,000
</code>```

答:
There is no direct way to do this because the delimiter used depends on the regional settings of the Computer. See here for more on the FormatNumber function and its use.

There is a round-about way. You can have the decimal points and turn off grouping like this:

```<code>a=1000000
response.write(FormatNumber(a,2,,,0))
</code>```

You can then insert your preferred delimiter using your own function: see this example.

Body:
I want to change number 1,000,000.00 into 1.000.000,00 with ASP classic. Please help

a=1000000
response.write formatnumber(a,0)

It shows

1,000,000

Body:
There is no direct way to do this because the delimiter used depends on the regional settings of the Computer. See here for more on the FormatNumber function and its use.

There is a round-about way. You can have the decimal points and turn off grouping like this:

a=1000000
response.write(FormatNumber(a,2,,,0))

You can then insert your preferred delimiter using your own function: see this example.


问:
How to insert image into Access database using Classic ASP
I am trying to use my webcam to take a picture and save it into an Access database with other information like first name, surname etc.

I have so far created a page that is able to insert the other details into the database. I now don't know how to go about with the image.

For now, I need help on how to capture the image and save into Access table.

答:
One way you could handle this would be to instead of inserting the image, you could store it in a relevant folder with the database'images', then instead insert the path to the image.

However if you need to have it in the db, you could use attachments to table records. Ive never done this, but from a glance it looks limited. As MS access databases max out at 2GB.


问:
Cutting a database down to size
Say you have a database that has served a company for 10 years. It is 500GB in size, it has myriad tables, stored procedures and triggers.

Now say you wish to create a cut down version of the database to use as a test bed for use in integration testing and for individual testers and developers to spin up instances of to play around with.

In broad terms how would you set about this task?

In case it matters, the database I have in mind is SQL Server 2008.

Edit: removed "unit testing" because of course unit tests should not test db integration

答:
In my opinion, subsets of "real data" should not be used for unit tests. Unit tests should be independent of the initial contents of the database. They should create the data needed for the specific test, perform the test, then delete the data. Alternatively, the entire test should be within a transaction which is rolled back at the end.

If you do not do this, then your tests will fail when someone decides to delete or change the data they depend on, and you'll waste an enormous amount of time trying to find out why your tests have suddenly started to fail.

For a QA or Integration system, you should be able to create a subset of your data based on your knowledge of the relations between the tables.

Title: Cutting a database down to size


问:
I wanna repeat function infinite but i couldn't
I wanna do some effect to my background so i tought i can add some shapes flying around but i do only 1 shape i cant loop or anything

i tried call function more than a one time but it doesnt help

```<code>function animasyon(a) {
    window.onload=function(){

        var id = setInterval(anim,5);

        $('body').append('<div class=shape></div>');
        $('body').append('<div class=shape></div>');

        var kutu = document.getElementsByClassName("shape");
        var pos = 0;
        var x = window.innerWidth;
        var y = window.innerHeight;
        var borderSize = Math.floor(Math.random() * 3 ) + 1;
        var ySize = Math.floor(Math.random() * y ) + 1;
        var Size = Math.floor(Math.random() * 30 ) + 5;
        var yon = Math.floor(Math.random() *2)+1;
        var dolu = Math.floor(Math.random() *2)+1;
        if (ySize > 50) { ySize-=20; }

            function anim(){

                if (pos == x) {
                    clearInterval(id);
                    document.getElementById("shape").remove();
                }else{
                    pos++;
                    kutu[a].style.position = "absolute";
                    kutu[a].style.border = "solid rgb(119,38,53) "+borderSize+"px";
                    kutu[a].style.left = pos+"px";
                    kutu[a].style.width = Size+"px";
                    kutu[a].style.height = Size+"px";

                    if (yon == 1) { ySize-=0.2; } else { ySize+=0.2; }
                    if (dolu==1) {kutu[a].style.background = "rgb(119,38,53)";}
                    if (kutu[a].offsetTop < 0 || kutu[a].offsetTop > y-30) {document.getElementById("shape").remove();}

                    kutu[a].style.top = ySize+"px";
                }
             }
    }

}

animasyon(0);
</code>```

答:
Your problem is that you are assigning window.onload function a value inside the function animasyon

window.onload holds only 1 function. If you call animation function more than once, then the last one will overwrite the first one.

Edit: You need to separate your animation logic from the page load logic. They are completely separate things.

Here is an example of adding multiple objects and animating each separately.

```<code>// HTML
<div id="container">
  <div id="ball"></div>
  <div id="ball2"></div>
  <div id="ball3"></div>
  <div id="ball4"></div>
</div>
// CSS
#ball, #ball2, #ball3, #ball4 {
  background: red;
  border: 1px solid #FAFDFA;
  display: inline-block;
  width: 1em;
  height: 1em;
  border-radius: 2em;
  position: absolute;
}

#ball2 {
  background: blue;
}

#ball3 {
  background: green;
}

#ball4 {
  background: purple;
}

#container {
  width: 512px;
  height: 512px;
  background: black;
  position: relative;
}
// JS
const container = document.getElementById('container');
const stageWidth = 512;
const stageHeight = 512;
const makeFall = (elementId) => {
    // this function makes an enlement fall in random direction
  const animationSpeed = 4;
  // your onload function
  const ball = document.getElementById(elementId);
  let directionX = (Math.random() * animationSpeed * 2) - animationSpeed;
  let directionY = Math.random() * animationSpeed;
  const setRandomStart = () => {
    ball.style.top = '10px';
    ball.style.left = (Math.random() * (stageWidth / 2)) + 'px';
    directionX = (Math.random() * animationSpeed * 2) - animationSpeed;
    directionY = Math.random() * animationSpeed;
  }
  setRandomStart();
  let animationInterval = setInterval(() => {
    let px = parseFloat(ball.style.left);
    let py = parseFloat(ball.style.top);
    px += directionX;
    py += directionY;
    if (px > stageWidth - 20 || py > stageHeight    - 20 || px < -20) {
      setRandomStart();
    } else {
      ball.style.left = px + 'px';
      ball.style.top = py + 'px';
    }

  }, 48);
}

// In Your onload function you can add the elements and then animate

makeFall('ball');
makeFall('ball2');
makeFall('ball3');
makeFall('ball4');
</code>```

https://jsfiddle.net/753oL8re/4/

Body:
I wanna do some effect to my background so i tought i can add some shapes flying around but i do only 1 shape i cant loop or anything

i tried call function more than a one time but it doesnt help

function animasyon(a) {
    window.onload=function(){

        var id = setInterval(anim,5);

        $('body').append('

');
        $('body').append('

');

        var kutu = document.getElementsByClassName("shape");
        var pos = 0;
        var x = window.innerWidth;
        var y = window.innerHeight;
        var borderSize = Math.floor(Math.random() * 3 ) + 1;
        var ySize = Math.floor(Math.random() * y ) + 1;
        var Size = Math.floor(Math.random() * 30 ) + 5;
        var yon = Math.floor(Math.random() *2)+1;
        var dolu = Math.floor(Math.random() *2)+1;
        if (ySize > 50) { ySize-=20; }

            function anim(){

                if (pos == x) {
                    clearInterval(id);
                    document.getElementById("shape").remove();
                }else{
                    pos++;
                    kutu[a].style.position = "absolute";
                    kutu[a].style.border = "solid rgb(119,38,53) "+borderSize+"px";
                    kutu[a].style.left = pos+"px";
                    kutu[a].style.width = Size+"px";
                    kutu[a].style.height = Size+"px";

                    if (yon == 1) { ySize-=0.2; } else { ySize+=0.2; }
                    if (dolu==1) {kutu[a].style.background = "rgb(119,38,53)";}
                    if (kutu[a].offsetTop < 0 || kutu[a].offsetTop > y-30) {document.getElementById("shape").remove();}

                    kutu[a].style.top = ySize+"px";
                }
             }
    }

}

animasyon(0);

Body:
Your problem is that you are assigning window.onload function a value inside the function animasyon

window.onload holds only 1 function. If you call animation function more than once, then the last one will overwrite the first one.

Edit: You need to separate your animation logic from the page load logic. They are completely separate things.

Here is an example of adding multiple objects and animating each separately.

// HTML
<div id="container">
  <div id="ball"></div>
  <div id="ball2"></div>
  <div id="ball3"></div>
  <div id="ball4"></div>
</div>
// CSS
#ball, #ball2, #ball3, #ball4 {
  background: red;
  border: 1px solid #FAFDFA;
  display: inline-block;
  width: 1em;
  height: 1em;
  border-radius: 2em;
  position: absolute;
}

#ball2 {
  background: blue;
}

#ball3 {
  background: green;
}

#ball4 {
  background: purple;
}

#container {
  width: 512px;
  height: 512px;
  background: black;
  position: relative;
}
// JS
const container = document.getElementById('container');
const stageWidth = 512;
const stageHeight = 512;
const makeFall = (elementId) => {
    // this function makes an enlement fall in random direction
  const animationSpeed = 4;
  // your onload function
  const ball = document.getElementById(elementId);
  let directionX = (Math.random() * animationSpeed * 2) - animationSpeed;
  let directionY = Math.random() * animationSpeed;
  const setRandomStart = () => {
    ball.style.top = '10px';
    ball.style.left = (Math.random() * (stageWidth / 2)) + 'px';
    directionX = (Math.random() * animationSpeed * 2) - animationSpeed;
    directionY = Math.random() * animationSpeed;
  }
  setRandomStart();
  let animationInterval = setInterval(() => {
    let px = parseFloat(ball.style.left);
    let py = parseFloat(ball.style.top);
    px += directionX;
    py += directionY;
    if (px > stageWidth - 20 || py > stageHeight    - 20 || px < -20) {
      setRandomStart();
    } else {
      ball.style.left = px + 'px';
      ball.style.top = py + 'px';
    }

  }, 48);
}

// In Your onload function you can add the elements and then animate

makeFall('ball');
makeFall('ball2');
makeFall('ball3');
makeFall('ball4');

https://jsfiddle.net/753oL8re/4/


问:
getting Null on handler intermittently when trying to retrieve last handler in Netty
I have a netty client that connect to remote server for a request-response. I want to block till the remote connection is successful and parse the response. My handler is similar to Netty factorial example in retrieving the results.

Here is what I have

```<code>Channel ch = bootstrap.connect(addr).sync().channel();
ChannelFuture f = ch.writeAndFlush(obj);
//blocking operation
ch.closeFuture().sync();
MyHandler handler = (MyHandler) f.channel().pipeline().last(); //this handler is null
String responseString = handler.responseString;
f.channel().close();
</code>```

Handler code

```<code>MyHandler extends ChannelInboundHandlerAdapter {

     public String result = null;
       @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof FullHttpResponse) {
            result = parse(msg);
         }
        // The following line automatically closes the channel:

ctx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }
    }
</code>```

why is the handler null intermittently and what is the right way to do it? (I commented on the line where NPE is thrown)

答:
One of the things you need to be aware of, is that when the Netty channel is in the progress of being closed, the last step is that it removes all handlers, this step is required so all cleanup routines get run inside those handlers.

This means, that after the channel is closed, you cannot access any of the handlers in the pipeline.

Inside your code, you are waiting for the event that a channel has fully closed, this means that the code afterwards has an "happens after" relation to the channel close event.

One solution for this is making a custom promise object, and passing this to the handler, who then fills it with a response:

// Somewhere inside the application:
public static final AttributeKey<Promise<String>> RESPONSE = new AttributeKey("RESPONSE");

ChannelFuture chf = bootstrap.connect(addr);
Promise<String> p = chf.channel().eventLoop().newPromise();
chf.channel().attr(RESPONSE).set(p);
//blocking operation
Channel ch = chf.sync().channel();
ChannelFuture f = ch.writeAndFlush(obj);
//blocking operation
String responseString = p.get();
f.channel().close();

....

// Inside you handler

MyHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof FullHttpResponse) {
            ctx.channel().attr(RESPONSE).get().setSuccess(parse(msg));
        }
        // The following line automatically closes the channel:
        ctx.channel()
            .writeAndFlush(Unpooled.EMPTY_BUFFER)
            .addListener(ChannelFutureListener.CLOSE);
    }
}
```

This solution works, because even though the channel and its attributes gets cleaned on choose, we still have a reference to the promise that contains the final result

Body:
I have a netty client that connect to remote server for a request-response. I want to block till the remote connection is successful and parse the response. My handler is similar to Netty factorial example in retrieving the results.

Here is what I have

Channel ch = bootstrap.connect(addr).sync().channel();
ChannelFuture f = ch.writeAndFlush(obj);
//blocking operation
ch.closeFuture().sync();
MyHandler handler = (MyHandler) f.channel().pipeline().last(); //this handler is null
String responseString = handler.responseString;
f.channel().close();

Handler code

MyHandler extends ChannelInboundHandlerAdapter {

     public String result = null;
       @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof FullHttpResponse) {
            result = parse(msg);
         }
        // The following line automatically closes the channel:

ctx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }
    }

why is the handler null intermittently and what is the right way to do it? (I commented on the line where NPE is thrown)

Body:
One of the things you need to be aware of, is that when the Netty channel is in the progress of being closed, the last step is that it removes all handlers, this step is required so all cleanup routines get run inside those handlers.

This means, that after the channel is closed, you cannot access any of the handlers in the pipeline.

Inside your code, you are waiting for the event that a channel has fully closed, this means that the code afterwards has an "happens after" relation to the channel close event.

One solution for this is making a custom promise object, and passing this to the handler, who then fills it with a response:

// Somewhere inside the application:
public static final AttributeKey<Promise<String>> RESPONSE = new AttributeKey("RESPONSE");

ChannelFuture chf = bootstrap.connect(addr);
Promise<String> p = chf.channel().eventLoop().newPromise();
chf.channel().attr(RESPONSE).set(p);
//blocking operation
Channel ch = chf.sync().channel();
ChannelFuture f = ch.writeAndFlush(obj);
//blocking operation
String responseString = p.get();
f.channel().close();

....

// Inside you handler

MyHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof FullHttpResponse) {
            ctx.channel().attr(RESPONSE).get().setSuccess(parse(msg));
        }
        // The following line automatically closes the channel:
        ctx.channel()
            .writeAndFlush(Unpooled.EMPTY_BUFFER)
            .addListener(ChannelFutureListener.CLOSE);
    }
}

This solution works, because even though the channel and its attributes gets cleaned on choose, we still have a reference to the promise that contains the final result


问:
Remove first element of JSON object array
I'm struggling to find a way to cut down this JSON array so I can use the values remaining. Below is what's returned to me from the API I'm fetching and I'm looking to remove the excess so I just have an array with the LGA results. Really unsure where to even start.</p>

```<code>{
  "query": {
    "offence": "Dangerous Operation of a Vehicle",
    "area": "",
    "age": "",
    "year": "",
    "gender": ""
  },
  "result": [
    {
      "LGA": "Aurukun Shire Council",
      "total": 156,
      "lat": -13.354875,
      "lng": 141.729058
    },
    {
      "LGA": "Balonne Shire Council",
      "total": 99,
      "lat": -28.464607,
      "lng": 148.189292
    },
    {
      "LGA": "Yarrabah Shire Council",
      "total": 28,
      "lat": -16.910135,
      "lng": 145.868659
    }
  ]
}
</code>```

答:
for example, if you want only LGA values, you could use something like that:

```<code>let parsedJson = JSON.parse(json);                //parse json to object
let onlyLGAValues = {};                           //create a new dictionary

parsedJson.result.forEach(function(key, index){   //for each result
    onlyLGAValues[index] = key.LGA;               //push the LGA value in the new dictionary
});

console.log(onlyLGAValues);
</code>```

expected output:

```<code>{0: "Aurukun Shire Council", 1: "Balonne Shire Council", ... 77: "Yarrabah Shire Council"}
</code>```

Body:
I'm struggling to find a way to cut down this JSON array so I can use the values remaining. Below is what's returned to me from the API I'm fetching and I'm looking to remove the excess so I just have an array with the LGA results. Really unsure where to even start.

{
  "query": {
    "offence": "Dangerous Operation of a Vehicle",
    "area": "",
    "age": "",
    "year": "",
    "gender": ""
  },
  "result": [
    {
      "LGA": "Aurukun Shire Council",
      "total": 156,
      "lat": -13.354875,
      "lng": 141.729058
    },
    {
      "LGA": "Balonne Shire Council",
      "total": 99,
      "lat": -28.464607,
      "lng": 148.189292
    },
    {
      "LGA": "Yarrabah Shire Council",
      "total": 28,
      "lat": -16.910135,
      "lng": 145.868659
    }
  ]
}

Body:
for example, if you want only LGA values, you could use something like that:

let parsedJson = JSON.parse(json);                //parse json to object
let onlyLGAValues = {};                           //create a new dictionary

parsedJson.result.forEach(function(key, index){   //for each result
    onlyLGAValues[index] = key.LGA;               //push the LGA value in the new dictionary
});

console.log(onlyLGAValues);

expected output:

{0: "Aurukun Shire Council", 1: "Balonne Shire Council", ... 77: "Yarrabah Shire Council"}


问:
Double authentication connection cannot be redirected
I am trying to set up a double authentication page under laravel, for that I add a checkTotp method that verifies that the user has activate double authentication and redirect this user to the page in question.

The problem is that I am not redirected and the code continues to execute.

public function login(Request $request)
{
    $this->validateLogin($request);
    ...
    $this->checkTotp($request);
    dd('after');
    ...
}

protected function checkTotp(Request $request)
{
    $user = User::where('email', $request->get('email'))->first();
    if (!is_null($user->totp_key)) {
        $request->session()->put('user_id', $user->id);
        return redirect('login/totp');
    }
}
```

What happens is that I enter the checkTotp method but the redirect does not work. My output is the dd('after'). I don't understand why I am not redirected. Can someone help me?

Quentin

答:
The checkTotp function returns a redirect, but you want the login function to return that redirect, such that it is passed to the browser. You might want to move the redirect to the main function and let checkTOTP just return true/false.

```<code>public function login(Request $request)
{
    $this->validateLogin($request);
    ...
    if ($this->checkTotp($request)) return redirect('login/totp');
    dd('after');
    ...
}

protected function checkTotp(Request $request)
{
    $user = User::where('email', $request->get('email'))->first();
    if (!is_null($user->totp_key)) {
        $request->session()->put('user_id', $user->id);
        return true;
    }
    return false;
}
</code>```

Body:
I am trying to set up a double authentication page under laravel, for that I add a checkTotp method that verifies that the user has activate double authentication and redirect this user to the page in question.

The problem is that I am not redirected and the code continues to execute.

public function login(Request $request)
{
    $this->validateLogin($request);
    ...
    $this->checkTotp($request);
    dd('after');
    ...
}

protected function checkTotp(Request $request)
{
    $user = User::where('email', $request->get('email'))->first();
    if (!is_null($user->totp_key)) {
        $request->session()->put('user_id', $user->id);
        return redirect('login/totp');
    }
}

What happens is that I enter the checkTotp method but the redirect does not work. My output is the dd('after'). I don't understand why I am not redirected. Can someone help me?

Quentin

Body:
The checkTotp function returns a redirect, but you want the login function to return that redirect, such that it is passed to the browser. You might want to move the redirect to the main function and let checkTOTP just return true/false.

public function login(Request $request)
{
    $this->validateLogin($request);
    ...
    if ($this->checkTotp($request)) return redirect('login/totp');
    dd('after');
    ...
}

protected function checkTotp(Request $request)
{
    $user = User::where('email', $request->get('email'))->first();
    if (!is_null($user->totp_key)) {
        $request->session()->put('user_id', $user->id);
        return true;
    }
    return false;
}


问:
Disable editing but allow continued typing in swift
I’m making an app where the user needs to be able to type long pieces of text (like a journal article) but shouldn’t be allowed to edit it until a later stage in the app.

So I need to allow the user to type in a UITextField in a ‘forwards’ direction but completely disable being able to select the text further up and edit it (or even use the backspace).

There are plenty of answers already around disabling the selecting/editing (for example when using a picker view as the input e.g. Disabling user input for UITextfield in swift) but I can’t find anything that would allow for the behaviour I want and despite trying variations of the text field delegate methods I really cant get my head around where to go next at the moment.

I’m thinking I need to do 3 things

1) allow editing of the text field
2) disable selecting (by tapping for example) the text field
3) disable the backspace key?

答:
As far as I understand this code can help you:

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return textField.text!.count <= range.location
}
</code>```

this method is from the delegate of your UITextField.

Also, you can add more complex checks with range and replacement string. Like if you want to add more text or you want to delete text.

Body:
As far as I understand this code can help you:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return textField.text!.count <= range.location
}

this method is from the delegate of your UITextField.

Also, you can add more complex checks with range and replacement string. Like if you want to add more text or you want to delete text.


问:
How can I change column types in Spark SQL's DataFrame?
Suppose I'm doing something like:

```<code>val df = sqlContext.load("com.databricks.spark.csv", Map("path" -> "cars.csv", "header" -> "true"))
df.printSchema()

root
 |-- year: string (nullable = true)
 |-- make: string (nullable = true)
 |-- model: string (nullable = true)
 |-- comment: string (nullable = true)
 |-- blank: string (nullable = true)

df.show()
year make  model comment              blank
2012 Tesla S     No comment
1997 Ford  E350  Go get one now th...
</code>```

But I really wanted the year as Int (and perhaps transform some other columns).

The best I could come up with was

```<code>df.withColumn("year2", 'year.cast("Int")).select('year2 as 'year, 'make, 'model, 'comment, 'blank)
org.apache.spark.sql.DataFrame = [year: int, make: string, model: string, comment: string, blank: string]
</code>```

which is a bit convoluted.

I'm coming from R, and I'm used to being able to write, e.g.

```<code>df2 <- df %>%
   mutate(year = year %>% as.integer,
          make = make %>% toupper)
</code>```

I'm likely missing something, since there should be a better way to do this in Spark/Scala...

答:
Another solution is as follows:

1) Keep "inferSchema" as False

2) While running 'Map' functions on the row, you can read 'asString' (row.getString...)

```<code>//Read CSV and create dataset
Dataset<Row> enginesDataSet = sparkSession
            .read()
            .format("com.databricks.spark.csv")
            .option("header", "true")
            .option("inferSchema","false")
            .load(args[0]);

JavaRDD<Box> vertices = enginesDataSet
            .select("BOX","BOX_CD")
            .toJavaRDD()
            .map(new Function<Row, Box>() {
                @Override
                public Box call(Row row) throws Exception {
                    return new Box((String)row.getString(0),(String)row.get(1));
                }
            });
</code>```

Body:
Suppose I'm doing something like:

val df = sqlContext.load("com.databricks.spark.csv", Map("path" -> "cars.csv", "header" -> "true"))
df.printSchema()

root
 |-- year: string (nullable = true)
 |-- make: string (nullable = true)
 |-- model: string (nullable = true)
 |-- comment: string (nullable = true)
 |-- blank: string (nullable = true)

df.show()
year make  model comment              blank
2012 Tesla S     No comment
1997 Ford  E350  Go get one now th...

But I really wanted the year as Int (and perhaps transform some other columns).

The best I could come up with was

df.withColumn("year2", 'year.cast("Int")).select('year2 as 'year, 'make, 'model, 'comment, 'blank)
org.apache.spark.sql.DataFrame = [year: int, make: string, model: string, comment: string, blank: string]

which is a bit convoluted.

I'm coming from R, and I'm used to being able to write, e.g.

df2 <- df %>%
   mutate(year = year %>% as.integer,
          make = make %>% toupper)

I'm likely missing something, since there should be a better way to do this in Spark/Scala...

Body:
Another solution is as follows:

1) Keep "inferSchema" as False

2) While running 'Map' functions on the row, you can read 'asString' (row.getString...)

//Read CSV and create dataset
Dataset<Row> enginesDataSet = sparkSession
            .read()
            .format("com.databricks.spark.csv")
            .option("header", "true")
            .option("inferSchema","false")
            .load(args[0]);

JavaRDD<Box> vertices = enginesDataSet
            .select("BOX","BOX_CD")
            .toJavaRDD()
            .map(new Function<Row, Box>() {
                @Override
                public Box call(Row row) throws Exception {
                    return new Box((String)row.getString(0),(String)row.get(1));
                }
            });


问:
Why can't I use var in this instance?
I am using the code below and for some reason I can't use var to declare my variable. I am brand new to asp/c# so please go easy on me. I've had a look around and I can't find the correct way of doing this:

```<code>var brandslist = from brand in brandDB.brands
                         join brand_family in brandDB.brand_family on brand.brand_family_id equals brand_family.bf_id
                         orderby brand_family.brand_family_name
                         orderby brand.priority
                         orderby brand.genre_id
                         select brand_family.brand_family_name, priority, roll_image;
</code>```

Thanks to anyone who can tell me the correct method of making this work.

答:
var exposes the enumerator, which supports a simple iteration over a collection of a specified type. In your select brand_family.brand_family_name, priority, roll_image;
you are returning multiple items.</p>

Title: Why can't I use var in this instance?

Body:
I am using the code below and for some reason I can't use var to declare my variable. I am brand new to asp/c# so please go easy on me. I've had a look around and I can't find the correct way of doing this:

var brandslist = from brand in brandDB.brands
                         join brand_family in brandDB.brand_family on brand.brand_family_id equals brand_family.bf_id
                         orderby brand_family.brand_family_name
                         orderby brand.priority
                         orderby brand.genre_id
                         select brand_family.brand_family_name, priority, roll_image;

Thanks to anyone who can tell me the correct method of making this work.


问:
Django raw query giving same result on all models
I have 3 models Product, Photo, and ProductLikeDilike. I am performing left outer join on all the 3 models. First I am joining Product with Photo and then the resultant table(temp) I am joining with ProductLikeDilike. Below is the raw sql.

Note: olx is the name of django app.

```<code>data = Product.objects.raw('select * from (select
    olx_product.id,olx_product.name,olx_photo.file,olx_photo.cover_photo_flag
    from olx_product left outer join olx_photo on
    (olx_product.id=olx_photo.reference_id_id) where
    olx_photo.cover_photo_flag="yes" or olx_photo.cover_photo_flag is null) as
    temp left outer join olx_productlikedislike on
    (temp.id=olx_productlikedislike.product_id_id and
    olx_productlikedislike.product_liked_by_id_id=2)')

for x in data:
  print(x.name)
</code>```

What I want to understand that when I use any of the above 3 models to run the raw sql why I am getting the same result i.e.

When I do

```<code>data = Product.objects.raw('select *.....')
for x in data:
  print(x.name)
</code>```

or

```<code>data = Photo.objects.raw('select *......')
for x in data:
  print(x.name)
</code>```

or

```<code>data = ProductLikeDislike.raw('select *.....')
for x in data:
  print(x.name)
</code>```

I am getting the same result. Why?
Please help me to understand this.

Below is the models.py file

```<code>from django.db import models
from django.urls import reverse
from django.dispatch import receiver
from django.contrib.auth.models import User

    class Product(models.Model):
        category = models.ForeignKey(Category ,on_delete=models.CASCADE)
        name = models.CharField(max_length = 200, db_index = True)
        slug = models.SlugField(max_length = 200, db_index = True)
        description = models.TextField(blank = True)
        price = models.DecimalField(max_digits = 10, decimal_places = 2 )#Not used FloatField to avoid rounding issues
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)

        contact= models.BigIntegerField(default=None,blank=True, null=True)
        created_by = models.CharField(max_length = 200, default=None,blank=True, null=True)
        uploaded_by_id = models.IntegerField(default=0)
        status = models.IntegerField(default=0) # 0-->Active,1-->Inactive
        mark_as_sold = models.IntegerField(default=0) # 0-->not sold,1-->sold

        def get_absolute_url(self):
            return reverse('olx:edit_product', kwargs={'pk': self.pk})

        class Meta:
            ordering = ('-created',)
            index_together = (('id','slug'),)# we want to query product by id and slug using together index to improve performance

        def __str__(self):
            return self.name

    class Photo(models.Model):

        reference_id = models.ForeignKey(Product, null=True,on_delete=models.CASCADE)
        photo_type = models.CharField(max_length = 70, db_index = True)
        file = models.FileField(upload_to='photos/',default='NoImage.jpg')
        cover_photo_flag = models.CharField(default=0,max_length = 5, db_index = True)
        uploaded_at = models.DateTimeField(auto_now_add=True)
        uploaded_by_id = models.IntegerField(default=0)
        status = models.IntegerField(default=0) # 0-->Active,1-->Inactive

        class Meta:
            ordering = ('-uploaded_at',)

    class ProductLikeDislike(models.Model):
        product_id = models.ForeignKey(Product,models.SET_DEFAULT,default=0)
        product_liked_by_id = models.ForeignKey(User,models.SET_DEFAULT,default=0)
        status = models.BooleanField(default=False)
</code>```

And Please also show me how to write it in pure Django way if possible?

答:
I am getting the same result. Why? Please help me to understand this.

Because .raw(..) [Django-doc] just takes a raw query and executes it. The model from which the raw is performed is irrelevant.

We can generate a query that looks like:

```<code>from django.db.models import <b>Q</b>

Product.objects.filter(
    Q(photo__photo_flag__isnull=True) | Q(photo__photo_flag='yes'),
    Q(likedislike__product_liked_by_id_id=2)
)</code>```

So here we accept all Products for which a related Photo object has a flag that is NULL (this also happens in case the JOIN does not yield any flags), or the photo_flag is 'yes'). Furthermore there should be a Likedislike object where the liked_by_id_id is 2.

Note that usually a ForeignKey [Django-doc] has no _id suffix, or id_ prefix. It is also a bit "odd" that you set a default=0 for this, especially since most databases only assign strictly positive values as primary keys, and it makes no sense to inherently prefer 0 over another object anyway.

Body:
I have 3 models Product, Photo, and ProductLikeDilike. I am performing left outer join on all the 3 models. First I am joining Product with Photo and then the resultant table(temp) I am joining with ProductLikeDilike. Below is the raw sql.

Note: olx is the name of django app.

data = Product.objects.raw('select * from (select
    olx_product.id,olx_product.name,olx_photo.file,olx_photo.cover_photo_flag
    from olx_product left outer join olx_photo on
    (olx_product.id=olx_photo.reference_id_id) where
    olx_photo.cover_photo_flag="yes" or olx_photo.cover_photo_flag is null) as
    temp left outer join olx_productlikedislike on
    (temp.id=olx_productlikedislike.product_id_id and
    olx_productlikedislike.product_liked_by_id_id=2)')

for x in data:
  print(x.name)

What I want to understand that when I use any of the above 3 models to run the raw sql why I am getting the same result i.e.

When I do

data = Product.objects.raw('select *.....')
for x in data:
  print(x.name)

or

data = Photo.objects.raw('select *......')
for x in data:
  print(x.name)

or

data = ProductLikeDislike.raw('select *.....')
for x in data:
  print(x.name)

I am getting the same result. Why?
Please help me to understand this.

Below is the models.py file

from django.db import models
from django.urls import reverse
from django.dispatch import receiver
from django.contrib.auth.models import User

    class Product(models.Model):
        category = models.ForeignKey(Category ,on_delete=models.CASCADE)
        name = models.CharField(max_length = 200, db_index = True)
        slug = models.SlugField(max_length = 200, db_index = True)
        description = models.TextField(blank = True)
        price = models.DecimalField(max_digits = 10, decimal_places = 2 )#Not used FloatField to avoid rounding issues
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)

        contact= models.BigIntegerField(default=None,blank=True, null=True)
        created_by = models.CharField(max_length = 200, default=None,blank=True, null=True)
        uploaded_by_id = models.IntegerField(default=0)
        status = models.IntegerField(default=0) # 0-->Active,1-->Inactive
        mark_as_sold = models.IntegerField(default=0) # 0-->not sold,1-->sold

        def get_absolute_url(self):
            return reverse('olx:edit_product', kwargs={'pk': self.pk})

        class Meta:
            ordering = ('-created',)
            index_together = (('id','slug'),)# we want to query product by id and slug using together index to improve performance

        def __str__(self):
            return self.name

    class Photo(models.Model):

        reference_id = models.ForeignKey(Product, null=True,on_delete=models.CASCADE)
        photo_type = models.CharField(max_length = 70, db_index = True)
        file = models.FileField(upload_to='photos/',default='NoImage.jpg')
        cover_photo_flag = models.CharField(default=0,max_length = 5, db_index = True)
        uploaded_at = models.DateTimeField(auto_now_add=True)
        uploaded_by_id = models.IntegerField(default=0)
        status = models.IntegerField(default=0) # 0-->Active,1-->Inactive

        class Meta:
            ordering = ('-uploaded_at',)

    class ProductLikeDislike(models.Model):
        product_id = models.ForeignKey(Product,models.SET_DEFAULT,default=0)
        product_liked_by_id = models.ForeignKey(User,models.SET_DEFAULT,default=0)
        status = models.BooleanField(default=False)

And Please also show me how to write it in pure Django way if possible?

Body:
I am getting the same result. Why? Please help me to understand this.

Because .raw(..) [Django-doc] just takes a raw query and executes it. The model from which the raw is performed is irrelevant.

We can generate a query that looks like:

from django.db.models import Q

Product.objects.filter(
    Q(photo__photo_flag__isnull=True) | Q(photo__photo_flag='yes'),
    Q(likedislike__product_liked_by_id_id=2)
)

So here we accept all Products for which a related Photo object has a flag that is NULL (this also happens in case the JOIN does not yield any flags), or the photo_flag is 'yes'). Furthermore there should be a Likedislike object where the liked_by_id_id is 2.

Note that usually a ForeignKey [Django-doc] has no _id suffix, or id_ prefix. It is also a bit "odd" that you set a default=0 for this, especially since most databases only assign strictly positive values as primary keys, and it makes no sense to inherently prefer 0 over another object anyway.


问:
Android Studio Collapse definitions and methods
How can I collapse all definitions and methods within the Android Studio editor?

Visual Studio has that option on Edit-->Outlining, but I cannot find a similar feature in Android Studio. I am sure that this feature exists.

How can I access Android Studio's outlining feature?

答:
If you want turn off all collapsing you need uncheck all fields in the Settings > Editor > General > Code Folding

Also you can use hot keys

ctrl + shift + + — expand code blocks

ctrl + shift + - — collapse code blocks


问:
Programming: Principles and Practice Using C++ chapter 4 drill step 6 : General question about numeric range
I want to prompt the user for some double, then store the smallest and largest value and then prints a text. This is the code I have so far:

```<code>#include <iostream>
#include <string>
#include <cmath>
#include <vector>

using namespace std;

int main()
{
    double min = 1000000000; // Here is my issue !
    double max = -100000000; // Here is my issue !
    for (double input; cin >> input;)
    {
        if (input == '|')
            return 0;
        else if (input < min)
        {
            min = input;
            cout << "The smallest so far\n";
        }
        else if (input > max)
        {
            max = input;
            cout << "The largest so far\n";
        }
        else
            cout << "\n";
    }
}
</code>```

So my code is working fine and doing what I want, but I have a question about the way to handle the double min and max.
I must give them a value to get my program working, but giving them a value inpact the user. If I don't set them high or low enough the user might input value that don't trigger the program.
So I set them up at arbitrary high/low number.
But I wonder if there is a better solution for this.

答:
If I don't set them high or low enough the user might input value that don't trigger the program.

Correct.

But I wonder if there is a better solution for this.

There is!

1000000000 may indeed be not enough. You might be interested in numeric limits. What you want is:

```<code>double min = std::numeric_limits<double>::max();
double max = std::numeric_limits<double>::lowest();
</code>```

which will set both values to the greatest and smallest representable double, respectively.

Don't forget to #include <limits>.

Body:
I want to prompt the user for some double, then store the smallest and largest value and then prints a text. This is the code I have so far:

#include <iostream>
#include <string>
#include <cmath>
#include <vector>

using namespace std;

int main()
{
    double min = 1000000000; // Here is my issue !
    double max = -100000000; // Here is my issue !
    for (double input; cin >> input;)
    {
        if (input == '|')
            return 0;
        else if (input < min)
        {
            min = input;
            cout << "The smallest so far\n";
        }
        else if (input > max)
        {
            max = input;
            cout << "The largest so far\n";
        }
        else
            cout << "\n";
    }
}

So my code is working fine and doing what I want, but I have a question about the way to handle the double min and max.
I must give them a value to get my program working, but giving them a value inpact the user. If I don't set them high or low enough the user might input value that don't trigger the program.
So I set them up at arbitrary high/low number.
But I wonder if there is a better solution for this.

Body:
If I don't set them high or low enough the user might input value that don't trigger the program.

Correct.

But I wonder if there is a better solution for this.

There is!

1000000000 may indeed be not enough. You might be interested in numeric limits. What you want is:

double min = std::numeric_limits<double>::max();
double max = std::numeric_limits<double>::lowest();

which will set both values to the greatest and smallest representable double, respectively.

Don't forget to #include <limits>.


问:
Changing "src" attribute of an image to another image file?
This portion of my assignment is instructing me to change the src attribute of a collection of star images to another image file.

I've tried numerous combinations of removeAttribute() and setAttribute(), but no luck.  I'm probably thinking down the wrong path here.

```<code>function lightStars () {
   var starNumber = e.target.alt;
   var stars = document.querySelectorAll("span#stars img");
for (var i = 0; i < starNumber; i++) {
   stars.setAttribute("src", "bw_star2.png");
}
}
</code>```

HTML Code:

```<code><label id="ratingLabel" for="rating">Rate this title
           <span id="stars">
           <img src="bw_star.png" alt="1" />
           <img src="bw_star.png" alt="2" />
           <img src="bw_star.png" alt="3" />
           <img src="bw_star.png" alt="4" />
           <img src="bw_star.png" alt="5" /></span>
           <input type="text" name="rating" id="rating" readonly value="" />
</label>
</code>```

The purpose of this function is to color a star when the user moves the mouse pointer over a star image in order to reflect the user’s rating of the book.

I hope I explained this properly.

答:
Instead of imgs, I used glyphicons. querySelectorAll return list of elements. So in order to change its attribute values you need to iterate over it.

const imgs = document.querySelectorAll('span');

imgs.forEach((img) => {
    img.addEventListener('mouseover', function()  {
      const ratings = this.getAttribute('data-rating');
      for(let i = 0; i < ratings; i++) {
          imgs[i].setAttribute('class', 'glyphicon glyphicon-star');
      }

      for(let j = ratings; j < imgs.length; j++) {
          imgs[j].setAttribute('class', 'glyphicon glyphicon-star-empty');
      }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<label id="ratingLabel" for="rating">Rate this title
        <span class="glyphicon glyphicon-star-empty" aria-hidden="true" data-rating="1"></span>
        <span class="glyphicon glyphicon-star-empty" aria-hidden="true" data-rating="2"></span>
        <span class="glyphicon glyphicon-star-empty" aria-hidden="true" data-rating="3"></span>
        <span class="glyphicon glyphicon-star-empty" aria-hidden="true" data-rating="4"></span>
        <span class="glyphicon glyphicon-star-empty" aria-hidden="true" data-rating="5"></span>
        <input type="text" name="rating" id="rating" readonly value="" />
     </label></code>```

Body:
This portion of my assignment is instructing me to change the src attribute of a collection of star images to another image file.

I've tried numerous combinations of removeAttribute() and setAttribute(), but no luck.  I'm probably thinking down the wrong path here.

function lightStars () {
   var starNumber = e.target.alt;
   var stars = document.querySelectorAll("span#stars img");
for (var i = 0; i < starNumber; i++) {
   stars.setAttribute("src", "bw_star2.png");
}
}

HTML Code:

Rate this title

           <input type="text" name="rating" id="rating" readonly value="" />

The purpose of this function is to color a star when the user moves the mouse pointer over a star image in order to reflect the user’s rating of the book.

I hope I explained this properly.

Body:
Instead of imgs, I used glyphicons. querySelectorAll return list of elements. So in order to change its attribute values you need to iterate over it.

const imgs = document.querySelectorAll('span');

imgs.forEach((img) => {
    img.addEventListener('mouseover', function()  {
      const ratings = this.getAttribute('data-rating');
      for(let i = 0; i < ratings; i++) {
          imgs[i].setAttribute('class', 'glyphicon glyphicon-star');
      }

      for(let j = ratings; j < imgs.length; j++) {
          imgs[j].setAttribute('class', 'glyphicon glyphicon-star-empty');
      }
  });
});

<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<label id="ratingLabel" for="rating">Rate this title
        <span class="glyphicon glyphicon-star-empty" aria-hidden="true" data-rating="1"></span>
        <span class="glyphicon glyphicon-star-empty" aria-hidden="true" data-rating="2"></span>
        <span class="glyphicon glyphicon-star-empty" aria-hidden="true" data-rating="3"></span>
        <span class="glyphicon glyphicon-star-empty" aria-hidden="true" data-rating="4"></span>
        <span class="glyphicon glyphicon-star-empty" aria-hidden="true" data-rating="5"></span>
        <input type="text" name="rating" id="rating" readonly value="" />
     </label>


问:
Pythonic way to avoid a mountain of if...else statements?
This has come up several times recently and I'd like to deal with it better than I have been: I have a series of attributes that I'm cross referencing between an object and a dictionary.  If the value is different between them, I want to set the object.attribute to the dictionary['attribute'] value.  I also want to keep track of what's getting changed.

Now, my first thought is to just use an if else statement for every attribute, but after writing a few of these it's apparent that I'm re-writing the same code again and again.  There has to be a DRY way to do this, where I specify only the parts that are changing every time, and then loop through all the attributes.

In production code, there are 15 different attributes, but my example below will just use 2 for simplicity.  I have some idea about how to do this in a clever way, but I'm missing the final step of actually setting the object.attribute equal to the dictionary['attribute'] value.

```<code># Simulated data setup - not under my control IRL
class someClass:
    def __init__(self, name, version):
        self.name = name
        self.version = version

objA = someClass('Test1','1.1')
dictA = {'name':'Test1','revision':'1.2'}

# My code below

# option 1 - a series of for loops
def updateAttributesSimple(obj, adict, msg):
    if obj.name == adict['name']:
        msg.append('Name is the same')
    else:
        msg.append('Name was updated from %s to %s' % (obj.name, adict['name']))
        obj.name = adict['name']

    if obj.version == adict['revision']:
        msg.append('Version is the same')
    else:
        msg.append('Version was updated from %s to %s' % (obj.version, adict['revision']))
        obj.version = adict['revision']

# option 2 - trying to be clever about this
def updateAttributesClever(obj, adict, msg):
    attributeList = (('Name', obj.name, adict['name']),
                     ('Version', obj.version, adict['revision']))

    for valTuple in attributeList:
        if valTuple[1] == valTuple[2]:
            msg.append('%s is the same' % (valTuple[0]))
        else:
            msg.append('%s was updated from %s to %s' % (valTuple[0], valTuple[1], valTuple[2]))
            # code to set valTuple[1] = valTuple[2] goes here, but what is it?
            # valTuple[1] = valTuple[2] attempts to set the desired value to a string, rather than the attribute of obj itself

msg = ['Updating Attributes simple way:']
updateAttributesSimple(objA, dictA, msg)
print '\n\t'.join(msg)

#reset data
objA = someClass('Test1','1.1')
dictA = {'name':'Test1','revision':'1.2'}

msg = ['Updating Attributes clever way:']
updateAttributesClever(objB, dictB, msg)
print '\n\t'.join(msg)
</code>```

The idea being that this way, whenever I need to add another attribute, I can just update the list of attributes being inspected and the rest of the code is already written.  What's the Pythonic way to accomplish this?

答:
This should work for your:</p>

```<code>class X(object):
    def __init__(self):
        self.a = 1
        self.b = 2

x = X()

d = dict()
d['a'] = 1
d['b'] = 3

def updateAttributes(obj,dic):
    def update(name):
        val = dic[name]
        if getattr(obj,name)==val:
            print name,"was equal"
        else:
            print "setting %s to %s" % (name,val)
            setattr(obj,name,val)

    for name in ['a','b']:
        update(name)

updateAttributes(x,d)
print x.a
print x.b
</code>```

Body:
This has come up several times recently and I'd like to deal with it better than I have been: I have a series of attributes that I'm cross referencing between an object and a dictionary.  If the value is different between them, I want to set the object.attribute to the dictionary['attribute'] value.  I also want to keep track of what's getting changed.

Now, my first thought is to just use an if else statement for every attribute, but after writing a few of these it's apparent that I'm re-writing the same code again and again.  There has to be a DRY way to do this, where I specify only the parts that are changing every time, and then loop through all the attributes.

In production code, there are 15 different attributes, but my example below will just use 2 for simplicity.  I have some idea about how to do this in a clever way, but I'm missing the final step of actually setting the object.attribute equal to the dictionary['attribute'] value.

# Simulated data setup - not under my control IRL
class someClass:
    def __init__(self, name, version):
        self.name = name
        self.version = version

objA = someClass('Test1','1.1')
dictA = {'name':'Test1','revision':'1.2'}

# My code below

# option 1 - a series of for loops
def updateAttributesSimple(obj, adict, msg):
    if obj.name == adict['name']:
        msg.append('Name is the same')
    else:
        msg.append('Name was updated from %s to %s' % (obj.name, adict['name']))
        obj.name = adict['name']

    if obj.version == adict['revision']:
        msg.append('Version is the same')
    else:
        msg.append('Version was updated from %s to %s' % (obj.version, adict['revision']))
        obj.version = adict['revision']

# option 2 - trying to be clever about this
def updateAttributesClever(obj, adict, msg):
    attributeList = (('Name', obj.name, adict['name']),
                     ('Version', obj.version, adict['revision']))

    for valTuple in attributeList:
        if valTuple[1] == valTuple[2]:
            msg.append('%s is the same' % (valTuple[0]))
        else:
            msg.append('%s was updated from %s to %s' % (valTuple[0], valTuple[1], valTuple[2]))
            # code to set valTuple[1] = valTuple[2] goes here, but what is it?
            # valTuple[1] = valTuple[2] attempts to set the desired value to a string, rather than the attribute of obj itself

msg = ['Updating Attributes simple way:']
updateAttributesSimple(objA, dictA, msg)
print '\n\t'.join(msg)

#reset data
objA = someClass('Test1','1.1')
dictA = {'name':'Test1','revision':'1.2'}

msg = ['Updating Attributes clever way:']
updateAttributesClever(objB, dictB, msg)
print '\n\t'.join(msg)

The idea being that this way, whenever I need to add another attribute, I can just update the list of attributes being inspected and the rest of the code is already written.  What's the Pythonic way to accomplish this?

Body:
This should work for your:

class X(object):
    def __init__(self):
        self.a = 1
        self.b = 2

x = X()

d = dict()
d['a'] = 1
d['b'] = 3

def updateAttributes(obj,dic):
    def update(name):
        val = dic[name]
        if getattr(obj,name)==val:
            print name,"was equal"
        else:
            print "setting %s to %s" % (name,val)
            setattr(obj,name,val)

    for name in ['a','b']:
        update(name)

updateAttributes(x,d)
print x.a
print x.b


问:
Which JRE am I really using?
I try to set environment variables JAVA_HOME and JRE_HOME.

JAVA_HOME worked through typing -java version in cmd but I have trouble to
find a solution for JRE_HOME.

```<code>javac version
</code>```

doesn't work

```<code>java-XshowSettings:properties -version
</code>```

doesn't work either

答: When updating environment variables in windows make sure to open a new terminal session. The old terminal session will not have the updates.</p>

Title: Which JRE am I really using?

Body:
I try to set environment variables JAVA_HOME and JRE_HOME.

JAVA_HOME worked through typing -java version in cmd but I have trouble to
find a solution for JRE_HOME.

javac version

doesn't work

java-XshowSettings:properties -version

doesn't work either


问:
How to destroy a frame by clicking on a button?
I want to destroy the frame by clicking on a button. I searched everywhere and it seems that I'm doing this right. but it is not working.

```<code>public class LoginWindow {

    public void CreateLoginWindow () {

        /** Set Style to Main Frame **/
        JFrame main_window = new JFrame();
        main_window.setUndecorated(true);
        main_window.setLocationRelativeTo(null);
        main_window.setLayout(new BorderLayout());
        main_window.setLayout(new FlowLayout());
        main_window.setVisible(false);
        main_window.setContentPane(new JLabel(new ImageIcon("images/MainWindow-bg.jpg")));
        main_window.setExtendedState(JFrame.MAXIMIZED_BOTH);
        main_window.setSize(1920,1080);
        main_window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        /** Some Codes **/

        JButton login_button = new JButton("Click to Exit");
        login_button.setBounds(920,480,120,45);

        /** Login Button Action **/
        login_button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            ValidateLogin validateLogin = new ValidateLogin();
            Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText());
            main_window.dispose();
            }
        });

        main_window.add(login_button);
        main_window.setVisible(true);

    }

}
</code>```

It seems ValidateLogin validateLogin = new ValidateLogin(); Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText()); make some problems.

And this is my ValidateLogin Class :

```<code>public class ValidateLogin {

    public Boolean ValidateLoginAction (String username, String password){

        ConnectToDB validate_login = new ConnectToDB();
        String right_password = validate_login.GetPassOfAnUsername(username);
        if ( right_password.equals(password) ){
            return true;
        } else {
            return false;
        }

    }

}
</code>```

And this is my ConnectToDB Class :

```<code>public class ConnectToDB {

    /** Connect to Database **/
    private Connection connect() {

        String url = "jdbc:sqlite:E://Resturant Project/db/Resturant.db";
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return connection;
    }

    /** Get Password of an Username **/
    public String GetPassOfAnUsername(String username){

        String password = "SELECT Password FROM Person WHERE UserName = '" + username +"'";

        try (Connection connection = this.connect();
             PreparedStatement statement= connection.prepareStatement(password);
             ResultSet results = statement.executeQuery()) {

            return results.getString("Password");

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

        return null;
    }

}
</code>```

And this is my MainWindow Class :

```<code>public class MainWindow {

    public static void main(String[] args) {
        LoginWindow loginWindow = new LoginWindow();
        loginWindow.CreateLoginWindow();
    }

}
</code>```

答:
Have the username_field and password_field variables been instantiated somewhere? Perhaps the line where you are accessing the getText() method is throwing a NullPointerException when the actionPerformed method is being called and so the program never reaches the main_window.dispose() line.

Try checking if both of those variables are null when the actionPerformed method is being executed before you try to access the getText() method from them.

On a further note, check if the connection the database is being established successfully.

```<code>ConnectToDB validate_login = new ConnectToDB();
String right_password = validate_login.GetPassOfAnUsername(username);
</code>```

The second line might also throw a NullPointerException in case validate_login is null because your code will return null from your ConnectToDB() constructor in case the connection fails.

Body:
I want to destroy the frame by clicking on a button. I searched everywhere and it seems that I'm doing this right. but it is not working.

public class LoginWindow {

    public void CreateLoginWindow () {

        /** Set Style to Main Frame **/
        JFrame main_window = new JFrame();
        main_window.setUndecorated(true);
        main_window.setLocationRelativeTo(null);
        main_window.setLayout(new BorderLayout());
        main_window.setLayout(new FlowLayout());
        main_window.setVisible(false);
        main_window.setContentPane(new JLabel(new ImageIcon("images/MainWindow-bg.jpg")));
        main_window.setExtendedState(JFrame.MAXIMIZED_BOTH);
        main_window.setSize(1920,1080);
        main_window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        /** Some Codes **/

        JButton login_button = new JButton("Click to Exit");
        login_button.setBounds(920,480,120,45);

        /** Login Button Action **/
        login_button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            ValidateLogin validateLogin = new ValidateLogin();
            Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText());
            main_window.dispose();
            }
        });

        main_window.add(login_button);
        main_window.setVisible(true);

    }

}

It seems ValidateLogin validateLogin = new ValidateLogin(); Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText()); make some problems.

And this is my ValidateLogin Class :

public class ValidateLogin {

    public Boolean ValidateLoginAction (String username, String password){

        ConnectToDB validate_login = new ConnectToDB();
        String right_password = validate_login.GetPassOfAnUsername(username);
        if ( right_password.equals(password) ){
            return true;
        } else {
            return false;
        }

    }

}

And this is my ConnectToDB Class :

public class ConnectToDB {

    /** Connect to Database **/
    private Connection connect() {

        String url = "jdbc:sqlite:E://Resturant Project/db/Resturant.db";
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return connection;
    }

    /** Get Password of an Username **/
    public String GetPassOfAnUsername(String username){

        String password = "SELECT Password FROM Person WHERE UserName = '" + username +"'";

        try (Connection connection = this.connect();
             PreparedStatement statement= connection.prepareStatement(password);
             ResultSet results = statement.executeQuery()) {

            return results.getString("Password");

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

        return null;
    }

}

And this is my MainWindow Class :

public class MainWindow {

    public static void main(String[] args) {
        LoginWindow loginWindow = new LoginWindow();
        loginWindow.CreateLoginWindow();
    }

}

Body:
Have the username_field and password_field variables been instantiated somewhere? Perhaps the line where you are accessing the getText() method is throwing a NullPointerException when the actionPerformed method is being called and so the program never reaches the main_window.dispose() line.

Try checking if both of those variables are null when the actionPerformed method is being executed before you try to access the getText() method from them.

On a further note, check if the connection the database is being established successfully.

ConnectToDB validate_login = new ConnectToDB();
String right_password = validate_login.GetPassOfAnUsername(username);

The second line might also throw a NullPointerException in case validate_login is null because your code will return null from your ConnectToDB() constructor in case the connection fails.


问:
parseInt() - String to Integer and back in PHP
Im trying to reverse engineering some Javascript code and recode it in PHP.
There is a String which is "converted" with parseInt(String, 36) to an Integer.
I need a posibility to convert the integer back to the secret String in PHP, without knowing the secret string.

secretCode = "0vo8fz4kvy03";
decode = parseInt(secretCode, 36).toString();
console.log(decode); //= 115802171408044510```
</div>
</div>
</p>

<p>How i can do that in PHP?
<code>115802171408044510</code> back to <code>0vo8fz4kvy03</code></p>

<p>This interger contains some informations:</p>

```decode="115802171408044510";
storeID = decode.substr(0, 4); // 1158
posID = decode.substr(12, 2); // 04
orderID = decode.substr(14, 2); // 45
day = decode.substr(6, 2); // 17
month = decode.substr(4, 2); // 02
hour = decode.substr(8, 2); // 14
minutes = decode.substr(10, 2); // 08
```

I would like to edit this values above and convert this back to a "secretCode" String.
They are doing exactly this somehow server-side.

答:
To convert your javascript encoded number string from base 10 to base 36:

$decode = "115802171408044510";
echo base_convert ( $decode , 10 , 36 );
```

Body:
Im trying to reverse engineering some Javascript code and recode it in PHP.
There is a String which is "converted" with parseInt(String, 36) to an Integer.
I need a posibility to convert the integer back to the secret String in PHP, without knowing the secret string.

secretCode = "0vo8fz4kvy03";
decode = parseInt(secretCode, 36).toString();
console.log(decode); //= 115802171408044510

How i can do that in PHP?
115802171408044510 back to 0vo8fz4kvy03

This interger contains some informations:

decode="115802171408044510";
storeID = decode.substr(0, 4); // 1158
posID = decode.substr(12, 2); // 04
orderID = decode.substr(14, 2); // 45
day = decode.substr(6, 2); // 17
month = decode.substr(4, 2); // 02
hour = decode.substr(8, 2); // 14
minutes = decode.substr(10, 2); // 08

I would like to edit this values above and convert this back to a "secretCode" String.
They are doing exactly this somehow server-side.


问:
Issues importing mlxtend python
I'm new to python, so apologies if this is a silly question.

I'm trying to use mlxtend, and have installed it using pip. Pip confirms that it is installed (when I type "pip install mlxtend" it notes that the requirement is already satisfied). However, when I try and import mlxtend in python using "import mlxtend as ml", I get the error: "ModuleNotFoundError: No module named 'mlxtend'". I used the same process for installing and importing pandas and numpy, and they both worked. Any advice?

I should note that I have resorted to dropping in the specific code I need from mlxtend (apriori and association rules), which is working, but hardly a good long term strategy!

I'm using python version 3.6.5.

Thanks!

答:
I have the same issue when I use this library with python 3.7 but it is working for python 2.7 and I don't know why!.

My workaround is to download the source code and import each file you need that way.

Title: Issues importing mlxtend python