问:
HTML and CSS..adding divs side by side n times
I need to build a HTML/CSS layout with the following layout

|Static Div|Content Div0|Content Div1|...|Content DivN|Static Div|

a scaled down version of my code is like follows:

```<code><div id="container">
  <div id="static_div_1"></div>
    <div id="content">
      <div id="item1"></div>
      <div id="item2"></div>
       ....
      <div id="itemN"></div>
    </div>
  <div id="static_div_2"></div>
</div>
</code>```

Requirements:

All DIVs need to be stacked next to
each other.

I will need to add DIV's in the content DIV dynamically using javascript

The static DIV's need to maintain their position at the beginning and end of the content.

Content DIV should scroll horizontaly

I am struggling with the following issues:

After a point the content div starts wrapping the inserted DIV and another row of DIVs start to be rendered.

Edit: Its not something tabular in nature like plain data. Assume each div is like a form in itself. Something looking like a W2. I just need scrolling in the content DIV. To make the matters worse I am not really a GUI guy.. :(

Any help will be greatly appreciated.

答:
The CSS code you need is this:

```<code>#static_div_1, #static_div_2 {
    float: left;
    width: 200px;
  }
  #content {
    float: left;
    overflow-x: scroll;
    white-space: nowrap;
    width: 600px;
  }
  #content .item {
    display: inline-block;
    *display: inline;  /* Target IE6/7 only */
    width: 150px;
    zoom: 1;
  }
</code>```

Note I have added a class "item" to each of the items inside the #content div to style them. The keys in this layout are:

Make "float: left" the three parts, #static_div_1, #static_div_2 and the #content divs (and optionally set a fixed width to them).

The "overflow-x: scroll" style on the #content div.

The "white-space: nowrap" to the #content div.

Set "display: inline-block" to each item inside the #content div.

You'll notice there is a space between each of the items. This is the newline space, so to avoid it, there must be no newline or space between those item divs.

I hope this results helpful to you.
Best regards.

UPDATE: It now works on IE6/7. For correct setting of "display: inline-block" on these browsers notice the addition of the lines:

```<code>...
#content .item {
    ...
    *display: inline;  /* Target IE6/7 only */
    ...
    zoom: 1;
  }
</code>```

Body:
I need to build a HTML/CSS layout with the following layout

|Static Div|Content Div0|Content Div1|...|Content DivN|Static Div|

a scaled down version of my code is like follows:

       ....

Requirements:

All DIVs need to be stacked next to
each other.

I will need to add DIV's in the content DIV dynamically using javascript

The static DIV's need to maintain their position at the beginning and end of the content.

Content DIV should scroll horizontaly

I am struggling with the following issues:

After a point the content div starts wrapping the inserted DIV and another row of DIVs start to be rendered.

Edit: Its not something tabular in nature like plain data. Assume each div is like a form in itself. Something looking like a W2. I just need scrolling in the content DIV. To make the matters worse I am not really a GUI guy.. :(

Any help will be greatly appreciated.

Body:
The CSS code you need is this:

#static_div_1, #static_div_2 {
    float: left;
    width: 200px;
  }
  #content {
    float: left;
    overflow-x: scroll;
    white-space: nowrap;
    width: 600px;
  }
  #content .item {
    display: inline-block;
    *display: inline;  /* Target IE6/7 only */
    width: 150px;
    zoom: 1;
  }

Note I have added a class "item" to each of the items inside the #content div to style them. The keys in this layout are:

Make "float: left" the three parts, #static_div_1, #static_div_2 and the #content divs (and optionally set a fixed width to them).

The "overflow-x: scroll" style on the #content div.

The "white-space: nowrap" to the #content div.

Set "display: inline-block" to each item inside the #content div.

You'll notice there is a space between each of the items. This is the newline space, so to avoid it, there must be no newline or space between those item divs.

I hope this results helpful to you.
Best regards.

UPDATE: It now works on IE6/7. For correct setting of "display: inline-block" on these browsers notice the addition of the lines:

...
#content .item {
    ...
    *display: inline;  /* Target IE6/7 only */
    ...
    zoom: 1;
  }


来源: stackexchange

问:
NullPointerException in Kotlin
When I write this code in kotlin activity

```<code>var tv: TextView = findViewById(R.id.tv_kotlin) as TextView
</code>```

It always crashes with the following error:

```<code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
</code>```

And I find when I convert my Java codes to kotlin codes,the auto converter always does like this:

```<code>private var btn: Button? = null
</code>```

And when I use the reference, I have to put a !! behind it which make the codes really ugly.So what is the correct way binding UI in kotlin android?

The completed code:

```<code>class JavaToKotlinActivity : AppCompatActivity() {

    private var tv: TextView = findViewById(R.id.tv) as TextView
    private var btn: Button? = null
    private var et: EditText? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_java_to_kotlin)
        initView()
    }

    private fun initView() {
        btn = findViewById(R.id.btn) as Button
        et = findViewById(R.id.et) as EditText
        btn!!.setOnClickListener { tv.text = "haha" }
        et!!.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable) {

            }
        })
    }
}
</code>```

And the error messages :

```<code>06-09 14:25:38.574 9770-9770/com.mimi E/AndroidRuntime: FATAL EXCEPTION: main
                                                        Process: com.mimi, PID: 9770
                                                        java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.mimi/com.mimi.Views.JavaToKotlinActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2488)
                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2643)
                                                            at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1480)
                                                            at android.os.Handler.dispatchMessage(Handler.java:111)
                                                            at android.os.Looper.loop(Looper.java:207)
                                                            at android.app.ActivityThread.main(ActivityThread.java:5799)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
                                                         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                                                            at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:116)
                                                            at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:147)
                                                            at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:27)
                                                            at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:50)
                                                            at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:29)
                                                            at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:199)
                                                            at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:181)
                                                            at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:521)
                                                            at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
                                                            at com.mimi.Views.JavaToKotlinActivity.<init>(JavaToKotlinActivity.kt:20)
                                                            at java.lang.Class.newInstance(Native Method)
                                                            at android.app.Instrumentation.newActivity(Instrumentation.java:1072)
                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2478)
                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2643)
                                                            at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1480)
                                                            at android.os.Handler.dispatchMessage(Handler.java:111)
                                                            at android.os.Looper.loop(Looper.java:207)
                                                            at android.app.ActivityThread.main(ActivityThread.java:5799)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
</code>```

答:
Remove the top TextView from your code,

private var tv: TextView = findViewById(R.id.tv) as TextView

and do should do like this.

```<code>class JavaToKotlinActivity : AppCompatActivity() {

    private var tv: TextView? = null
    private var btn: Button? = null
    private var et: EditText? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_java_to_kotlin)
        initView()
    }

    private fun initView() {
        btn = findViewById(R.id.btn) as Button
        et = findViewById(R.id.et) as EditText
        tv = findViewById(R.id.tv) as TextView

        btn?.setOnClickListener{
            tv?.text = "haha"
        }

        et?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable) {

            }
        })
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: NullPointerException in Kotlin

Body:
When I write this code in kotlin activity

var tv: TextView = findViewById(R.id.tv_kotlin) as TextView

It always crashes with the following error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference

And I find when I convert my Java codes to kotlin codes,the auto converter always does like this:

private var btn: Button? = null

And when I use the reference, I have to put a !! behind it which make the codes really ugly.So what is the correct way binding UI in kotlin android?

The completed code:

class JavaToKotlinActivity : AppCompatActivity() {

    private var tv: TextView = findViewById(R.id.tv) as TextView
    private var btn: Button? = null
    private var et: EditText? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_java_to_kotlin)
        initView()
    }

    private fun initView() {
        btn = findViewById(R.id.btn) as Button
        et = findViewById(R.id.et) as EditText
        btn!!.setOnClickListener { tv.text = "haha" }
        et!!.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable) {

            }
        })
    }
}

And the error messages :

06-09 14:25:38.574 9770-9770/com.mimi E/AndroidRuntime: FATAL EXCEPTION: main
                                                        Process: com.mimi, PID: 9770
                                                        java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.mimi/com.mimi.Views.JavaToKotlinActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2488)
                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2643)
                                                            at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1480)
                                                            at android.os.Handler.dispatchMessage(Handler.java:111)
                                                            at android.os.Looper.loop(Looper.java:207)
                                                            at android.app.ActivityThread.main(ActivityThread.java:5799)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
                                                         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                                                            at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:116)
                                                            at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:147)
                                                            at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:27)
                                                            at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:50)
                                                            at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:29)
                                                            at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:199)
                                                            at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:181)
                                                            at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:521)
                                                            at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
                                                            at com.mimi.Views.JavaToKotlinActivity.<init>(JavaToKotlinActivity.kt:20)
                                                            at java.lang.Class.newInstance(Native Method)
                                                            at android.app.Instrumentation.newActivity(Instrumentation.java:1072)
                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2478)
                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2643)
                                                            at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1480)
                                                            at android.os.Handler.dispatchMessage(Handler.java:111)
                                                            at android.os.Looper.loop(Looper.java:207)
                                                            at android.app.ActivityThread.main(ActivityThread.java:5799)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)

Body:
Remove the top TextView from your code,

private var tv: TextView = findViewById(R.id.tv) as TextView

and do should do like this.

class JavaToKotlinActivity : AppCompatActivity() {

    private var tv: TextView? = null
    private var btn: Button? = null
    private var et: EditText? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_java_to_kotlin)
        initView()
    }

    private fun initView() {
        btn = findViewById(R.id.btn) as Button
        et = findViewById(R.id.et) as EditText
        tv = findViewById(R.id.tv) as TextView

        btn?.setOnClickListener{
            tv?.text = "haha"
        }

        et?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable) {

            }
        })
    }
}


问:
In Eiffel, what is the difference between entities, variables, fields and arguments?
I've seen the terms entity, variable, and argument used to describe things about Eiffel, that look quite similar to me, and I wanted to understand what is the intention behind using either term instead of the other.

Arguments — Some routines require some data in order to run. Imagine a fictitious feature foo (x, y: INTEGER; z: BOOLEAN). This routine takes 3 arguments: x, y, and z. When you call the routine, you must give it three valid arguments, for instance foo(6, 92, False). These values we passed to the routine are called actual arguments, while the placeholders defined in the definition are called formal arguments.

I've read of object fields, which specify the place inside the object structure where values are stored (either references or expanded objects).

I think the only time I saw the term variables was for local variables, inside features.

And entity seems to be a generic term for denoting a data-container with a name, so local variables, arguments, and querys (features that return some data) are all examples of entities.

And in what category would Current and Result fall? Local variables?

Could someone help me with the terminology?

答:
Specification

According to ISO/IEC 25436:2006(E) and newly added language constructs:

Syntax-based terms

Local variable is any of the following:

an identifier declared in a Local_declarations part (of a feature body, including inline agents)

predefined entity Result

Formal argument:

an identifier to represent information passed by callers

Actual argument:

an expression in a particular call to the routine

Variable attribute is a feature declaration satisfying all of the following:

there are no formal arguments

there is a query mark (i.e. it has a type)

there is no explicit value (i.e. it is not a constant)

if there is a body, it is of Attribute kind

Constant attribute is a feature declaration satisfying all of the following:

there are no formal arguments

there is a query mark (i.e. it has a type)

there is an explicit value

Collective terms

Variable is any of the following:

a final name of a variable attribute

local variable (including Result)

Read-only entity is any of the following:

formal argument

object test local

cursor local (in Iteration_part of a loop)

separate local (in Separate_instruction)

constant attribute

Current

Entity is any of the following:

variable

read-only entity

Query is any of the following:

attribute

function

I.e. a query is a feature that has a type and can be used to get a value at run-time.

Semantics terms

Field:

a value in a direct instance of a non-basic type, corresponding to an attribute

Example

```<code>class C feature
   pi: REAL_32 = 3.14
   double (x: LIST [INTEGER]): LIST [INTEGER]
      local
         r: ARRAYED_LIST [INTEGER]
      do
         create r.make (x.count)
         across x as c loop
            r.extend (c.item * 2)
         end
         Result := r
      end
   average_age: NATURAL
   count: NATURAL
   print_list (x: LIST [PERSON])
      do
         average_age := 0
         count := 0
         x.do_all (agent (p: PERSON)
            do
               if attached p.name as n then
                  io.put_string (n + ": " + p.age.out + "%N")
                  average_age := average_age + p.age
                  count := count + 1
               end
            end)
          if count > 0 then
             average_age := average_age // count
          end
      end
end
</code>```

Syntax-based terms

Local variable: r, Result.

Object test local: n.

Cursor local: c.

Formal argument: x, p.

Actual argument: x.count, 2 (this is an argument for multiplication), c.item * 2, ": " (in string concatenation), p.age.out, "%N", n + ": " + p.age.out + "%N", p.age, 1, 0, count (in division).

Variable attribute: average_age, count.

Constant attribute: pi.

Collective terms

Variable: r, Result, average_age, count.

Read-only entity: pi, n, c, x, p.

Entity: pi, r, Result, average_age, count, n, c, x, p.

Query: pi, double, average_age, count.

Body:
Specification

According to ISO/IEC 25436:2006(E) and newly added language constructs:

Syntax-based terms

Local variable is any of the following:

an identifier declared in a Local_declarations part (of a feature body, including inline agents)

predefined entity Result

Formal argument:

an identifier to represent information passed by callers

Actual argument:

an expression in a particular call to the routine

Variable attribute is a feature declaration satisfying all of the following:

there are no formal arguments

there is a query mark (i.e. it has a type)

there is no explicit value (i.e. it is not a constant)

if there is a body, it is of Attribute kind

Constant attribute is a feature declaration satisfying all of the following:

there are no formal arguments

there is a query mark (i.e. it has a type)

there is an explicit value

Collective terms

Variable is any of the following:

a final name of a variable attribute

local variable (including Result)

Read-only entity is any of the following:

formal argument

object test local

cursor local (in Iteration_part of a loop)

separate local (in Separate_instruction)

constant attribute

Current

Entity is any of the following:

variable

read-only entity

Query is any of the following:

attribute

function

I.e. a query is a feature that has a type and can be used to get a value at run-time.

Semantics terms

Field:

a value in a direct instance of a non-basic type, corresponding to an attribute

Example

class C feature
   pi: REAL_32 = 3.14
   double (x: LIST [INTEGER]): LIST [INTEGER]
      local
         r: ARRAYED_LIST [INTEGER]
      do
         create r.make (x.count)
         across x as c loop
            r.extend (c.item * 2)
         end
         Result := r
      end
   average_age: NATURAL
   count: NATURAL
   print_list (x: LIST [PERSON])
      do
         average_age := 0
         count := 0
         x.do_all (agent (p: PERSON)
            do
               if attached p.name as n then
                  io.put_string (n + ": " + p.age.out + "%N")
                  average_age := average_age + p.age
                  count := count + 1
               end
            end)
          if count > 0 then
             average_age := average_age // count
          end
      end
end

Syntax-based terms

Local variable: r, Result.

Object test local: n.

Cursor local: c.

Formal argument: x, p.

Actual argument: x.count, 2 (this is an argument for multiplication), c.item * 2, ": " (in string concatenation), p.age.out, "%N", n + ": " + p.age.out + "%N", p.age, 1, 0, count (in division).

Variable attribute: average_age, count.

Constant attribute: pi.

Collective terms

Variable: r, Result, average_age, count.

Read-only entity: pi, n, c, x, p.

Entity: pi, r, Result, average_age, count, n, c, x, p.

Query: pi, double, average_age, count.


问:
navigator is deprecated and has been removed from this package (expo)
since the last update my expo project always generates the error: navigator is deprecated and has been removed from this package. It can now be installed and imported from 'react-native-deprecated-custom-components' instead of 'react-native'. Learn about alternative navigation solutions at [...].
enter image description here
But when i try to import it from the new package i get the error: the development server returned response errror code: 500 [...].
enter image description here

I work with expo and the following code. The error however accurs in every new project i want to create with expo. Old project still work. When i copy the old code in my new projects i got the same error as.
I think that the code is functional and the problem is in the package manager for example.

import Expo from 'expo';
import React from 'react';
import {Navigator} from 'react-native-deprecated-custom-components';
import {Text, View, /*Navigator*/} from 'react-native';

class App extends React.Component {

   constructor(){
    super()

   // this.renderScene = this.renderScene.bind(this) /* bindet die funktion renderScene an das aktuelle this objekt*/
   }

   renderScene(route, navigator){
    if(route.name === 'WelcomePage'){
     return <WelcomePage navigator={navigator}/>
    }
    else if(route.name === 'PlayerSelect'){
        return <PlayerSelect navigator={navigator}/>
    }
   }

    render() {
      return (
        <View>
        <Navigator
          initialRoute={{name: 'WelcomePage'}}
          renderScene={this.renderScene}
          />

          <Text> Hallo</Text>
         </View>
      );
    }
    }

Expo.registerRootComponent(App);```

What i have to do to make my code work again?
Thanks in advance,

Maffinius

答:
I got a link which solve my same error so i guess here will work too.
http://www.hongming.me/?p=670</p>

Body:
since the last update my expo project always generates the error: navigator is deprecated and has been removed from this package. It can now be installed and imported from 'react-native-deprecated-custom-components' instead of 'react-native'. Learn about alternative navigation solutions at [...].
enter image description here
But when i try to import it from the new package i get the error: the development server returned response errror code: 500 [...].
enter image description here

I work with expo and the following code. The error however accurs in every new project i want to create with expo. Old project still work. When i copy the old code in my new projects i got the same error as.
I think that the code is functional and the problem is in the package manager for example.

import Expo from 'expo';
import React from 'react';
import {Navigator} from 'react-native-deprecated-custom-components';
import {Text, View, /*Navigator*/} from 'react-native';

class App extends React.Component {

   constructor(){
    super()

   // this.renderScene = this.renderScene.bind(this) /* bindet die funktion renderScene an das aktuelle this objekt*/
   }

   renderScene(route, navigator){
    if(route.name === 'WelcomePage'){
     return <WelcomePage navigator={navigator}/>
    }
    else if(route.name === 'PlayerSelect'){
        return <PlayerSelect navigator={navigator}/>
    }
   }

    render() {
      return (
        <View>
        <Navigator
          initialRoute={{name: 'WelcomePage'}}
          renderScene={this.renderScene}
          />

          <Text> Hallo</Text>
         </View>
      );
    }
    }

Expo.registerRootComponent(App);

What i have to do to make my code work again?
Thanks in advance,

Maffinius


问:
How to replace string with another string and keep case in php and mysql?
I'm trying to do some sort of translator which would be able to keep text uppercase/lowercase.
I need to replace it in PHP string and MySQL query too.

Example:

```<code>Potato is jumping all over the PLACE.
Potato is jumping all over the pLAcE. (optional)
Potato is jumping all over the place.
Potato is jumping all over the Place.
</code>```

I want to replace word 'place' with 'garden'.

```<code>Potato is jumping all over the GARDEN.
Potato is jumping all over the gARdEe. (optional)
Potato is jumping all over the garden.
Potato is jumping all over the Garden.
</code>```

It should also work with phrases.

答:
```<code>function stringReplace($findStr, $replaceStr, $str)
{
    $isLowerStr = true;
    for($i=0; $i<strlen($findStr); $i++){
        if(ord($findStr[$i]) >= 97 && ord($findStr[$i])<=122){
            if(ord($replaceStr[$i]) >= 65 && ord($replaceStr[$i])<=96){
                $replaceStr[$i] = strtolower($replaceStr[$i]);
            }else{
                $replaceStr[$i] = $replaceStr[$i];
            }
        }else{
            $isLowerStr = false;
            $replaceStr[$i] = strtoupper($replaceStr[$i]);
        }
    }
    if($isLowerStr == false){
        if(strlen($replaceStr) > strlen($findStr)){
            for($i=0;$i<(strlen($replaceStr)-strlen($findStr));$i++){
                if(strtoupper($findStr) == $findStr){
                        $replaceStr[strlen($findStr)+$i] = strtoupper($replaceStr[strlen($findStr)+$i]);
                }else{
                    $replaceStr[strlen($findStr)+$i] = strtolower($replaceStr[strlen($findStr)+$i]);
                }
            }
        }
    }
    echo str_replace($findStr, $replaceStr, $str);die;
}
$findStr = 'Place';
$replaceStr = 'garden';
echo stringReplace($findStr, $replaceStr, 'Potato is jumping all over the '.$findStr.'.');
</code>```

Body:
I'm trying to do some sort of translator which would be able to keep text uppercase/lowercase.
I need to replace it in PHP string and MySQL query too.

Example:

Potato is jumping all over the PLACE.
Potato is jumping all over the pLAcE. (optional)
Potato is jumping all over the place.
Potato is jumping all over the Place.

I want to replace word 'place' with 'garden'.

Potato is jumping all over the GARDEN.
Potato is jumping all over the gARdEe. (optional)
Potato is jumping all over the garden.
Potato is jumping all over the Garden.

It should also work with phrases.


问:
how to format mysql float into sytem local values or decimal comma for a reportlab billing system
I have a Reportlab form for a billing system and it works good. But what I want to get are the values in sytem local values, with decimal comma, or separator; something as next instead as shown in the picture:

```<code>1,350,000.00
</code>```

I'd like something like FORMAT in MySQL, but the problem with this one is that it does'nt let me to sum the values to get the total because it returns the values as string.

SELECT FORMAT (columna, 'es_CO') FROM tabla;

How my form looks like

And my Python code:

Just retefuente, ivajuridico, rteiva and i_vlrenta are float in mysql

```<code>#!/usr/bin/python
#-*- coding:utf-8 -*-
from Tkinter import*
from tkMessageBox import*
import MySQLdb
from controller import *
import analisis_arrendatarios
import os
import datetime
import time
import locale
locale.setlocale(locale.LC_ALL, "")
#LIBRERÍA PLATYPUS DE REPORTLAB PARA CREAR TABLAS
from reportlab.platypus import (SimpleDocTemplate, PageBreak, Image, Spacer,
Paragraph, Table, TableStyle)
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.pagesizes import letter
from reportlab.lib import colors
styleSheet = getSampleStyleSheet()
style = styleSheet['BodyText']

class Proceso_Fact_Auto_Arre(Frame):
        def __init__(self, parent, controller):
                Frame.__init__(self, parent)

        global opt

        #VARIABLES
        opt = IntVar()

        #WIDGETS
        header = Label(self, text="TENANTS AUTO BILLING PROCESS", font="bold")
        header.pack(pady=20, side=TOP)

        wrapper = Frame (self)
        wrapper.pack()

        r1 = Radiobutton(wrapper, text="Generate Analysis", variable=opt, value=0).pack(pady=5, anchor=W)
        r2 = Radiobutton(wrapper, text="Generate Billings", variable=opt, value=1).pack(pady=5, anchor=W)
        Button(wrapper, text="Iniciar Proceso", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=operacion).pack(pady=5, anchor=W)

def operacion():
    if opt.get()==0:
        showinfo('Operation', "Generate Analysis")
        try:
            connect.commit()
            #Consulta de códigos y valores de la tabla 'configuracion'
            cursor.execute("SELECT cod_canon, cod_subtotalarrend, cod_ivaarrend,
                      retefuente, ivajuridico, rteiva, resolucion
                    FROM configuracion;")
            dato1 = cursor.fetchall()
            #Consulta de datos generales del propietario y el arrendatario para la factura
            cursor.execute("SELECT p_cc, dueño, r_carpeta, relacionip.i_cod, i_dir, i_vlrenta, i_tel, contratos.a_cc, inquilino, a_tpersona, a_contribuyente
                  FROM contratos
                  INNER JOIN relacionip ON contratos.r_id = relacionip.r_id
                  INNER JOIN inmuebles ON relacionip.i_cod = inmuebles.i_cod
                  INNER JOIN arrendatarios ON contratos.a_cc = arrendatarios.a_cc;")
            #cursor.execute("SELECT p_cc, dueño, r_carpeta, relacionip.i_cod, i_dir, FORMAT(SUM(i_vlrenta), 2,'es'), i_tel, contratos.a_cc, inquilino, a_tpersona, a_contribuyente
                  #FROM contratos
                  #INNER JOIN relacionip ON contratos.r_id = relacionip.r_id
                  #INNER JOIN inmuebles ON relacionip.i_cod = inmuebles.i_cod
                  #INNER JOIN arrendatarios ON contratos.a_cc = arrendatarios.a_cc;")
            dato2 = cursor.fetchall()
        except:
            pass
        for c in dato1:
            canon = c[0]
            subtotal = c[1]
            iva = c[2]
            retef = c[3]
            ivajuridi = c[4]
            retei = c[5]
            resolucion = c[6]

        doc = SimpleDocTemplate("facturas/factura_auto_inquilino.pdf", pagesize = (595.27,400.00), rightMargin=5, leftMargin=5, topMargin=10, bottomMargin=0)
        story=[]

        for i in dato2:
            nit = i[0]
            prop = i[1]
            folder = i[2]
            inm = i[3]
            loc = i[4]
            renta = i[5]
            tel = i[6]
            cc = i[7]
            arrend = i[8]
            tipo = i[9]
            contri = i[10]
            #SI ARREND ES NATURAL(1)
            if tipo == 1:
                tipo = 0
            #SI ARREND ES JURÍDICO(2)
            if tipo == 2:
                tipo = renta*ivajuridi/100

            total = renta+tipo

            tiempo = datetime.date.today()
            anio = time.strftime("%Y")
            mes = time.strftime("%B")

        #-------------------------------------------- CABECERA DEL DOCUMENTO

            #VARIABLES
            logo = Image("img/logo.gif", width=150, height=45) #LOGO
            logo.hAlign ='LEFT' #Posicion de la img en la hoja

            info = Paragraph('''<para align=center leading=8><font size=6>CALLE 11A N°42-68 LOC,195 ED. EL DORADO<br/>TELEFONO: 3110513 FAX:2664154<br/>AFILIADO A FENALCO<br/>M.A.V.U N°000078</font></para>''', styleSheet["BodyText"])

            tipoDoc = Paragraph ('''<para align=right><b>FACTURA DE VENTA<br/>N°</b></para>''', styleSheet["BodyText"])

            #TABLA 1
            tabla1 = Table([[logo, info, tipoDoc]], colWidths=[200,150,140], rowHeights=None)
            tabla1.setStyle([
                ('VALIGN', (1,0), (2,0), 'TOP'),
                ('ALIGN', (2,0), (2,0), 'RIGHT')#ALINEAR A LA DER
                ])

            story.append(tabla1) #Construye la tabla 't' definida anteriormente
            story.append(Spacer(0,-10)) #Espacio del salto de línea con el siguiente Ejemplo

        #-------------------------------------------- DATOS GENERALES DEL DOCUMENTO

            #VARIABLES
            inquilino = Paragraph ('''<font size=6><b>Nombre Arrendatario:</b><br/></font>%s'''%arrend, styleSheet["BodyText"])
            docID = Paragraph ('''<font size=6><b>CC/Nit: </b></font>   %s''' %nit, styleSheet["BodyText"])
            locImn = Paragraph ('''<font size=6><b>Dirección Inmueble:</b><br/></font>%s'''%loc, styleSheet["BodyText"])
            telefono = Paragraph ('''<font size=6><b>Teléfono:</b><br/></font>%s'''%tel, styleSheet["BodyText"])
            IDpropietario = Paragraph ('''<font size=6><b>CC/Nit:</b><br/></font>%s'''%cc, styleSheet["BodyText"])
            propietario = Paragraph ('''<font size=6><b>Propietario: </b></font>%s'''%prop, styleSheet["BodyText"])
            fechaFormato = Paragraph ('''<para align=center fontSize=6>Día Mes Año</para>''', styleSheet["BodyText"])
            hoy = time.strftime("%d/%m/%Y")
            fecha = Paragraph ('''<para align=center spaceBefore=0>%s</para>''' %hoy, styleSheet["BodyText"])
            codigoImn = Paragraph ('''<font size=6><b>Código Inmueble:</b><br/></font>%s'''%inm, styleSheet["BodyText"])

            #TABLA 2
            datos = [[inquilino,'','','','',[fechaFormato,fecha]],
                    [docID,'','',propietario,'',''],
                    [locImn,'',telefono,IDpropietario,'',codigoImn]]

            tabla2 = Table(datos,
                           style=[('BOX',(0,0),(2,2),0.5,colors.black),
                                  ('VALIGN', (0,0),(2,0),'TOP'),
                                  ('SPAN',(0,0),(2,0)),#Combinar 3 filas (col0,row0) hasta (col2,row0) Arrendatario #0
                                  ('SPAN',(0,1),(2,1)),#Combinar 3 filas CC/Nit #1
                                  ('SPAN',(0,2),(1,2)),#Combinar 2 filas Dirección #2
                                  ('SPAN',(3,1),(5,1)),#Combinar 3 filas Nombre Propietario #
                                  ('SPAN',(3,2),(4,2)),#Combinar 2 filas CC/Nit Propietario #
                                  ('GRID',(3,1),(4,2),0.5,colors.black),
                                  ('GRID',(5,0),(5,2),0.5,colors.black)
                                 ],colWidths=[100,90,90,90,80,70], rowHeights=None)

            #Constructor y espaciado
            story.append(Spacer(0,15)) #Espacio del salto de línea con el siguiente Ejemplo
            story.append(tabla2) #Construye la tabla 't' definida anteriormente

        #-------------------------------------------- DETALLES DEL DOCUMENTO

            #VARIABLES
            desc = Paragraph('''<para align=center><b>DESCRIPCION</b></para>''', styleSheet["BodyText"])
            vlr = Paragraph('''<para align=center><b>VALOR</b></para>''', styleSheet["BodyText"])
            concepto = Paragraph('''Valor Arrendamiento Mes: %s/%s''' % (mes,anio), styleSheet["BodyText"])

            resol = "Resolucion Dian N°110000658514 de Diciembre de 2015 Consectivo Facturacion 33001 al 36000. P"

            #TABLA 3
            data=[[desc, '', vlr],      #0
                  [concepto, '', renta], #1
                  ['', '', ''],         #2
                  ['', '', ''],         #3
                  ['', '', ''],         #4
                  ['', '', ''],         #5
                  ['', '', ''],         #6
                  ['Observaciones', 'SUBTOTAL', renta], #7
                  ['', 'IVA', tipo], #8
                  [resolucion, 'TOTAL', total]] #9

            #Formato de la tabla
            tabla3 = Table(data,
                        style=[('GRID',(0,0),(2,0),0.5,colors.black),#Color regilla de DESCRIPCION & VALOR
                               ('BOX',(2,1),(2,9),0.5,colors.black), #Color & grosor de la tabla/marco externo de los VALORES
                               #('BACKGROUND',(0,0),(2,0), colors.pink), #Color de fondo de DESCRIPCION & VALOR #0
                               ('SPAN',(0,0),(1,0)), #Combinar filas DESCRIPCION #0
                               ('BOX',(0,1),(2,6),0.5,colors.black), #Color & grosor de la tabla o marco externo de los DETALLES
                               ('ALIGN', (2,1), (2,1), 'RIGHT'),#Centrar renta #1
                               ('ALIGN', (2,7), (2,7), 'RIGHT'),#Centrar renta #7
                               ('ALIGN', (2,8), (2,8), 'RIGHT'),#Centrar tipo #8
                               ('ALIGN', (2,9), (2,9), 'RIGHT'),#Centrar total #9
                               #('ALIGN', (2,9), (2,9), 'CENTER'),#Centrar total #9
                               ('SPAN',(0,1),(1,1)), #Combinar filas de Detalle #1
                               ('SPAN',(0,2),(1,2)), #Combinar filas de Detalle #2
                               ('SPAN',(0,3),(1,3)), #Combinar filas de Detalle #3
                               ('SPAN',(0,4),(1,4)), #Combinar filas de Detalle #4
                               ('SPAN',(0,5),(1,5)), #Combinar filas de Detalle #5
                               ('SPAN',(0,6),(1,6)), #Combinar filas de Detalle #6
                               ('GRID',(1,7),(2,9),0.5,colors.black),#Color regilla de SUBTOTAL, IVA, TOTAL
                               ('BOX',(0,7),(0,9),0.5,colors.black), #Color & grosor de la tabla o marco externo de los OBSERVACIONES Y RESOLUCION
                               ('FONTSIZE', (0,9),(0,9),7), #Tamaño de la Resolucion
                               #('BACKGROUND',(1,9),(1,9),colors.black),#Color de fondo de TOTAL
                               ('TEXTCOLOR',(1,9),(1,9),colors.black), #Color de letra de TOTAL
                               #('BACKGROUND',(2,9),(2,9),colors.grey)#Color de fondo de VALOR TOTAL
                              ],colWidths=[340,80,100], rowHeights=None)

            story.append(Spacer(0,15)) #Espacio del salto de línea con el siguiente Ejemplo
            story.append(tabla3) #Construye la tabla 't' definida anteriormente

        #-------------------------------------------- FIN PDF

        doc.build(story) #Constructor del documento

        if sys.platform == 'linux2':
            os.system("xdg-open ~/Project/facturas/factura_auto_inquilino.pdf")#DEBIAN
        elif sys.platform == 'linux2':
            os.system("/usr/bin/gnome-open facturas/factura_auto_inquilino.pdf")#UBUNTU
        else:
            os.startfile("Project/facturas/factura_auto_inquilino.pdf")#WINDOWS

    else:
        #Code to insert data into a billinf table)
</code>```

答:
As some guys suggested, what I had to do was: sum the values, which was already done in my code, add a new variable appling a format with 'locale.format', and then just place that variable in the corresponding place in the reportlab form. For the total value it was not necessary to create a new variable, but just apply locate.

So, I added to my code something like this:

```<code>for i in dato2:
            #...
            renta = i[5]
            #New var to show value with thousands separator in the form
            renta1 = locale.format("%d", renta, grouping=True)
            tipo = i[9]
            #SI ARREND ES NATURAL(1)
            if tipo == 1:
                tipo = 0
                #New var to show value with thousands separator in the form
                tipo1 = locale.format("%d", tipo, grouping=True)
            #SI ARREND ES JURÍDICO(2)
            if tipo == 2:
                tipo = renta*ivajuridi/100
                #New var to show value with thousands separator in the form
                tipo1 = locale.format("%d", tipo, grouping=True)

            total = locale.format("%d", renta+tipo, grouping=True)

            #REPORTLAB FORM TABLA 3
            data=[[desc, '', vlr],      #0
                  [concepto, '', renta], #1
                  ['', '', ''],         #2
                  ['', '', ''],         #3
                  ['', '', ''],         #4
                  ['', '', ''],         #5
                  ['', '', ''],         #6
                  ['Observaciones', 'SUBTOTAL', renta], #7
                  ['', 'IVA', tipo], #8
                  [resolucion, 'TOTAL', total]] #9
</code>```

Body:
I have a Reportlab form for a billing system and it works good. But what I want to get are the values in sytem local values, with decimal comma, or separator; something as next instead as shown in the picture:

1,350,000.00

I'd like something like FORMAT in MySQL, but the problem with this one is that it does'nt let me to sum the values to get the total because it returns the values as string.

SELECT FORMAT (columna, 'es_CO') FROM tabla;

How my form looks like

And my Python code:

Just retefuente, ivajuridico, rteiva and i_vlrenta are float in mysql

#!/usr/bin/python
#-*- coding:utf-8 -*-
from Tkinter import*
from tkMessageBox import*
import MySQLdb
from controller import *
import analisis_arrendatarios
import os
import datetime
import time
import locale
locale.setlocale(locale.LC_ALL, "")
#LIBRERÍA PLATYPUS DE REPORTLAB PARA CREAR TABLAS
from reportlab.platypus import (SimpleDocTemplate, PageBreak, Image, Spacer,
Paragraph, Table, TableStyle)
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.pagesizes import letter
from reportlab.lib import colors
styleSheet = getSampleStyleSheet()
style = styleSheet['BodyText']

class Proceso_Fact_Auto_Arre(Frame):
        def __init__(self, parent, controller):
                Frame.__init__(self, parent)

        global opt

        #VARIABLES
        opt = IntVar()

        #WIDGETS
        header = Label(self, text="TENANTS AUTO BILLING PROCESS", font="bold")
        header.pack(pady=20, side=TOP)

        wrapper = Frame (self)
        wrapper.pack()

        r1 = Radiobutton(wrapper, text="Generate Analysis", variable=opt, value=0).pack(pady=5, anchor=W)
        r2 = Radiobutton(wrapper, text="Generate Billings", variable=opt, value=1).pack(pady=5, anchor=W)
        Button(wrapper, text="Iniciar Proceso", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=operacion).pack(pady=5, anchor=W)

def operacion():
    if opt.get()==0:
        showinfo('Operation', "Generate Analysis")
        try:
            connect.commit()
            #Consulta de códigos y valores de la tabla 'configuracion'
            cursor.execute("SELECT cod_canon, cod_subtotalarrend, cod_ivaarrend,
                      retefuente, ivajuridico, rteiva, resolucion
                    FROM configuracion;")
            dato1 = cursor.fetchall()
            #Consulta de datos generales del propietario y el arrendatario para la factura
            cursor.execute("SELECT p_cc, dueño, r_carpeta, relacionip.i_cod, i_dir, i_vlrenta, i_tel, contratos.a_cc, inquilino, a_tpersona, a_contribuyente
                  FROM contratos
                  INNER JOIN relacionip ON contratos.r_id = relacionip.r_id
                  INNER JOIN inmuebles ON relacionip.i_cod = inmuebles.i_cod
                  INNER JOIN arrendatarios ON contratos.a_cc = arrendatarios.a_cc;")
            #cursor.execute("SELECT p_cc, dueño, r_carpeta, relacionip.i_cod, i_dir, FORMAT(SUM(i_vlrenta), 2,'es'), i_tel, contratos.a_cc, inquilino, a_tpersona, a_contribuyente
                  #FROM contratos
                  #INNER JOIN relacionip ON contratos.r_id = relacionip.r_id
                  #INNER JOIN inmuebles ON relacionip.i_cod = inmuebles.i_cod
                  #INNER JOIN arrendatarios ON contratos.a_cc = arrendatarios.a_cc;")
            dato2 = cursor.fetchall()
        except:
            pass
        for c in dato1:
            canon = c[0]
            subtotal = c[1]
            iva = c[2]
            retef = c[3]
            ivajuridi = c[4]
            retei = c[5]
            resolucion = c[6]

        doc = SimpleDocTemplate("facturas/factura_auto_inquilino.pdf", pagesize = (595.27,400.00), rightMargin=5, leftMargin=5, topMargin=10, bottomMargin=0)
        story=[]

        for i in dato2:
            nit = i[0]
            prop = i[1]
            folder = i[2]
            inm = i[3]
            loc = i[4]
            renta = i[5]
            tel = i[6]
            cc = i[7]
            arrend = i[8]
            tipo = i[9]
            contri = i[10]
            #SI ARREND ES NATURAL(1)
            if tipo == 1:
                tipo = 0
            #SI ARREND ES JURÍDICO(2)
            if tipo == 2:
                tipo = renta*ivajuridi/100

            total = renta+tipo

            tiempo = datetime.date.today()
            anio = time.strftime("%Y")
            mes = time.strftime("%B")

        #-------------------------------------------- CABECERA DEL DOCUMENTO

            #VARIABLES
            logo = Image("img/logo.gif", width=150, height=45) #LOGO
            logo.hAlign ='LEFT' #Posicion de la img en la hoja

            info = Paragraph('''<para align=center leading=8>CALLE 11A N°42-68 LOC,195 ED. EL DORADO
TELEFONO: 3110513 FAX:2664154
AFILIADO A FENALCO
M.A.V.U N°000078</para>''', styleSheet["BodyText"])

            tipoDoc = Paragraph ('''<para align=right>FACTURA DE VENTA
N°</para>''', styleSheet["BodyText"])

            #TABLA 1
            tabla1 = Table([[logo, info, tipoDoc]], colWidths=[200,150,140], rowHeights=None)
            tabla1.setStyle([
                ('VALIGN', (1,0), (2,0), 'TOP'),
                ('ALIGN', (2,0), (2,0), 'RIGHT')#ALINEAR A LA DER
                ])

            story.append(tabla1) #Construye la tabla 't' definida anteriormente
            story.append(Spacer(0,-10)) #Espacio del salto de línea con el siguiente Ejemplo

        #-------------------------------------------- DATOS GENERALES DEL DOCUMENTO

            #VARIABLES
            inquilino = Paragraph ('''Nombre Arrendatario:
%s'''%arrend, styleSheet["BodyText"])
            docID = Paragraph ('''CC/Nit:    %s''' %nit, styleSheet["BodyText"])
            locImn = Paragraph ('''Dirección Inmueble:
%s'''%loc, styleSheet["BodyText"])
            telefono = Paragraph ('''Teléfono:
%s'''%tel, styleSheet["BodyText"])
            IDpropietario = Paragraph ('''CC/Nit:
%s'''%cc, styleSheet["BodyText"])
            propietario = Paragraph ('''Propietario: %s'''%prop, styleSheet["BodyText"])
            fechaFormato = Paragraph ('''<para align=center fontSize=6>Día Mes Año</para>''', styleSheet["BodyText"])
            hoy = time.strftime("%d/%m/%Y")
            fecha = Paragraph ('''<para align=center spaceBefore=0>%s</para>''' %hoy, styleSheet["BodyText"])
            codigoImn = Paragraph ('''Código Inmueble:
%s'''%inm, styleSheet["BodyText"])

            #TABLA 2
            datos = [[inquilino,'','','','',[fechaFormato,fecha]],
                    [docID,'','',propietario,'',''],
                    [locImn,'',telefono,IDpropietario,'',codigoImn]]

            tabla2 = Table(datos,
                           style=[('BOX',(0,0),(2,2),0.5,colors.black),
                                  ('VALIGN', (0,0),(2,0),'TOP'),
                                  ('SPAN',(0,0),(2,0)),#Combinar 3 filas (col0,row0) hasta (col2,row0) Arrendatario #0
                                  ('SPAN',(0,1),(2,1)),#Combinar 3 filas CC/Nit #1
                                  ('SPAN',(0,2),(1,2)),#Combinar 2 filas Dirección #2
                                  ('SPAN',(3,1),(5,1)),#Combinar 3 filas Nombre Propietario #
                                  ('SPAN',(3,2),(4,2)),#Combinar 2 filas CC/Nit Propietario #
                                  ('GRID',(3,1),(4,2),0.5,colors.black),
                                  ('GRID',(5,0),(5,2),0.5,colors.black)
                                 ],colWidths=[100,90,90,90,80,70], rowHeights=None)

            #Constructor y espaciado
            story.append(Spacer(0,15)) #Espacio del salto de línea con el siguiente Ejemplo
            story.append(tabla2) #Construye la tabla 't' definida anteriormente

        #-------------------------------------------- DETALLES DEL DOCUMENTO

            #VARIABLES
            desc = Paragraph('''<para align=center>DESCRIPCION</para>''', styleSheet["BodyText"])
            vlr = Paragraph('''<para align=center>VALOR</para>''', styleSheet["BodyText"])
            concepto = Paragraph('''Valor Arrendamiento Mes: %s/%s''' % (mes,anio), styleSheet["BodyText"])

            resol = "Resolucion Dian N°110000658514 de Diciembre de 2015 Consectivo Facturacion 33001 al 36000. P"

            #TABLA 3
            data=[[desc, '', vlr],      #0
                  [concepto, '', renta], #1
                  ['', '', ''],         #2
                  ['', '', ''],         #3
                  ['', '', ''],         #4
                  ['', '', ''],         #5
                  ['', '', ''],         #6
                  ['Observaciones', 'SUBTOTAL', renta], #7
                  ['', 'IVA', tipo], #8
                  [resolucion, 'TOTAL', total]] #9

            #Formato de la tabla
            tabla3 = Table(data,
                        style=[('GRID',(0,0),(2,0),0.5,colors.black),#Color regilla de DESCRIPCION & VALOR
                               ('BOX',(2,1),(2,9),0.5,colors.black), #Color & grosor de la tabla/marco externo de los VALORES
                               #('BACKGROUND',(0,0),(2,0), colors.pink), #Color de fondo de DESCRIPCION & VALOR #0
                               ('SPAN',(0,0),(1,0)), #Combinar filas DESCRIPCION #0
                               ('BOX',(0,1),(2,6),0.5,colors.black), #Color & grosor de la tabla o marco externo de los DETALLES
                               ('ALIGN', (2,1), (2,1), 'RIGHT'),#Centrar renta #1
                               ('ALIGN', (2,7), (2,7), 'RIGHT'),#Centrar renta #7
                               ('ALIGN', (2,8), (2,8), 'RIGHT'),#Centrar tipo #8
                               ('ALIGN', (2,9), (2,9), 'RIGHT'),#Centrar total #9
                               #('ALIGN', (2,9), (2,9), 'CENTER'),#Centrar total #9
                               ('SPAN',(0,1),(1,1)), #Combinar filas de Detalle #1
                               ('SPAN',(0,2),(1,2)), #Combinar filas de Detalle #2
                               ('SPAN',(0,3),(1,3)), #Combinar filas de Detalle #3
                               ('SPAN',(0,4),(1,4)), #Combinar filas de Detalle #4
                               ('SPAN',(0,5),(1,5)), #Combinar filas de Detalle #5
                               ('SPAN',(0,6),(1,6)), #Combinar filas de Detalle #6
                               ('GRID',(1,7),(2,9),0.5,colors.black),#Color regilla de SUBTOTAL, IVA, TOTAL
                               ('BOX',(0,7),(0,9),0.5,colors.black), #Color & grosor de la tabla o marco externo de los OBSERVACIONES Y RESOLUCION
                               ('FONTSIZE', (0,9),(0,9),7), #Tamaño de la Resolucion
                               #('BACKGROUND',(1,9),(1,9),colors.black),#Color de fondo de TOTAL
                               ('TEXTCOLOR',(1,9),(1,9),colors.black), #Color de letra de TOTAL
                               #('BACKGROUND',(2,9),(2,9),colors.grey)#Color de fondo de VALOR TOTAL
                              ],colWidths=[340,80,100], rowHeights=None)

            story.append(Spacer(0,15)) #Espacio del salto de línea con el siguiente Ejemplo
            story.append(tabla3) #Construye la tabla 't' definida anteriormente

        #-------------------------------------------- FIN PDF

        doc.build(story) #Constructor del documento

        if sys.platform == 'linux2':
            os.system("xdg-open ~/Project/facturas/factura_auto_inquilino.pdf")#DEBIAN
        elif sys.platform == 'linux2':
            os.system("/usr/bin/gnome-open facturas/factura_auto_inquilino.pdf")#UBUNTU
        else:
            os.startfile("Project/facturas/factura_auto_inquilino.pdf")#WINDOWS

    else:
        #Code to insert data into a billinf table)

Body:
As some guys suggested, what I had to do was: sum the values, which was already done in my code, add a new variable appling a format with 'locale.format', and then just place that variable in the corresponding place in the reportlab form. For the total value it was not necessary to create a new variable, but just apply locate.

So, I added to my code something like this:

for i in dato2:
            #...
            renta = i[5]
            #New var to show value with thousands separator in the form
            renta1 = locale.format("%d", renta, grouping=True)
            tipo = i[9]
            #SI ARREND ES NATURAL(1)
            if tipo == 1:
                tipo = 0
                #New var to show value with thousands separator in the form
                tipo1 = locale.format("%d", tipo, grouping=True)
            #SI ARREND ES JURÍDICO(2)
            if tipo == 2:
                tipo = renta*ivajuridi/100
                #New var to show value with thousands separator in the form
                tipo1 = locale.format("%d", tipo, grouping=True)

            total = locale.format("%d", renta+tipo, grouping=True)

            #REPORTLAB FORM TABLA 3
            data=[[desc, '', vlr],      #0
                  [concepto, '', renta], #1
                  ['', '', ''],         #2
                  ['', '', ''],         #3
                  ['', '', ''],         #4
                  ['', '', ''],         #5
                  ['', '', ''],         #6
                  ['Observaciones', 'SUBTOTAL', renta], #7
                  ['', 'IVA', tipo], #8
                  [resolucion, 'TOTAL', total]] #9


问:
Creating URL query parameters from NSDictionary objects in ObjectiveC
With all the URL-handling objects lying around in the standard Cocoa libraries (NSURL, NSMutableURL, NSMutableURLRequest, etc), I know I must be overlooking an easy way to programmatically compose a GET request.

Currently I'm manually appending "?" followed by name value pairs joined by "&", but all of my name and value pairs need to be manually encoded so NSMutableURLRequest doesn't fail entirely when it tries to connect to the URL.

This feels like something I should be able to use a pre-baked API for.... is there anything out of the box to append an NSDictionary of query parameters to an NSURL? Is there another way I should approach this?

答:
Simple way of converting NSDictionary to url query string in Objective-c

Ex: first_name=Steve&middle_name=Gates&last_name=Jobs&address=Palo Alto, California

```<code>    NSDictionary *sampleDictionary = @{@"first_name"         : @"Steve",
                                     @"middle_name"          : @"Gates",
                                     @"last_name"            : @"Jobs",
                                     @"address"              : @"Palo Alto, California"};

    NSMutableString *resultString = [NSMutableString string];
            for (NSString* key in [sampleDictionary allKeys]){
                if ([resultString length]>0)
                    [resultString appendString:@"&"];
                [resultString appendFormat:@"%@=%@", key, [sampleDictionary objectForKey:key]];
            }
NSLog(@"QueryString: %@", resultString);
</code>```

Hope will help :)

ContentLicense: CC BY-SA 2.5

Body:
Simple way of converting NSDictionary to url query string in Objective-c

Ex: first_name=Steve&middle_name=Gates&last_name=Jobs&address=Palo Alto, California

    NSDictionary *sampleDictionary = @{@"first_name"         : @"Steve",
                                     @"middle_name"          : @"Gates",
                                     @"last_name"            : @"Jobs",
                                     @"address"              : @"Palo Alto, California"};

    NSMutableString *resultString = [NSMutableString string];
            for (NSString* key in [sampleDictionary allKeys]){
                if ([resultString length]>0)
                    [resultString appendString:@"&"];
                [resultString appendFormat:@"%@=%@", key, [sampleDictionary objectForKey:key]];
            }
NSLog(@"QueryString: %@", resultString);

Hope will help :)


问:
Join SQL tables
Suppose that in table "ab" I have the names of the students that get along from class "a" and class "b", identically I have table "ac" and "bc". What SQL query should I use in order to get all the combinations possible of students who can form groups (i.e. "get along together")? And how can i extend this to n classes?
For example: John from class a gets along with Jen from class b and Steff from class c, and Jen and Steff get along. Therefore John, Jen and Steff can form a group).</p>

答:
First you don't want to have a table for each class. You are capturing the same type of information in multiple tables and this is generally considered a bad practice. You want to "normalize" your data so that the same data exists in one place.

Second, name your tables appropriately so that you understand what you are actually trying to build. Maybe you are generalizing to mask what your intentions for the actual implementations are by using "ab" in the question, but if you are doing this in your actual code it will hurt you in the long run.

It appears you need a people table with names and a friends table where you track who is friends with who:

```<code>create table people ( id int, name char(128) );
create table friends ( id int, person_id int, friend_id int );
</code>```

Then you just need to have the query to get the groups:

```<code>SELECT person.* FROM friends
INNER JOIN friends grp
        ON friends.friend_id = grp.person_id
INNER JOIN people person
        ON person.id = grp.friend_id
WHERE friends.person_id = 42;
</code>```

Title: Join SQL tables

Body:
First you don't want to have a table for each class. You are capturing the same type of information in multiple tables and this is generally considered a bad practice. You want to "normalize" your data so that the same data exists in one place.

Second, name your tables appropriately so that you understand what you are actually trying to build. Maybe you are generalizing to mask what your intentions for the actual implementations are by using "ab" in the question, but if you are doing this in your actual code it will hurt you in the long run.

It appears you need a people table with names and a friends table where you track who is friends with who:

create table people ( id int, name char(128) );
create table friends ( id int, person_id int, friend_id int );

Then you just need to have the query to get the groups:

SELECT person.* FROM friends
INNER JOIN friends grp
        ON friends.friend_id = grp.person_id
INNER JOIN people person
        ON person.id = grp.friend_id
WHERE friends.person_id = 42;


问:
scala how to reduce while n > 0
I am wondering if there's a way to deal with a while (n > 0) loop in a more functional way, I have a small Scala app that counts the number of digits equal to K from a range from 1 to N:
for example 30 and 3 would return 4 [3, 13, 23, 30]

```<code>object NumKCount {

  def main(args: Array[String]): Unit = {
    println(countK(30,3))
  }

  def countKDigit(n:Int, k:Int):Int = {
      var num = n
      var count = 0
      while (num > 10) {
        val digit = num % 10
        if (digit == k) {count += 1}
        num = num / 10
      }
      if (num == k) {count += 1}
      count
  }

  def countK(n:Int, k:Int):Int = {
    1.to(n).foldLeft(0)((acc, x) => acc + countKDigit(x, k))
  }
}
</code>```

I'm looking for a way to define the function countKDigit using a purely functional approach

答:
Counting the occurrences of a single digit in a number sequence.

```<code>def countK(n:Int, k:Int):Int = {
  assert(k >= 0 && k <= 9)
  1.to(n).mkString.count(_ == '0' + k)
}
</code>```

If you really only want to modify countKDigit() to a more functional design, there's always recursion.

```<code>def countKDigit(n:Int, k:Int, acc: Int = 0):Int =
  if (n == 0) acc
  else countKDigit(n/10, k, if (n%10 == k) acc+1 else acc)
</code>```

Title: scala how to reduce while n > 0

Body:
I am wondering if there's a way to deal with a while (n > 0) loop in a more functional way, I have a small Scala app that counts the number of digits equal to K from a range from 1 to N:
for example 30 and 3 would return 4 [3, 13, 23, 30]

object NumKCount {

  def main(args: Array[String]): Unit = {
    println(countK(30,3))
  }

  def countKDigit(n:Int, k:Int):Int = {
      var num = n
      var count = 0
      while (num > 10) {
        val digit = num % 10
        if (digit == k) {count += 1}
        num = num / 10
      }
      if (num == k) {count += 1}
      count
  }

  def countK(n:Int, k:Int):Int = {
    1.to(n).foldLeft(0)((acc, x) => acc + countKDigit(x, k))
  }
}

I'm looking for a way to define the function countKDigit using a purely functional approach

Body:
Counting the occurrences of a single digit in a number sequence.

def countK(n:Int, k:Int):Int = {
  assert(k >= 0 && k <= 9)
  1.to(n).mkString.count(_ == '0' + k)
}

If you really only want to modify countKDigit() to a more functional design, there's always recursion.

def countKDigit(n:Int, k:Int, acc: Int = 0):Int =
  if (n == 0) acc
  else countKDigit(n/10, k, if (n%10 == k) acc+1 else acc)


问:
Normalizing a column of dataframe pyspark ML
I am trying to do L1 normalisation for the values of a column in a data frame using pyspark ML library. Following is my code. But it fails to do. Can you please help me in figuring out what is wrong with this code?

```<code>from pyspark.ml.feature import Normalizer

y = range(1,10)
data = spark.createDataFrame([[float(e), ] for e in y])
#data.select('_1').show()

normalizer = Normalizer(p=1.0, inputCol="_1", outputCol="features")
data2 = normalizer.transform(data)
data2.select("features").show()
</code>```

Following is a part of error log.

```<code>Py4JJavaError: An error occurred while calling o857.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure:
Task 0 in stage 36.0 failed 4 times, most recent failure: Lost task 0.3
in stage 36.0 (TID 67,  XXXXX.serveraddress.com):
org.apache.spark.SparkException: Failed to execute user defined
function($anonfun$createTransformFunc$1: (double) => vector)
</code>```

Body:
I am trying to do L1 normalisation for the values of a column in a data frame using pyspark ML library. Following is my code. But it fails to do. Can you please help me in figuring out what is wrong with this code?

from pyspark.ml.feature import Normalizer

y = range(1,10)
data = spark.createDataFrame([[float(e), ] for e in y])
#data.select('_1').show()

normalizer = Normalizer(p=1.0, inputCol="_1", outputCol="features")
data2 = normalizer.transform(data)
data2.select("features").show()

Following is a part of error log.

Py4JJavaError: An error occurred while calling o857.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure:
Task 0 in stage 36.0 failed 4 times, most recent failure: Lost task 0.3
in stage 36.0 (TID 67,  XXXXX.serveraddress.com):
org.apache.spark.SparkException: Failed to execute user defined
function($anonfun$createTransformFunc$1: (double) => vector)

Body:
Normalizer is used to to normalize Vectors across the Rows, not scalars across the columns.

To L1 scale one or more scalar columns you can try:

data.select([
    (data[c] / s).alias(c)
    for c, s in zip(data.columns, data.groupBy().sum().first())
])

## +--------------------+
## |                  _1|
## +--------------------+
## |0.022222222222222223|
## |0.044444444444444446|
## | 0.06666666666666667|
## | 0.08888888888888889|
## |  0.1111111111111111|
## | 0.13333333333333333|
## | 0.15555555555555556|
## | 0.17777777777777778|
## |                 0.2|
## +--------------------+

but beware of possible overflow and numerical precision issues.

You can of course scale a Column with Pipeline API as well:

from pyspark.ml.feature import SQLTransformer

stf = SQLTransformer(statement="""
    WITH norm AS (SELECT SUM({inputCol}) L1 FROM __THIS__)
    SELECT /*+ MAPJOIN(norm) +*/
      __THIS__.*, __THIS__.{inputCol} / norm.L1 {outputCol}
    FROM __THIS__  CROSS JOIN norm
    """.format(inputCol="_1", outputCol="_1_scaled"))

stf.transform(data)

## +---+--------------------+
## | _1|           _1_scaled|
## +---+--------------------+
## |1.0|0.022222222222222223|
## |2.0|0.044444444444444446|
## |3.0| 0.06666666666666667|
## |4.0| 0.08888888888888889|
## |5.0|  0.1111111111111111|
## |6.0| 0.13333333333333333|
## |7.0| 0.15555555555555556|
## |8.0| 0.17777777777777778|
## |9.0|                 0.2|
## +---+--------------------+


问:
Magento 1.9.1 security patch failed
I know it might be a duplicate question but I tried all answers of SO but nothing is working.

I am applying security patches on my magento 1.9.1 but all patches are failed.
I am using AWS EC-2 with php7 and ubuntu 16.04.

I have tried almot every answers

I have spent approx 2 hours and try with changing permission, running with bash, sh, ./path_path, chmod -x patch and others but same result every time.
.

答:
The hunk error normally came because it will not match the file lines. In this case you can do 2 things.

Replace mention files with new same version Magento setup and then try to install the patch using SSH.

Install the patch manually and then do your modifications on it.

Thanks.

Title: Magento 1.9.1 security patch failed


问:
Enabling SSL in ASP.NET MVC 5 app results in OpenIdConnectProtocolValidator issue
I have an ASP.NET MVC 5 app that authenticates against Azure Active Directory. I wanted to enable SSL on it across the app. and hence leveraged global filters as follows:

```<code>public class FilterConfig
{
    /// <summary>
    /// Registers the global filters.
    /// </summary>
    /// <param name="filters">The filters.</param>
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new RequireHttpsAttribute());
    }
}
</code>```

After this I also set 'Enable SSL' in the project's properties to true. This gave me the following SSL URL -> https://localhost:34567. I updated the project to have this in its IIS Express path under the 'Web Tab' under Servers in 'Project URL'. However on running the site I run in to the following error:

IDX10311: RequireNonce is 'true' (default) but validationContext.Nonce is null. A nonce cannot be validated. If you don't need to check the nonce, set OpenIdConnectProtocolValidator.RequireNonce to 'false'.

I have auth. enabled on the site. I use Azure Active directory.

The security code is as follows:

```<code>app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri
            });

        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Audience = audience,
                Tenant = tenant,
            });
</code>```

The auth. values are being read from the web.config and are as follows:

```<code><add key="ida:ClientId" value="<some_guid>" />
<add key="ida:Audience" value="https://localhost:34567/" />
<add key="ida:AADInstance" value="https://login.windows.net/{0}" />
<add key="ida:Tenant" value="microsoft.onmicrosoft.com" />
<add key="ida:PostLogoutRedirectUri" value="https://localhost:34567/" />
</code>```

I tried setting RequireNonce to false as directed in the error message as follows:

```<code>ProtocolValidator = new OpenIdConnectProtocolValidator
                {
                    RequireNonce = false
                }
</code>```

But this just resulted in an invalid request error.

Could someone help me understand what the problem is here? Everything worked great until SSL was enabled.

答:
I manage to work around this problem using following method in the Global.asax file. At least this won't show the exception to the client. I use ELMAH to catch exceptions.</p>

```<code>protected void Application_Error(object sender, EventArgs args)
    {
        var ex = Server.GetLastError();
        if (ex.Message.Contains("IDX10311:"))
        {
            Server.ClearError();
            Response.Redirect("https://www.yoursitename.com");
        }
</code>```

Body:
I have an ASP.NET MVC 5 app that authenticates against Azure Active Directory. I wanted to enable SSL on it across the app. and hence leveraged global filters as follows:

public class FilterConfig
{
    ///
    /// Registers the global filters.
    ///
    /// <param name="filters">The filters.</param>
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new RequireHttpsAttribute());
    }
}

After this I also set 'Enable SSL' in the project's properties to true. This gave me the following SSL URL -> https://localhost:34567. I updated the project to have this in its IIS Express path under the 'Web Tab' under Servers in 'Project URL'. However on running the site I run in to the following error:

IDX10311: RequireNonce is 'true' (default) but validationContext.Nonce is null. A nonce cannot be validated. If you don't need to check the nonce, set OpenIdConnectProtocolValidator.RequireNonce to 'false'.

I have auth. enabled on the site. I use Azure Active directory.

The security code is as follows:

app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri
            });

        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Audience = audience,
                Tenant = tenant,
            });

The auth. values are being read from the web.config and are as follows:

<add key="ida:ClientId" value="<some_guid>" />
<add key="ida:Audience" value="https://localhost:34567/" />
<add key="ida:AADInstance" value="https://login.windows.net/{0}" />
<add key="ida:Tenant" value="microsoft.onmicrosoft.com" />
<add key="ida:PostLogoutRedirectUri" value="https://localhost:34567/" />

I tried setting RequireNonce to false as directed in the error message as follows:

ProtocolValidator = new OpenIdConnectProtocolValidator
                {
                    RequireNonce = false
                }

But this just resulted in an invalid request error.

Could someone help me understand what the problem is here? Everything worked great until SSL was enabled.

Body:
I manage to work around this problem using following method in the Global.asax file. At least this won't show the exception to the client. I use ELMAH to catch exceptions.

protected void Application_Error(object sender, EventArgs args)
    {
        var ex = Server.GetLastError();
        if (ex.Message.Contains("IDX10311:"))
        {
            Server.ClearError();
            Response.Redirect("https://www.yoursitename.com");
        }


问:
PHP & MySQL - Deleting users problem
For some reason if a user does not have data in the info or pid MySQL tables I can't delete the user form any other table like the user table is there some way I can have the user
deleted even if the user has not entered data into the other tables except the user table?

Here is part of the code for deleting members.

```<code>    if(($months >= 3) && ($row['deletion'] == 1)){

        $dqc = mysqli_query($mysqli,"DELETE FROM info WHERE user_id = '" . $row['user_id'] . "'");
        if(!$dqc){ print mysqli_error($mysqli); }

        $dpq = mysqli_query($mysqli,"DELETE FROM pid WHERE user_id = '" . $row['user_id'] . "'");
        if(!$dpq){ print mysqli_error($mysqli); }

        $duq = mysqli_query($mysqli,"DELETE FROM users WHERE user_id = '" . $row['user_id'] . "'");
        if(!$duq){ print mysqli_error($mysqli); }
    }
</code>```

答:
Make sure this is populating properly</p>

```<code> $row['user_id']
</code>```

Title: PHP & MySQL - Deleting users problem

Body:
For some reason if a user does not have data in the info or pid MySQL tables I can't delete the user form any other table like the user table is there some way I can have the user
deleted even if the user has not entered data into the other tables except the user table?

Here is part of the code for deleting members.

    if(($months >= 3) && ($row['deletion'] == 1)){

        $dqc = mysqli_query($mysqli,"DELETE FROM info WHERE user_id = '" . $row['user_id'] . "'");
        if(!$dqc){ print mysqli_error($mysqli); }

        $dpq = mysqli_query($mysqli,"DELETE FROM pid WHERE user_id = '" . $row['user_id'] . "'");
        if(!$dpq){ print mysqli_error($mysqli); }

        $duq = mysqli_query($mysqli,"DELETE FROM users WHERE user_id = '" . $row['user_id'] . "'");
        if(!$duq){ print mysqli_error($mysqli); }
    }

Body:
Make sure this is populating properly

 $row['user_id']


问:
How to build an array in recursion?
I have the following structure array:

```<code>array:6 [▼
  "593a4331b25f428814000035" => array:8 [▶]
  "593a4331b25f428814000036" => array:8 [▶]
  "593a4331b25f428814000037" => array:8 [▶]
  "593a4331b25f428814000038" => array:8 [▼
    "_id" => MongoId {#238 ▶}
    "object_id" => "593a4331b25f428814000034"
    "parameter_id" => "59398f5ab25f424016000029"
    "value" => "1"
    "children" => []
    "parent_id" => "593a4331b25f428814000037"
    "type" => "2"
    "prefix" => "object"
  ]
  "593a4331b25f428814000039" => array:8 [▶]
  "593a4331b25f42881400003a" => array:8 [▶]
]
</code>```

As you can see 3-th element of array has parent 593a4331b25f428814000037, where identificator is element in the same array.

How to put this element 593a4331b25f428814000038 inside parent in children?

In result I need to get:

```<code>"593a4331b25f428814000037" => array:8 [▼
        "_id" => MongoId {#238 ▶}
        "object_id" => "593a4331b25f428814000034"
        "parameter_id" => "59398f5ab25f424016000029"
        "value" => "1"
        "children" => [ 0 => array("_id" => MongoId {#238 ▶}
        "object_id" => "593a4331b25f428814000034"
        "parameter_id" => "59398f5ab25f424016000029"
        "value" => "1"
        "children" => []
        "parent_id" => "593a4331b25f428814000037"
        "type" => "2"
        "prefix" => "object")]
        "parent_id" => "593a4331b25f428814000037"
        "type" => "2"
        "prefix" => "object"
      ]
</code>```

I tried this way:

```<code>public function recursion($data){

foreach ($data as $k => $value) {

            if (is_array($value['children']) && count($value['children']) > 0) {

                $list[$k] = $value;
                $list[$k]["children"] = $this->getChildren($all, $value['children']);

            } else {

                $list[$k] = $value;
            }
        }

        return $list;
}

private function getChildren($all, $childs)
    {

        $list = [];

        foreach ($childs as $k => $child) {

            if (is_array($all[$child]['children'])) {

                $tmpArray = $all[$child];
                $tmpArray['children'] = $this->getChildren($all, $all[$child]['children']);

            } else {

                $tmpArray = $all[$child];
            }

            $list[] = $tmpArray;
        }

        return $list;

    }
</code>```

But it works incorrect

答:
You can use array_reduce like:

```<code>$array = array_reduce($myArray, function ($carry, $item) {

    if (empty($item['parent_id'])) {
        $carry[$item['object_id']] = $item;
    } else {
        $carry[$item['parent_id']]['children'][] = $item;
    }
    return $carry;

}, []);

var_dump($array);
</code>```

In this example I supposed the parent_id is empty for those items which doesn't belong to a another item. You can change that with isset in case there is no parent_id key

Title: How to build an array in recursion?

Body:
I have the following structure array:

array:6 [▼
  "593a4331b25f428814000035" => array:8 [▶]
  "593a4331b25f428814000036" => array:8 [▶]
  "593a4331b25f428814000037" => array:8 [▶]
  "593a4331b25f428814000038" => array:8 [▼
    "_id" => MongoId {#238 ▶}
    "object_id" => "593a4331b25f428814000034"
    "parameter_id" => "59398f5ab25f424016000029"
    "value" => "1"
    "children" => []
    "parent_id" => "593a4331b25f428814000037"
    "type" => "2"
    "prefix" => "object"
  ]
  "593a4331b25f428814000039" => array:8 [▶]
  "593a4331b25f42881400003a" => array:8 [▶]
]

As you can see 3-th element of array has parent 593a4331b25f428814000037, where identificator is element in the same array.

How to put this element 593a4331b25f428814000038 inside parent in children?

In result I need to get:

"593a4331b25f428814000037" => array:8 [▼
        "_id" => MongoId {#238 ▶}
        "object_id" => "593a4331b25f428814000034"
        "parameter_id" => "59398f5ab25f424016000029"
        "value" => "1"
        "children" => [ 0 => array("_id" => MongoId {#238 ▶}
        "object_id" => "593a4331b25f428814000034"
        "parameter_id" => "59398f5ab25f424016000029"
        "value" => "1"
        "children" => []
        "parent_id" => "593a4331b25f428814000037"
        "type" => "2"
        "prefix" => "object")]
        "parent_id" => "593a4331b25f428814000037"
        "type" => "2"
        "prefix" => "object"
      ]

I tried this way:

public function recursion($data){

foreach ($data as $k => $value) {

            if (is_array($value['children']) && count($value['children']) > 0) {

                $list[$k] = $value;
                $list[$k]["children"] = $this->getChildren($all, $value['children']);

            } else {

                $list[$k] = $value;
            }
        }

        return $list;
}

private function getChildren($all, $childs)
    {

        $list = [];

        foreach ($childs as $k => $child) {

            if (is_array($all[$child]['children'])) {

                $tmpArray = $all[$child];
                $tmpArray['children'] = $this->getChildren($all, $all[$child]['children']);

            } else {

                $tmpArray = $all[$child];
            }

            $list[] = $tmpArray;
        }

        return $list;

    }

But it works incorrect

Body:
You can use array_reduce like:

$array = array_reduce($myArray, function ($carry, $item) {

    if (empty($item['parent_id'])) {
        $carry[$item['object_id']] = $item;
    } else {
        $carry[$item['parent_id']]['children'][] = $item;
    }
    return $carry;

}, []);

var_dump($array);

In this example I supposed the parent_id is empty for those items which doesn't belong to a another item. You can change that with isset in case there is no parent_id key


问:
Date not showing in div
I have View with div where I need to show date

I write this JavaScript code

$(document).ready(function() {
  var dateObj = new Date();
  var month = dateObj.getUTCMonth() + 1; //months from 1-12
  var day = dateObj.getUTCDate();
  var year = dateObj.getUTCFullYear();

  newdate = year + "/" + month + "/" + day;
  $("#id").append(newdate);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="date" style="width: 100%; height: 10%; background:#1d69b4 ">

</div></code>```

答:
In your HTML you have div id='date' and to display your formatted date string into that div then you should be using .text() or .html() instead of .append()

So your script should be

```<code>$("#date").text(newdate);

// or

$("#date").html(newdate);
</code>```

Title: Date not showing in div

Body:
In your HTML you have div id='date' and to display your formatted date string into that div then you should be using .text() or .html() instead of .append()

So your script should be

$("#date").text(newdate);

// or

$("#date").html(newdate);


问:
Spark Structured Streaming - compare two streams
I am using Kafka and Spark 2.1 Structured Streaming. I have two topics with data in json format eg:

```<code>topic 1:

{"id":"1","name":"tom"}
{"id":"2","name":"mark"}

topic 2:

{"name":"tom","age":"25"}
{"name":"mark","age:"35"}
</code>```

I need to compare those two streams in Spark base on tag:name and when value is equal execute some additional definition/function.

How to use Spark Structured Streaming to do this ?

Thanks

答: One method would be to transform both streams into (K,V) format. In your case this would probably take the form of (name, otherJSONData)  See the Spark documentation for more information on joining streams and an example located here. Then do a join on both streams and then perform whatever function on the newly joined stream. If needed you can use map to return (K,(W,V)) to (K,V).</p>

Body:
I am using Kafka and Spark 2.1 Structured Streaming. I have two topics with data in json format eg:

topic 1:

{"id":"1","name":"tom"}
{"id":"2","name":"mark"}

topic 2:

{"name":"tom","age":"25"}
{"name":"mark","age:"35"}

I need to compare those two streams in Spark base on tag:name and when value is equal execute some additional definition/function.

How to use Spark Structured Streaming to do this ?

Thanks


问:
Android Intent putExtra(String, Serializable)
I'm sorry if this Question is already answered, i searched a lot, but i couldn't find any question with my problem.

I'm writing an android app which gets data from an internet database. My first activity retrieves the data from the database, and i try to pass a reference to the whole database to another activity.

it briefly looks briefly like this:

```<code>//server is wrapper class for my database connection/ data retrieving
Server server = new Server(...connection data...);
server.connect();
server.filldata();
</code>```

And after that i try to pass this to another activity

```<code>Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra("server", server); //server, and all implements Serializable
startActivity(intent);
</code>```

And after this i get a java.lang.reflect.InvocationTargetException without explanation, what the problem could be.

Please if you know a way to pass an Object (except for int, string...) to another activity, help me!

答:
For any object which needs to be passed via Bundle must implement the Parcelable or Seralizable interface.Intent provides both the interfaces:

```<code>putExtra(String name, Parcelable value)
putExtra(String name, Serializable value)
</code>```

https://developer.android.com/reference/android/content/Intent.html

But it is advisable to use Parcelable as it is written specifically for Android and is light-weight in nature.

Body:
I'm sorry if this Question is already answered, i searched a lot, but i couldn't find any question with my problem.

I'm writing an android app which gets data from an internet database. My first activity retrieves the data from the database, and i try to pass a reference to the whole database to another activity.

it briefly looks briefly like this:

//server is wrapper class for my database connection/ data retrieving
Server server = new Server(...connection data...);
server.connect();
server.filldata();

And after that i try to pass this to another activity

Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra("server", server); //server, and all implements Serializable
startActivity(intent);

And after this i get a java.lang.reflect.InvocationTargetException without explanation, what the problem could be.

Please if you know a way to pass an Object (except for int, string...) to another activity, help me!

Body:
For any object which needs to be passed via Bundle must implement the Parcelable or Seralizable interface.Intent provides both the interfaces:

putExtra(String name, Parcelable value)
putExtra(String name, Serializable value)

https://developer.android.com/reference/android/content/Intent.html

But it is advisable to use Parcelable as it is written specifically for Android and is light-weight in nature.


问:
Generic parsing of Expressiontree to SQL
So, im having this very simple linq provider that does stuff with objects in a small constrained domain. No need for a full blown Linq2Sql implementation, but some of the stuff i need to do involves sql queries. My thougt was that, if you look away from table and column names, most expression tree => sql must be very (very) generic.

```<code>Expression<Func<DateTime, bool>> expr = d => d.DateTime.Month == 1
</code>```

will always translate to

```<code>DATEPART({0}, m) = 1
</code>```

or

```<code>Expression<Func<DateTime?, bool>> expr = d => d.HasValue || d ==  DateTime.Now
</code>```

into

```<code>{0} IS NOT NULL OR {0} = NOW()
</code>```

hope you get the point. Is there any generic sql generators like this out there?

答:
hehe, dont we just looove hacking around? So, its not FULLY working yet, i need to figure out how to dynamically inject some mapping information, but so far it looks promising.

I've been able to produce this sql

```<code>SELECT t0.[Born], t0.[Yo]
FROM [Heies] AS t0
WHERE ((MONTH(t0.[Born]) = 1) OR (NOT (t0.[Yo] IS NULL OR t0.[Yo] = '') AND (t0.
[Born] = @p0)))
</code>```

with this code

```<code>var provider = new DbEntityProvider(new SqlConnection(), new TSqlLanguage(), new ImplicitMapping(), new QueryPolicy());
var exp = provider.GetTable<Hey>().Where(d => d.Born.Month == 1 || (!String.IsNullOrEmpty(d.Yo) && d.Born == DateTime.Now)).Expression;
var sql = ((QueryProvider)provider).GetQueryText(exp);
</code>```

using the IQToolkit, so thanks to Damian for reminding me about it again! If anyone has a similar way to produce sql via Linq2Sql i would love to hear from you so i could loose the dependency on IQToolkit.

Update

After a lot of fooling around i have hit the wall at extracting the values for each of the parameters. After a lot of source reading it seems like its hidden far away for the actual execution of the query. Well, guess what, i don't want the query to be executed :/

After looking into Linq2Sql i came up with this code that does roughly the same, so maybe i should just stick with that

```<code>var xml = Generate<NewsProperty>();
var mapping = XmlMappingSource.FromUrl(xml);
var ctx = new DataContext(new SqlConnection("..."), mapping);

var query = ctx.GetTable<NewsProperty>().Where(n => n.Date.Year == 2010).OrderBy(n => n.Date).Take(5);
var cmd = ctx.GetCommand(query);
string sql = cmd.CommandText;

foreach (DbParameter param in cmd.Parameters)
{
   sql = sql.Replace(param.ParameterName, param.Value.ToString());
}
</code>```

Body:
So, im having this very simple linq provider that does stuff with objects in a small constrained domain. No need for a full blown Linq2Sql implementation, but some of the stuff i need to do involves sql queries. My thougt was that, if you look away from table and column names, most expression tree => sql must be very (very) generic.

Expression<Func<DateTime, bool>> expr = d => d.DateTime.Month == 1

will always translate to

DATEPART({0}, m) = 1

or

Expression<Func<DateTime?, bool>> expr = d => d.HasValue || d ==  DateTime.Now

into

{0} IS NOT NULL OR {0} = NOW()

hope you get the point. Is there any generic sql generators like this out there?

Body:
hehe, dont we just looove hacking around? So, its not FULLY working yet, i need to figure out how to dynamically inject some mapping information, but so far it looks promising.

I've been able to produce this sql

SELECT t0.[Born], t0.[Yo]
FROM [Heies] AS t0
WHERE ((MONTH(t0.[Born]) = 1) OR (NOT (t0.[Yo] IS NULL OR t0.[Yo] = '') AND (t0.
[Born] = @p0)))

with this code

var provider = new DbEntityProvider(new SqlConnection(), new TSqlLanguage(), new ImplicitMapping(), new QueryPolicy());
var exp = provider.GetTable<Hey>().Where(d => d.Born.Month == 1 || (!String.IsNullOrEmpty(d.Yo) && d.Born == DateTime.Now)).Expression;
var sql = ((QueryProvider)provider).GetQueryText(exp);

using the IQToolkit, so thanks to Damian for reminding me about it again! If anyone has a similar way to produce sql via Linq2Sql i would love to hear from you so i could loose the dependency on IQToolkit.

Update

After a lot of fooling around i have hit the wall at extracting the values for each of the parameters. After a lot of source reading it seems like its hidden far away for the actual execution of the query. Well, guess what, i don't want the query to be executed :/

After looking into Linq2Sql i came up with this code that does roughly the same, so maybe i should just stick with that

var xml = Generate<NewsProperty>();
var mapping = XmlMappingSource.FromUrl(xml);
var ctx = new DataContext(new SqlConnection("..."), mapping);

var query = ctx.GetTable<NewsProperty>().Where(n => n.Date.Year == 2010).OrderBy(n => n.Date).Take(5);
var cmd = ctx.GetCommand(query);
string sql = cmd.CommandText;

foreach (DbParameter param in cmd.Parameters)
{
   sql = sql.Replace(param.ParameterName, param.Value.ToString());
}