问:
How can I connect to multiple databases from a Blazor .NET Core project?
How do I connect to multiple database instances from a Blazor WebAssembly project, where I have also added the ASP.NET Core hosted?

My thought was to initiate the DBContexts into the `Startup.cs`` (from Blazor.Server Application which has a reference to Blazor.Client Application):

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<DatabaseContext>(options =>
            options.UseSqlite(
                "connection string holder ..."));
}
```

like this but I want to let the user choose in my View if they want to do a test run of the App where the SQLite database instance will be created. The regular run will be an instance to SQL Server database. How can I do this in the ConfigureServices method?

Right now I am building the DBContexts classes, are these effected too?

The controllers are not done yet, are ASP.NET Core MVC controllers the right choice?

答:
I haven't tried but you can try something like this-

In Blazor client Program.cs -

```<code>builder.Services.AddDatabaseStorage();
</code>```

In Blazor server Startup.cs -

```<code>   public void ConfigureServices(IServiceCollection services)
    {
        services.AddDatabaseStorage();
    }
</code>```

Create a static class and add all the DB storage interfaces and their implementations-

```<code>public static class StorageServiceCollections
{
    public static IServiceCollection AddDatabaseStorage(this IServiceCollection
 services)
    {
  //you may also return DB service based on certain condition here. Like factory, singleton pattern.
        return services
            .AddSingleton<IDBStorageService, SQLStorageService>()
            .AddSingleton<IMongoDBStorageService, MongoStorageService>();
    }
}
</code>```

Stablish DB connections and their implementation classes e.g. SQLStorageService, MongoStorageService Something like this -

```<code>  public MongoStorageService()
    {
        var client = new MongoClient("mongodb://localhost:23456");
        _mongoDatabase = client.GetDatabase("DB");
    }
</code>```

Inject in razor components to call them -

```<code>@inject IDBStorageService dbStorage
</code>```

Body:
How do I connect to multiple database instances from a Blazor WebAssembly project, where I have also added the ASP.NET Core hosted?

My thought was to initiate the DBContexts into the `Startup.cs`` (from Blazor.Server Application which has a reference to Blazor.Client Application):

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<DatabaseContext>(options =>
            options.UseSqlite(
                "connection string holder ..."));
}

like this but I want to let the user choose in my View if they want to do a test run of the App where the SQLite database instance will be created. The regular run will be an instance to SQL Server database. How can I do this in the ConfigureServices method?

Right now I am building the DBContexts classes, are these effected too?

The controllers are not done yet, are ASP.NET Core MVC controllers the right choice?

Body:
I haven't tried but you can try something like this-

In Blazor client Program.cs -

builder.Services.AddDatabaseStorage();

In Blazor server Startup.cs -

   public void ConfigureServices(IServiceCollection services)
    {
        services.AddDatabaseStorage();
    }

Create a static class and add all the DB storage interfaces and their implementations-

public static class StorageServiceCollections
{
    public static IServiceCollection AddDatabaseStorage(this IServiceCollection
 services)
    {
  //you may also return DB service based on certain condition here. Like factory, singleton pattern.
        return services
            .AddSingleton<IDBStorageService, SQLStorageService>()
            .AddSingleton<IMongoDBStorageService, MongoStorageService>();
    }
}

Stablish DB connections and their implementation classes e.g. SQLStorageService, MongoStorageService Something like this -

  public MongoStorageService()
    {
        var client = new MongoClient("mongodb://localhost:23456");
        _mongoDatabase = client.GetDatabase("DB");
    }

Inject in razor components to call them -

@inject IDBStorageService dbStorage


来源: stackexchange

问:
how to visualize geodata (Points) in databricks builtin map?
I simply have a dataframe of "lat" and "lon" coordinates that I would like to visualize on a map.

I am trying to view my data data on the map. But nothing is being displayed.
In my case, the mmsi is the id.

Please note that I have around 2M points to display. Is that possible in databricks?

If there is no way around (plotting 2,000,000 points) in databricks, then what tool can handle large amount of data?

Any help is much appreciated!!

答:
The built in map does not support latitude / longitude data points.

Delivering 2 million data points directly to a browser is problematic. Databricks has a protective limit of 20 MB for HTML display. Your viewers won't be able to take in and visually process that level of detail at any point in time.

I recommend implementing a filter/summarization strategy to enable the display within Databricks notebooks. Some ideas can be taken from this Databricks post: https://databricks.com/blog/2019/12/05/processing-geospatial-data-at-scale-with-databricks.html

Also this Anaconda post gives an excellent survey of data visualization packages, some (like Datashader, Vaex) implement a visual summarization strategies before rendering images: https://www.anaconda.com/blog/python-data-visualization-2018-why-so-many-libraries

ContentLicense: CC BY-SA 4.0


问:
Xcode 11 "iphone is busy: Making iphone ready for development"
I have been waiting 2 days now, and the xcode "Devices and simulators" window is still hung with the message "myiphone is busy: Making myiphone ready for development".

I have connected this phone to xcode and uploaded apps many times before

I have not updated ios nor macos recently

I have tried the usual suspects:

waiting. 5 hours so far.

disconnecting phone, restarting xcode

rebooting phone.

rebooting mac

checking under general-device management, nothing new there.

versions:

xcode 11.2

2017 mb pro 512 quad. 16GB

mac 10.14.4 (I can never upgrade beyond this due to need for 32bit drivers).

ios 13.3.1

iphone storage: 51GB
of 64GB used.

I also frequently get the issue that when I connect the iphone the device managers says its locked, but it is not locked. In this case, I disconnect device, restart xcode, reconnect the device while xcode is running, which fixes this common issue.

答: Well, some days later, after several reboots and assorted activities, it started working.  So no idea what caused it.</p>


问:
I have two tables in mysql in which i want to query in mysql as follows
table - emp

```<code>ename | sal  | deptno
-----------------------
smith | 800  | 20
allen | 1600 | 30
ward  | 1400 | 30
jones | 1200 | 20
</code>```

table - dept

```<code>deptno | dname
----------------
20     | Accounting
30     | Sales
</code>```

i want the following output which displays average salary of each department

```<code>deptno| dname     | avg(sal)
-----------------------------
20    | Accounting| 1000
30    | Sales     | 1500
</code>```

i have tried the query
select emp.deptno, dname, avg(sal) from emp,dept group by (emp.deptno);

but it is showing error dept.dname' which is not functionally dependent on columns in GROUP BY clause;

答:
just use avg() and group by  </p>

```<code>select  a.deptno, a.dname, avg(b.sal)
from dept a
inner  join emp b on a.deptno = b.deptno
group by   a.deptno, a.dname
</code>```

Body:
table - emp

ename | sal  | deptno
-----------------------
smith | 800  | 20
allen | 1600 | 30
ward  | 1400 | 30
jones | 1200 | 20

table - dept

deptno | dname
----------------
20     | Accounting
30     | Sales

i want the following output which displays average salary of each department

deptno| dname     | avg(sal)
-----------------------------
20    | Accounting| 1000
30    | Sales     | 1500

i have tried the query
select emp.deptno, dname, avg(sal) from emp,dept group by (emp.deptno);

but it is showing error dept.dname' which is not functionally dependent on columns in GROUP BY clause;

Body:
just use avg() and group by

select  a.deptno, a.dname, avg(b.sal)
from dept a
inner  join emp b on a.deptno = b.deptno
group by   a.deptno, a.dname


问:
Upload Photos using Silverlight - Ria Services
i'm trying to find a good exemple on uploading and downloading images using solely Silverlgith + Ria Services, i tried to find some but i failed, please any help would be appreciated.

thank you all in advance

答: I just found some useful walk trough here and make sure to read follow-up that improves the save process and used image</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How to handle element in parent id in jquery
I want to show a content in an increase id ( #showcp_ ) when click the id ( #coupon_click_ ) I use php for increase the value of ids, and I just want to show content in parent id ( #cp_box_ ), how to solve this ?</p>

```<code><div class="row cp_box" >
    <?php
    $counter = -1;
    $args = array(
        'post_status' => 'publish',
        'post_type' => 'post',
        'showposts' => 3,
        'cat' => 6,
    );
    ?>
    <?php $getposts = new WP_query($args); ?>
    <?php global $wp_query; $wp_query->in_the_loop = true; ?>
    <?php while ($getposts->have_posts()) : $getposts->the_post(); $counter++ ?>

        <div id="cp_box_<?php echo $counter; ?>" class="col large-4" style="background-image:url(<?php the_post_thumbnail_url(); ?>);position:relative;">
            <ul class="time_cp">
                <li class="time-begin">Time begin:  </li>
                <li class="time-end">Expired: </li>
            </ul>
            <div class="coupon_wrap">
                <a id="coupon_click_<?php echo $counter; ?>"  href="#" target="_blank">View coupon</a>
                <p  id="showcp_<?php echo $counter; ?>" class="cp_show" style="display:none;">Coupon code</p>
                <a class="readmore" href="<?php the_permalink(); ?>">View detail</a>
            </div>
        </div>
    <?php endwhile; wp_reset_postdata(); ?>
</div>
<script>
    $(document).ready(function() {
        $("[id^='coupon_click_']").click(function() {
            $("[id^='showcp_']").show();
            $("[id^='coupon_click_']").hide();
        });
    });
</script>
</code>```

答:
You can solve this easily using the correct this context here like:

```<code>$(document).ready(function() {
    $("[id^='coupon_click_']").click(function() {
        $(this).closest(".coupon_wrap").find("[id^='showcp_']").show();
        $(this).hide();
    });
});
</code>```

Explanation:

$(this).closest(".coupon_wrap") will find the closest parent div with class .coupon_wrap to the clicked coupon_click_ link.

Then it will find the showcp_ element inside that div and show it.

And finally using $(this).hide() we simply hide the clicked coupon_click_ element instead of hiding all the elements where id starts with coupon_click_.

Body:
I want to show a content in an increase id ( #showcp_ ) when click the id ( #coupon_click_ ) I use php for increase the value of ids, and I just want to show content in parent id ( #cp_box_ ), how to solve this ?

    <?php
    $counter = -1;
    $args = array(
        'post_status' => 'publish',
        'post_type' => 'post',
        'showposts' => 3,
        'cat' => 6,
    );
    ?>
    <?php $getposts = new WP_query($args); ?>
    <?php global $wp_query; $wp_query->in_the_loop = true; ?>
    <?php while ($getposts->have_posts()) : $getposts->the_post(); $counter++ ?>

        <div id="cp_box_<?php echo $counter; ?>" class="col large-4" style="background-image:url(<?php the_post_thumbnail_url(); ?>);position:relative;">

Time begin:

Expired:

                <a id="coupon_click_<?php echo $counter; ?>"  href="#" target="_blank">View coupon
                <p  id="showcp_<?php echo $counter; ?>" class="cp_show" style="display:none;">Coupon code

                <a class="readmore" href="<?php the_permalink(); ?>">View detail

    <?php endwhile; wp_reset_postdata(); ?>

Body:
You can solve this easily using the correct this context here like:

$(document).ready(function() {
    $("[id^='coupon_click_']").click(function() {
        $(this).closest(".coupon_wrap").find("[id^='showcp_']").show();
        $(this).hide();
    });
});

Explanation:

$(this).closest(".coupon_wrap") will find the closest parent div with class .coupon_wrap to the clicked coupon_click_ link.

Then it will find the showcp_ element inside that div and show it.

And finally using $(this).hide() we simply hide the clicked coupon_click_ element instead of hiding all the elements where id starts with coupon_click_.


问:
SigninScreen.js and functions.js - how to make function.js function update useState in SigninScreen.js?
I have two files: one for functions (functions.js) and one for SigninScreen, please see the code below. How can I make the signInUser formula refer back to the SigninScreen (and e.g. update useState value of email/password there)?

Right now, it seems as if the signInUser function does not have access to that scope because I get error message stating 'setEmail is not a function'.

functions.js

```<code>export async function signInUser(email, password) {
  console.log('Attempting to sign in');

  credentials = {
  email: email.toString(),
  password: password.toString()
  }

  const requestOptions = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(credentials)
  };
  const response = await fetch('http://localhost:3000/signin', requestOptions)
  const data = await response.json()

  setEmail('xaxaxaxa')

  console.log(data)

}
</code>```

SigninScreen.js

```<code>import React, { useState, useContext } from 'react'
import { View, StyleSheet, Button } from 'react-native'
import { Text, Input } from 'react-native-elements'
import Spacer from '../components/Spacer'
import { signInUser } from '../functions/functions.js'
import UserContext from '../context/appContext.js'

const SigninScreen = ({ navigation }) => {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')

  // This can be removed later
  const user = useContext(UserContext);
  console.log(user);

  return (
  <UserContext.Consumer>
  {({userloggerinfo, updateUserLoggerInfo}) => (
  <View style={styles.container}>
    <Spacer>
      <Text h3>Sign in</Text>
    </Spacer>
    <Input
    label="Email"
    value={email}
    onChangeText={setEmail}
    autoCapitalize="none"
    autoCorrect={false}
    />
    <Spacer />
    <Input
    secureTextEntry
    label="Password"
    value={password}
    onChangeText={setPassword}
    autoCapitalize="none"
    autoCorrect={false}
    />
    <Spacer>
      <Button
      title="Sign in"
      onPress={() => { signInUser(email, password); console.log('hejjjjjj'); }}
      />
    </Spacer>
  </View>
  )}
  </UserContext.Consumer>
  )
}

SigninScreen.navigationOptions = () => {
  return {
    header: null
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    marginBottom: 250
  }
})

export default SigninScreen
</code>```

Kind regards

答:
function.js ---- >

```<code>export async function signInUser(email, password,setEmail) {
    console.log('Attempting to sign in');

    let credentials = {
    email: email.toString(),
    password: password.toString()
    }

    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(credentials)
    };
    const response = await fetch('http://localhost:3000/signin', requestOptions)
    const data = await response.json()

    setEmail('xaxaxaxa')

    console.log(data)
  }
</code>```

SignInScreen.js ----- >

```<code>import React, { useState, useContext } from 'react'
import { View, StyleSheet, Button } from 'react-native'
import { Text, Input } from 'react-native-elements'
import Spacer from '../components/Spacer'
import { signInUser } from '../functions/functions.js'
import UserContext from '../context/appContext.js'

const SigninScreen = ({ navigation }) => {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')

  // This can be removed later
  const user = useContext(UserContext);
  console.log(user);

  return (
  <UserContext.Consumer>
  {({userloggerinfo, updateUserLoggerInfo}) => (
  <View style={styles.container}>
    <Spacer>
      <Text h3>Sign in</Text>
    </Spacer>
    <Input
    label="Email"
    value={email}
    onChangeText={setEmail}
    autoCapitalize="none"
    autoCorrect={false}
    />
    <Spacer />
    <Input
    secureTextEntry
    label="Password"
    value={password}
    onChangeText={setPassword}
    autoCapitalize="none"
    autoCorrect={false}
    />
    <Spacer>
      <Button
      title="Sign in"
      onPress={() => { signInUser(email, password,setEmail); console.log('hejjjjjj'); }}
      />
    </Spacer>
  </View>
  )}
  </UserContext.Consumer>
  )
}

SigninScreen.navigationOptions = () => {
  return {
    header: null
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    marginBottom: 250
  }
})

export default SigninScreen
</code>```

Try above code it should work now!! :)

Body:
I have two files: one for functions (functions.js) and one for SigninScreen, please see the code below. How can I make the signInUser formula refer back to the SigninScreen (and e.g. update useState value of email/password there)?

Right now, it seems as if the signInUser function does not have access to that scope because I get error message stating 'setEmail is not a function'.

functions.js

export async function signInUser(email, password) {
  console.log('Attempting to sign in');

  credentials = {
  email: email.toString(),
  password: password.toString()
  }

  const requestOptions = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(credentials)
  };
  const response = await fetch('http://localhost:3000/signin', requestOptions)
  const data = await response.json()

  setEmail('xaxaxaxa')

  console.log(data)

}

SigninScreen.js

import React, { useState, useContext } from 'react'
import { View, StyleSheet, Button } from 'react-native'
import { Text, Input } from 'react-native-elements'
import Spacer from '../components/Spacer'
import { signInUser } from '../functions/functions.js'
import UserContext from '../context/appContext.js'

const SigninScreen = ({ navigation }) => {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')

  // This can be removed later
  const user = useContext(UserContext);
  console.log(user);

  return (
  <UserContext.Consumer>
  {({userloggerinfo, updateUserLoggerInfo}) => (
  <View style={styles.container}>
    <Spacer>
      <Text h3>Sign in</Text>
    </Spacer>
    <Input
    label="Email"
    value={email}
    onChangeText={setEmail}
    autoCapitalize="none"
    autoCorrect={false}
    />
    <Spacer />
    <Input
    secureTextEntry
    label="Password"
    value={password}
    onChangeText={setPassword}
    autoCapitalize="none"
    autoCorrect={false}
    />
    <Spacer>
      <Button
      title="Sign in"
      onPress={() => { signInUser(email, password); console.log('hejjjjjj'); }}
      />
    </Spacer>
  </View>
  )}
  </UserContext.Consumer>
  )
}

SigninScreen.navigationOptions = () => {
  return {
    header: null
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    marginBottom: 250
  }
})

export default SigninScreen

Kind regards

Body:
function.js ---- >

export async function signInUser(email, password,setEmail) {
    console.log('Attempting to sign in');

    let credentials = {
    email: email.toString(),
    password: password.toString()
    }

    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(credentials)
    };
    const response = await fetch('http://localhost:3000/signin', requestOptions)
    const data = await response.json()

    setEmail('xaxaxaxa')

    console.log(data)
  }

SignInScreen.js ----- >

import React, { useState, useContext } from 'react'
import { View, StyleSheet, Button } from 'react-native'
import { Text, Input } from 'react-native-elements'
import Spacer from '../components/Spacer'
import { signInUser } from '../functions/functions.js'
import UserContext from '../context/appContext.js'

const SigninScreen = ({ navigation }) => {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')

  // This can be removed later
  const user = useContext(UserContext);
  console.log(user);

  return (
  <UserContext.Consumer>
  {({userloggerinfo, updateUserLoggerInfo}) => (
  <View style={styles.container}>
    <Spacer>
      <Text h3>Sign in</Text>
    </Spacer>
    <Input
    label="Email"
    value={email}
    onChangeText={setEmail}
    autoCapitalize="none"
    autoCorrect={false}
    />
    <Spacer />
    <Input
    secureTextEntry
    label="Password"
    value={password}
    onChangeText={setPassword}
    autoCapitalize="none"
    autoCorrect={false}
    />
    <Spacer>
      <Button
      title="Sign in"
      onPress={() => { signInUser(email, password,setEmail); console.log('hejjjjjj'); }}
      />
    </Spacer>
  </View>
  )}
  </UserContext.Consumer>
  )
}

SigninScreen.navigationOptions = () => {
  return {
    header: null
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    marginBottom: 250
  }
})

export default SigninScreen

Try above code it should work now!! :)


问:
insertRowBefore() not displaying values
Can someone advise what I am doing wrong with the following code please?
I know it's simple but I think I've been staring at the screen for too long!

```<code>function addDelivery() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var srcSheet = ss.getSheetByName("Sheet7");

  var range = srcSheet.getRange("B3:J3").getValues();
  srcSheet.insertRowBefore(6);
  srcSheet.getRange(6,2,1,4).setValues([['B3', 'C3', 'D3', 'E3' , 'F3' , 'G3' , 'H3' , 'I3' , 'J3']]);
</code>```

I'm obviously trying to append the values in cells B3:J3, not have it show B3, C3, D3 etc in the appended row!

答:
Sorry for the post.
The answer was obvious....

```<code>srcSheet.getRange(6,2,1,9).setValues(range);
</code>```

Was as simple as that!

Hope this helps someone.

Best regards manc

Title: insertRowBefore() not displaying values

Body:
Can someone advise what I am doing wrong with the following code please?
I know it's simple but I think I've been staring at the screen for too long!

function addDelivery() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var srcSheet = ss.getSheetByName("Sheet7");

  var range = srcSheet.getRange("B3:J3").getValues();
  srcSheet.insertRowBefore(6);
  srcSheet.getRange(6,2,1,4).setValues([['B3', 'C3', 'D3', 'E3' , 'F3' , 'G3' , 'H3' , 'I3' , 'J3']]);

I'm obviously trying to append the values in cells B3:J3, not have it show B3, C3, D3 etc in the appended row!

Body:
Sorry for the post.
The answer was obvious....

srcSheet.getRange(6,2,1,9).setValues(range);

Was as simple as that!

Hope this helps someone.

Best regards manc


问:
What is the difference between braces and commas when used to separate arms of a match expression?
I just started learning Rust and there are some things that confuse me.

I read Chapter 2 of the book, Programming a Guessing Game and some parts of the code are making me wonder what is right or not.

Example:
Here's a loop I asked about in another question:

 loop {
    ...

    match guess.cmp(&secret_number) {
        Ordering::Less => println!("Too small!"),
        Ordering::Greater => println!("Too big!"),
        Ordering::Equal => {
            println!("You win!");
            break;
        }
    }
}
```

<p>I realized I could write this instead:</p>

<pre class="lang-rust prettyprint-override"><code> match guess.cmp(&secret_number) {
    Ordering::Less => {
        println!("Too low!") // without semicolon ;
    } // without comma ,
    Ordering::Greater => {
        println!("Too high!")
    }
    Ordering::Equal => {
        println!("You win!!!");
        break;
    }
 }
</code>```

I find it confusing, I don't know if it's good or wrong, if it could cause future breaking changes ...
Can anyone help me understand?

答:
The comma at the end of match arm is optional if braces are used. The rust parser/tokenizer can unambiguously parse the match arms with or without comma. Look here:  comma is optional.

Anything ending with semicolon is a statement which doesn't return any value (expect return <>; statement).

In the first case,

```<code>Ordering::Less => println!("Too small!"),

// Returns a unit value
</code>```

In the second case with braces, the last line without the semicolon would be returned. In this case, it is a unit value.

See this example:

```<code>   let flag = false;

   let result = match flag {
        false => {
            println!("in false arm");
            100
        },
        true => {
            println!("In true arm");
            200
        }
   };
   println!("result = {}", result);
</code>```

This prints the following:

```<code>in false arm
result = 100
</code>```

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f4a531293d9fc82459da0c3fbcf0e93d

Body:
I just started learning Rust and there are some things that confuse me.

I read Chapter 2 of the book, Programming a Guessing Game and some parts of the code are making me wonder what is right or not.

Example:
Here's a loop I asked about in another question:

 loop {
    ...

    match guess.cmp(&secret_number) {
        Ordering::Less => println!("Too small!"),
        Ordering::Greater => println!("Too big!"),
        Ordering::Equal => {
            println!("You win!");
            break;
        }
    }
}

I realized I could write this instead:

 match guess.cmp(&secret_number) {
    Ordering::Less => {
        println!("Too low!") // without semicolon ;
    } // without comma ,
    Ordering::Greater => {
        println!("Too high!")
    }
    Ordering::Equal => {
        println!("You win!!!");
        break;
    }
 }

I find it confusing, I don't know if it's good or wrong, if it could cause future breaking changes ...
Can anyone help me understand?

Body:
The comma at the end of match arm is optional if braces are used. The rust parser/tokenizer can unambiguously parse the match arms with or without comma. Look here:  comma is optional.

Anything ending with semicolon is a statement which doesn't return any value (expect return <>; statement).

In the first case,

Ordering::Less => println!("Too small!"),

// Returns a unit value

In the second case with braces, the last line without the semicolon would be returned. In this case, it is a unit value.

See this example:

   let flag = false;

   let result = match flag {
        false => {
            println!("in false arm");
            100
        },
        true => {
            println!("In true arm");
            200
        }
   };
   println!("result = {}", result);

This prints the following:

in false arm
result = 100

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f4a531293d9fc82459da0c3fbcf0e93d


问:
Good xcode alternative for writing objective-C code
As Xcode 4 is likely to stay as slow as it is now, are there any editors out there that are code aware and good with objective-C?

I will not stop using xcode, it still has great features but just for the writing of the code.

答:
JetBrains is working on AppCode - http://www.jetbrains.com/objc/

It's in beta and freely available.  Worth a look if you searching for alternatives.


问:
Install `pygame` with Pip problems
When I run python -V on terminal, it outputs Python 3.8.0 but whenever I try to install a library with pip, it always downloads to Python 3.7.

For example, when I run pip3 install pygame, it outputs Requirement already satisfied: pygame in /usr/local/lib/python3.7/site-packages (1.9.6) but when I test it with import pygame, it returns ModuleNotFoundError: No module named 'pygame'.

I think I installed Python 3.8 incorrectly? I've been using an older version of python with no problems up to now, and I tried installing python 3.8 with pyenv, and ever since then I've had this problem.

My pip is updated: Requirement already up-to-date: pip in /usr/local/lib/python3.7/site-packages (20.0.2)

P.S. Is it just me or do you guys have two folders called Python in both your user library and Macintosh HD library? Also, the 3.7.7 is referring to a totally different folder at Macintosh HD/ussr/local/Cellar/python... is this normal?

Edit: pip3 --version returns pip 20.0.2 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)

Edit 2: Tried using venv. A really long error... (the below error message is only the final part of the actual error message)

```<code>ERROR: Command errored out with exit status 1: /Users/username/my_venv/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/g3/8kbv7g411r32xwzp2681_s540000gn/T/pip-install-ywfy_s_y/pygame/setup.py'"'"'; __file__='"'"'/private/var/folders/g3/8kbv7g411r32xwzp2681_s540000gn/T/pip-install-ywfy_s_y/pygame/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/g3/8kbv7g411r32xwzp2681_s540000gn/T/pip-record-fxa7km57/install-record.txt --single-version-externally-managed --compile --install-headers /Users/username/my_venv/include/site/python3.8/pygame Check the logs for full command output.
</code>```

Edit 3: I just tried reinstalling numpy & pandas & matplotlib, it works with pip3.8 install <library> but pygame doesn't work. Could it be pygame's fault?

Edit 4: Nevermind, I figured it out! Apparently pygame dev 3 wasn't out when Python 3.8 was released, so I have to modify my command to dev 6 with
python3 -m pip install pygame==2.0.0.dev6... I don't know why it doesn't fetch the latest version by default but it worked so thank you for your help and time!

答: Try create a venv with Python 3.7.7. That worked fine for me without any other config.</p>

Title: Install `pygame` with Pip problems

Body:
When I run python -V on terminal, it outputs Python 3.8.0 but whenever I try to install a library with pip, it always downloads to Python 3.7.

For example, when I run pip3 install pygame, it outputs Requirement already satisfied: pygame in /usr/local/lib/python3.7/site-packages (1.9.6) but when I test it with import pygame, it returns ModuleNotFoundError: No module named 'pygame'.

I think I installed Python 3.8 incorrectly? I've been using an older version of python with no problems up to now, and I tried installing python 3.8 with pyenv, and ever since then I've had this problem.

My pip is updated: Requirement already up-to-date: pip in /usr/local/lib/python3.7/site-packages (20.0.2)

P.S. Is it just me or do you guys have two folders called Python in both your user library and Macintosh HD library? Also, the 3.7.7 is referring to a totally different folder at Macintosh HD/ussr/local/Cellar/python... is this normal?

Edit: pip3 --version returns pip 20.0.2 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)

Edit 2: Tried using venv. A really long error... (the below error message is only the final part of the actual error message)

ERROR: Command errored out with exit status 1: /Users/username/my_venv/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/g3/8kbv7g411r32xwzp2681_s540000gn/T/pip-install-ywfy_s_y/pygame/setup.py'"'"'; __file__='"'"'/private/var/folders/g3/8kbv7g411r32xwzp2681_s540000gn/T/pip-install-ywfy_s_y/pygame/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/g3/8kbv7g411r32xwzp2681_s540000gn/T/pip-record-fxa7km57/install-record.txt --single-version-externally-managed --compile --install-headers /Users/username/my_venv/include/site/python3.8/pygame Check the logs for full command output.

Edit 3: I just tried reinstalling numpy & pandas & matplotlib, it works with pip3.8 install <library> but pygame doesn't work. Could it be pygame's fault?

Edit 4: Nevermind, I figured it out! Apparently pygame dev 3 wasn't out when Python 3.8 was released, so I have to modify my command to dev 6 with
python3 -m pip install pygame==2.0.0.dev6... I don't know why it doesn't fetch the latest version by default but it worked so thank you for your help and time!


问:
zsh completion : suggestion of multiples directory and how to choose one without knowing the content of this directory
I have a simple issue with zsh. Sometimes, I am in a directory with multiples sub-directories.

So, when I do a $ ls[TAB] or $cd[TAB], I list all these sub-directories.

But how to accept one of the suggestions for sub-directories? Is there a short cut or a key to choose a directory to go deeper in this directory.

I must precise that I don't know systematically the content of these subdirectories, so I can't often choose a subdirectory in which the first letter of filename could allow me to choose automatically the sub-directory to explore.

I was looking for a solution on the web but documentation about zsh completion is pretty big.

答: The only way I know is: double click your target + cmd c + cmd v and then press Enter.</p>


问:
How to merge date and time in Pandas?
I am a beginner of Pandas, so my question is very basic. I have a dataset, which has seperate columns for date and time as following

```<code>    Date        Time    Ooen    High    Low     Close   Vol
0   2000.12.22  12:00   0.91810 0.92620 0.91650 0.92320 2244
1   2000.12.22  16:00   0.92260 0.92520 0.92220 0.92310 1688
2   2000.12.22  20:00   0.92300 0.92580 0.92260 0.92420 955
3   2000.12.23  00:01   0.92410 0.92450 0.92270 0.92320 168
4   2000.12.25  00:00   0.92300 0.92460 0.92300 0.92420 260
</code>```

The type of Date and Time are

```<code>type(df['Date'])
pandas.core.series.Series

type(df['Time'])
pandas.core.series.Series
</code>```

I don't know how to merge them into a timestamp like

```<code>'2015-07-04 00:00:00'
</code>```

Could anyone please help me?

Title: How to merge date and time in Pandas?

Body:
I am a beginner of Pandas, so my question is very basic. I have a dataset, which has seperate columns for date and time as following

    Date        Time    Ooen    High    Low     Close   Vol
0   2000.12.22  12:00   0.91810 0.92620 0.91650 0.92320 2244
1   2000.12.22  16:00   0.92260 0.92520 0.92220 0.92310 1688
2   2000.12.22  20:00   0.92300 0.92580 0.92260 0.92420 955
3   2000.12.23  00:01   0.92410 0.92450 0.92270 0.92320 168
4   2000.12.25  00:00   0.92300 0.92460 0.92300 0.92420 260

The type of Date and Time are

type(df['Date'])
pandas.core.series.Series

type(df['Time'])
pandas.core.series.Series

I don't know how to merge them into a timestamp like

'2015-07-04 00:00:00'

Could anyone please help me?

Body:
You could try something like this -

df['Datetime'] = pd.to_datetime(df['Date'] + ' ' + df['Time'], format='%Y.%m.%d %H:%M')
df
     Date       Time   Open    High    Low    Close    Vol    Datetime
0  2000.12.22  12:00  0.9181  0.9262  0.9165  0.9232  2244 2000-12-22 12:00:00
1  2000.12.22  16:00  0.9226  0.9252  0.9222  0.9231  1688 2000-12-22 16:00:00
2  2000.12.22  20:00  0.9230  0.9258  0.9226  0.9242   955 2000-12-22 20:00:00
3  2000.12.23  00:01  0.9241  0.9245  0.9227  0.9232   168 2000-12-23 00:01:00
4  2000.12.25  00:00  0.9230  0.9246  0.9230  0.9242   260 2000-12-25 00:00:00


问:
How to change from request.site to Site._find_for_request(request) in wagtail 2.9
I've recently upgraded my wagtail app to the latest version, version 2.9, now since the wagtail site middleware has been deprecated I'm having trouble getting my site to work. I was using a request.site now  wagtail 2.9 uses Site._find_for_request(request)

How do I change my current code to work with the latest wagtail version? Thanks in advance

```<code>@register.simple_tag(takes_context=True)
</code>```

def og_image(context, page):

```<code>protocol = re.compile(r'^(\w[\w\.\-\+]*:)*//')

if protocol.match(settings.MEDIA_URL):
    base_url = ''
else:
    base_url = context['request'].site.root_url

if page:
    if page.og_image:
        return base_url + page.og_image.get_rendition('original').url
    elif page.cover_image:
        return base_url + page.cover_image.get_rendition('original').url
if LayoutSettings.for_site(context['request'].site).logo:
    layout_settings = LayoutSettings.for_site(context['request'].site)
    return base_url + layout_settings.logo.get_rendition('original').url
return None
</code>```

答:
It looks like that you're still doing the old way of getting current site, in this case:

```<code>context['request'].site
</code>```

where context['request'] is the request object. Change those occurrences to below as recommended in the Wagtail 2.9 release notes:

```<code>Site.find_for_request(context['request'])
</code>```

Don't forget to make sure that you have from wagtail.core.models import Site somewhere on top of the file or else your code won't work, i.e. you get an error.

You can find more info on Site.find_for_request in the docs.

Body:
I've recently upgraded my wagtail app to the latest version, version 2.9, now since the wagtail site middleware has been deprecated I'm having trouble getting my site to work. I was using a request.site now  wagtail 2.9 uses Site._find_for_request(request)

How do I change my current code to work with the latest wagtail version? Thanks in advance

@register.simple_tag(takes_context=True)

def og_image(context, page):

protocol = re.compile(r'^(\w[\w\.\-\+]*:)*//')

if protocol.match(settings.MEDIA_URL):
    base_url = ''
else:
    base_url = context['request'].site.root_url

if page:
    if page.og_image:
        return base_url + page.og_image.get_rendition('original').url
    elif page.cover_image:
        return base_url + page.cover_image.get_rendition('original').url
if LayoutSettings.for_site(context['request'].site).logo:
    layout_settings = LayoutSettings.for_site(context['request'].site)
    return base_url + layout_settings.logo.get_rendition('original').url
return None

Body:
It looks like that you're still doing the old way of getting current site, in this case:

context['request'].site

where context['request'] is the request object. Change those occurrences to below as recommended in the Wagtail 2.9 release notes:

Site.find_for_request(context['request'])

Don't forget to make sure that you have from wagtail.core.models import Site somewhere on top of the file or else your code won't work, i.e. you get an error.

You can find more info on Site.find_for_request in the docs.


问:
How to apply different text formats to different text in python tkinter Text widget
I am writing a python code to create a RICH TEXT EDITOR in pythonmy python text editor. It has a bold button and all formating buttons like italic,fonts etc.

These buttons would format the selected text.

But the problem with all these buttons is that First when I bold the selected text, it is working fine but at the second time it applies the same format to the previously selected text

This is my code for the bold and italic function :

```<code>def boldtxt():
        bldbtn['activebackground']="#ffad33"
        contboxfont['weight']="bold"
        contbox.tag_add("bold",SEL_FIRST,SEL_LAST)
        contbox.tag_config("bold",font=contboxfont)
def italictxt():

itlbtn['activebackground']="#ffad33"
                contboxfont['slant']="italic"
                contbox.tag_add("italic",SEL_FIRST,SEL_LAST)
                contbox.tag_config("italic",font=contboxfont)
contbox=Text()
contbox.pack()
bldbtn=Button(comand=boldtxt)
bldbtn.pack()
itlbtn=Button(command=italictxt)
itlbtn.pack()
</code>```

I want that every word (or selected item should be formatted according to the user.
For ex.
if the bold button is pressed the selected text should be bold
and if the italic button is pressed then the selected text would be italic.
Thanks in advance :)

答: If you want each word to be uniquely formatted, they each need to have a unique tag. In your code, everything uses the "bold" tag, so if you change the "bold" tag, all of the words would change. If you don't want that, each word will need its own unique tag.

Body:
I am writing a python code to create a RICH TEXT EDITOR in pythonmy python text editor. It has a bold button and all formating buttons like italic,fonts etc.

These buttons would format the selected text.

But the problem with all these buttons is that First when I bold the selected text, it is working fine but at the second time it applies the same format to the previously selected text

This is my code for the bold and italic function :

def boldtxt():
        bldbtn['activebackground']="#ffad33"
        contboxfont['weight']="bold"
        contbox.tag_add("bold",SEL_FIRST,SEL_LAST)
        contbox.tag_config("bold",font=contboxfont)
def italictxt():

itlbtn['activebackground']="#ffad33"
                contboxfont['slant']="italic"
                contbox.tag_add("italic",SEL_FIRST,SEL_LAST)
                contbox.tag_config("italic",font=contboxfont)
contbox=Text()
contbox.pack()
bldbtn=Button(comand=boldtxt)
bldbtn.pack()
itlbtn=Button(command=italictxt)
itlbtn.pack()

I want that every word (or selected item should be formatted according to the user.
For ex.
if the bold button is pressed the selected text should be bold
and if the italic button is pressed then the selected text would be italic.
Thanks in advance :)


问:
XMLStartlet is not updating salesforce package.xml file
I want to create Salesforce Dynamic package.xml file. I followed the process mentioned in this apexandbeyond.wordpress.com/2017/03/15/dynamic-package-xml-generation/ blog, it is neither updating not inserting data in xml file. I am trying following way but i doesn't work for me. please help me on this.
Below code is in loop i need update xml file dynamically. Here i am getting modified file dynamically.

git diff-tree --no-commit-id --name-only --diff-filter=ACMRTUXB -t -r $PREVRSA $LCOMMIT | \
while read -r CFILE; do
    case "$CFILE"
        in
                .cls) TYPENAME="ApexClass";;
                .component) TYPENAME="ApexComponent";;
                .page) TYPENAME="ApexPage";;
                *) TYPENAME="UNKNOWN TYPE";;

```<code>    esac

    if [[ "$TYPENAME" != "UNKNOWN TYPE" ]]
    then
        echo $TYPENAME "," $ENTITY #example:(ApexClass,TestClass1
                                   #example: ApexClass,Testclass2
                                   #example: ApexPage,TestPage) # getting values Dynamically

       xmlstarlet edit -L --subnode "/Package/types[name=$TYPENAME]" --type elem -n members -v
         "$ENTITY" testpackage.xml > edipackage.xml

    fi
</code>```

done

echo Cleaning up Package.xml

xmlstarlet ed -L -i /Package -t attr -n xmlns -v "http://soap.sforce.com/2006/04/metadata" testpackage.xml > edipackage.xml

Original testpackage.xml file:

```<code><Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
<members>*</members>
<name>ApexClass</name>
</types>
<types>
<members>*</members>
<name>ApexComponent</name>
</types>
<types>
<members>*</members>
<name>ApexPage</name>
</types>
<version>48.0</version>
</Package>
</code>```

Expected Output:

```<code><Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
<members>TestClass1</members>
<members>TestClass2</members>
<name>ApexClass</name>
</types>
<types>
<members>TestPage</members>
<name>ApexPage</name>
</types>
<version>48.0</version>
</Package>
</code>```

Please help me on this.

答:
The namespace should be defined as follows:

xml sel -N x=http://soap.sforce.com/2006/04/metadata   -t -m //x:name -v . -n salesforce.xml

which returns:

```<code>ApexClass
ApexComponent
ApexPage
</code>```

Body:
I want to create Salesforce Dynamic package.xml file. I followed the process mentioned in this apexandbeyond.wordpress.com/2017/03/15/dynamic-package-xml-generation/ blog, it is neither updating not inserting data in xml file. I am trying following way but i doesn't work for me. please help me on this.
Below code is in loop i need update xml file dynamically. Here i am getting modified file dynamically.

git diff-tree --no-commit-id --name-only --diff-filter=ACMRTUXB -t -r $PREVRSA $LCOMMIT | \
while read -r CFILE; do
    case "$CFILE"
        in
                .cls) TYPENAME="ApexClass";;
                .component) TYPENAME="ApexComponent";;
                .page) TYPENAME="ApexPage";;
                *) TYPENAME="UNKNOWN TYPE";;

    esac

    if [[ "$TYPENAME" != "UNKNOWN TYPE" ]]
    then
        echo $TYPENAME "," $ENTITY #example:(ApexClass,TestClass1
                                   #example: ApexClass,Testclass2
                                   #example: ApexPage,TestPage) # getting values Dynamically

       xmlstarlet edit -L --subnode "/Package/types[name=$TYPENAME]" --type elem -n members -v
         "$ENTITY" testpackage.xml > edipackage.xml

    fi

done

echo Cleaning up Package.xml

xmlstarlet ed -L -i /Package -t attr -n xmlns -v "http://soap.sforce.com/2006/04/metadata" testpackage.xml > edipackage.xml

Original testpackage.xml file:

<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
<members>*</members>
<name>ApexClass</name>
</types>
<types>
<members>*</members>
<name>ApexComponent</name>
</types>
<types>
<members>*</members>
<name>ApexPage</name>
</types>
<version>48.0</version>
</Package>

Expected Output:

<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
<members>TestClass1</members>
<members>TestClass2</members>
<name>ApexClass</name>
</types>
<types>
<members>TestPage</members>
<name>ApexPage</name>
</types>
<version>48.0</version>
</Package>

Please help me on this.

Body:
The namespace should be defined as follows:

xml sel -N x=http://soap.sforce.com/2006/04/metadata   -t -m //x:name -v . -n salesforce.xml

which returns:

ApexClass
ApexComponent
ApexPage


问:
three.js weird artifacts overlapping box and plane
I'm seeing the weird behavior when at certain zoom levels / angles.

But at other positions it looks fine.

Can anyone tell me what's going on here, and how to fix it?

答:
Decreasing the far distance of the camera solved the problem:</p>

```<code>THREE.PerspectiveCamera(50, aspect, 100, 15000)
</code>```

Body:
Decreasing the far distance of the camera solved the problem:

THREE.PerspectiveCamera(50, aspect, 100, 15000)


问:
In Hello World flask app, Flask cannot find the app
I am running the minimal Hello World app from the Flask documentation. The code is below. I get no module named "flask.hello." The traceback is also below. I would like to know how to direct the flask to resolve the location of the app. The name of the source file is hello.py. I set

```<code>FLASK_APP='hello.py' and PYTHONPATH="."
</code>```

I start Flask with the command:

```<code>flask run --host=0.0.0.0 --port=3000

</code>```

```<code>from flask import Flask
app=Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello world!"
</code>```

```<code>Traceback (most recent call last):
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 240, in locate_app
    __import__(module_name)
ModuleNotFoundError: No module named 'flask.hello'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 338, in __call__
    self._flush_bg_loading_exception()
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 326, in _flush_bg_loading_exception
    reraise(*exc_info)
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 314, in _load_app
    self._load_unlocked()
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 330, in _load_unlocked
    self._app = rv = self.loader()
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 388, in load_app
    app = locate_app(self, import_name, name)
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 250, in locate_app
    raise NoAppException('Could not import "{name}".'.format(name=module_name))
flask.cli.NoAppException: Could not import "flask.hello".
</code>```

答:
Run it like this from the directory where you have hello.py:

FLASK_APP='hello.py' PYTHONPATH="." flask run --host=0.0.0.0 --port=3000
```

<p>There's a typo in your code:</p>

<pre class="lang-py prettyprint-override"><code>from flask import Flask
app=Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello world!'
</code>```

Body:
I am running the minimal Hello World app from the Flask documentation. The code is below. I get no module named "flask.hello." The traceback is also below. I would like to know how to direct the flask to resolve the location of the app. The name of the source file is hello.py. I set

FLASK_APP='hello.py' and PYTHONPATH="."

I start Flask with the command:

flask run --host=0.0.0.0 --port=3000

from flask import Flask
app=Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello world!"

Traceback (most recent call last):
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 240, in locate_app
    __import__(module_name)
ModuleNotFoundError: No module named 'flask.hello'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 338, in __call__
    self._flush_bg_loading_exception()
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 326, in _flush_bg_loading_exception
    reraise(*exc_info)
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 314, in _load_app
    self._load_unlocked()
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 330, in _load_unlocked
    self._app = rv = self.loader()
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 388, in load_app
    app = locate_app(self, import_name, name)
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 250, in locate_app
    raise NoAppException('Could not import "{name}".'.format(name=module_name))
flask.cli.NoAppException: Could not import "flask.hello".

Body:
Run it like this from the directory where you have hello.py:

FLASK_APP='hello.py' PYTHONPATH="." flask run --host=0.0.0.0 --port=3000

There's a typo in your code:

from flask import Flask
app=Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello world!'


问:
DolphinDB error: SegmentedTable does not support direct access. Please use sql query to retrieve data
```<code>dbDir = '/tests/dolphindb/valueDB'
devDir = '/tests/dolphindb/dev.csv'
db = database(dbDir)
dev = db.loadTable(`dev)
saveText(dev, devDir)
</code>```

I want to export table "dev" as 'csv' file but I encountered this error message:

```<code>Execution was completed with exception
SegmentedTable does not support direct access. Please use sql query to retrieve data
</code>```

I wonder if I have to load all data into memory to export it as 'csv' file.

答: Yes, the input table for saveText must be a non-partitioned table.

Body:
dbDir = '/tests/dolphindb/valueDB'
devDir = '/tests/dolphindb/dev.csv'
db = database(dbDir)
dev = db.loadTable(`dev)
saveText(dev, devDir)

I want to export table "dev" as 'csv' file but I encountered this error message:

Execution was completed with exception
SegmentedTable does not support direct access. Please use sql query to retrieve data

I wonder if I have to load all data into memory to export it as 'csv' file.


问:
Certain text not showing on my webpage, jQuery script to blame?
I'm trying to create a nice simple checkout form with a jquery script I got on the web and I seem to be facing a weird problem that could be due to a couple of things and I'm clueless as to how to fix this.

Maybe you can solve this... Below is my website in development:

[link removed]

If you look at the form (the light gray part that scrolls up and down), I have a list of cupcakes (around 30) that stretch all the way down the frame. My problem is that for no apparent reason the last 5 items don't show up, but if you look at the HTML everything is there.

The script I'm using is featureList : http://jqueryglobe.com/article/feature-list

Is this :

a jQuery limitation?

a
 limitation?

a featureList bug/limitation?

multiple ids tags on html limitation?

is it a stupid error and I've been looking at this code for too long?

How can I solve this?

Thanks

答: The last 5 elements have z-index:-60; set on them, if you change that to 0 they display normally. All the other elements have z-index of 0 as well.</p>


问:
In Java, how to print divisor numbers?
I want to print the divisors of a user input value between 1 and 10000.

```<code>import java.util.Scanner;

public class Divisors {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int Range;
        int Divisor;

        while(true) {

            System.out.print("Please insert a number between 1 and 10000: ");
            Range = scan.nextInt();

            if (Range < 1 || Range > 10000)
            System.out.println("Wrong choice");

            else
                break;
        }

        Divisor = 0;    // Start counting Divisor from Zero

        for (int loop = 1; loop <= Range; loop++) {
            if (Range % loop == 0)
                Divisor++;
                System.out.println("loop);
            }

        System.out.println("Total number of divisors of " + Range + " is " + Divisor);

    }
}
</code>```

I have problem here with command System.out.println("loop);.
  I want to print all the divisors, like if a user inserted 10, then the
  output should show something like:

!

```<code>Please insert a number between 1 and 10000: 10
1
2
5
10
Total number of divisors of 10 is 4
</code>```

!
!

But the current output is:

!

```<code>Please insert a number between 1 and 10000: 10
1
2
3
4
5
6
7
8
9
10
Total number of divisors of 10 is 4
</code>```

!
!

so how to print loop only when the (Range % loop == 0) is true??

答:
Any conditional statement will execute subsequent one line if you do not include curly braces. If you want to execute more than one statement inside if block, include those statements inside curly braces.
Example: </p>

```<code>    If(Condition)
{
Statement1;
Statement2;
}
</code>```

Title: In Java, how to print divisor numbers?

Body:
I want to print the divisors of a user input value between 1 and 10000.

import java.util.Scanner;

public class Divisors {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int Range;
        int Divisor;

        while(true) {

            System.out.print("Please insert a number between 1 and 10000: ");
            Range = scan.nextInt();

            if (Range < 1 || Range > 10000)
            System.out.println("Wrong choice");

            else
                break;
        }

        Divisor = 0;    // Start counting Divisor from Zero

        for (int loop = 1; loop <= Range; loop++) {
            if (Range % loop == 0)
                Divisor++;
                System.out.println("loop);
            }

        System.out.println("Total number of divisors of " + Range + " is " + Divisor);

    }
}

I have problem here with command System.out.println("loop);.
  I want to print all the divisors, like if a user inserted 10, then the
  output should show something like:

!

Please insert a number between 1 and 10000: 10
1
2
5
10
Total number of divisors of 10 is 4

!
!

But the current output is:

!

Please insert a number between 1 and 10000: 10
1
2
3
4
5
6
7
8
9
10
Total number of divisors of 10 is 4

!
!

so how to print loop only when the (Range % loop == 0) is true??

Body:
Any conditional statement will execute subsequent one line if you do not include curly braces. If you want to execute more than one statement inside if block, include those statements inside curly braces.
Example:

    If(Condition)
{
Statement1;
Statement2;
}


问:
R BootStrap With Strata
I learned how to do bootstrap regression. Here is my example and Code.

```<code>   library(boot)
    sampledata = data.frame(y = sample(0:20, r = T, size = 5000),
                            x1 = runif(5000),
                            x2 = runif(5000),
                            group1 = sample(1:3, r = T, size = 5000),
                            group2 = sample(0:1, r = T, size = 5000))

# function to obtain R-Squared from the data
rsq <- function(formula, data, indices) {
  d <- data[indices,]
  fit <- lm(formula, data=d)
  return(coef(fit))
}

# bootstrapping with 250 replications
results <- boot(data=sampledata, statistic=rsq,
   R=250, formula=y~x1+x2)
df <- data.frame(results$t)
names(df) <- names(results$t0)
</code>```

However if you want to do this process for subgroups of your data how can you make it more automated? This is what I hope to do but this is very tiresome and I have many more group categories but this is basically the hopeful result, basically I subset the sampledata into 6 groups and then use all those data sets separate in 6 different bootstrap models and then combine the results in DATA. I see boot has strata feature but am not getting it to function. Also are you supposed to subset your data to group and then do the bootstrap sample? Or get a bootstrap sample and then subset your data? Any way, I am wondering how can it be possible to make this more automatic where I can code the program to do the bootstrap estimate for all groups separately, where the models are stratified.

```<code>sampledata1 = subset(sampledata, group1 == 1 & group2 == 0)
sampledata2 = subset(sampledata, group1 == 2 & group2 == 0)
sampledata3 = subset(sampledata, group1 == 3 & group2 == 0)
sampledata4 = subset(sampledata, group1 == 1 & group2 == 1)
sampledata5 = subset(sampledata, group1 == 2 & group2 == 1)
sampledata6 = subset(sampledata, group1 == 3 & group2 == 1)

# bootstrapping with 250 replications
results <- boot(data=sampledata1, statistic=rsq,
   R=250, formula=y~x1+x2)
df1 <- data.frame(results$t)
names(df1) <- names(results$t0)
df1$group1 = 1
df1$group2 = 0

# bootstrapping with 250 replications
results <- boot(data=sampledata2, statistic=rsq,
   R=250, formula=y~x1+x2)
df2 <- data.frame(results$t)
names(df2) <- names(results$t0)
df2$group1 = 2
df2$group2 = 0

# bootstrapping with 250 replications
results <- boot(data=sampledata3, statistic=rsq,
   R=250, formula=y~x1+x2)
df3 <- data.frame(results$t)
names(df3) <- names(results$t0)
df3$group1 = 3
df3$group2 = 0

# bootstrapping with 250 replications
results <- boot(data=sampledata4, statistic=rsq,
   R=250, formula=y~x1+x2)
df4 <- data.frame(results$t)
names(df4) <- names(results$t0)
df4$group1 = 1
df4$group2 = 1

# bootstrapping with 250 replications
results <- boot(data=sampledata5, statistic=rsq,
   R=250, formula=y~x1+x2)
df5 <- data.frame(results$t)
names(df5) <- names(results$t0)
df5$group1 = 2
df5$group2 = 1

# bootstrapping with 250 replications
results <- boot(data=sampledata6, statistic=rsq,
   R=250, formula=y~x1+x2)
df6 <- data.frame(results$t)
names(df6) <- names(results$t0)
df6$group1 = 3
df6$group2 = 1

DATA = rbind(df1, df2, df3, df4, df5, df6)
</code>```

```<code>rsq <- function(formula, data, indices) {
  dataSUB <- data %>% filter(GROUP1 == group1, GROUP2 == group2)
  d <- dataSUB[indices,]
  fit <- lm(formula, data=d)
  return(coef(fit))
}
</code>```

答:
This should do the trick:

```<code>set1 <- c(1,2,3)
set2 <- c(0,1)
for(i in set1) {
    for(j in set2) {
        sampleDataSet = subset(sampledata, group1 == i & group2 == j)
        results <- boot(data=sampleDataSet, statistic=rsq, R=250, formula=y~x1+x2)
        df <- data.frame(results$t)
        names(df) <- names(results$t0)
        df$group1 = i
        df$group2 = j
        assign(paste("df",i+(j*length(set1)),sep=""), df)
    }
}
</code>```

Note:  if you plan to do this with larger groups, assuming 0 is always in set2 you can just update set1 and set2 and the naming scheme should continue to work.

I hope this helps!

Title: R BootStrap With Strata

Body:
I learned how to do bootstrap regression. Here is my example and Code.

   library(boot)
    sampledata = data.frame(y = sample(0:20, r = T, size = 5000),
                            x1 = runif(5000),
                            x2 = runif(5000),
                            group1 = sample(1:3, r = T, size = 5000),
                            group2 = sample(0:1, r = T, size = 5000))

# function to obtain R-Squared from the data
rsq <- function(formula, data, indices) {
  d <- data[indices,]
  fit <- lm(formula, data=d)
  return(coef(fit))
}

# bootstrapping with 250 replications
results <- boot(data=sampledata, statistic=rsq,
   R=250, formula=y~x1+x2)
df <- data.frame(results$t)
names(df) <- names(results$t0)

However if you want to do this process for subgroups of your data how can you make it more automated? This is what I hope to do but this is very tiresome and I have many more group categories but this is basically the hopeful result, basically I subset the sampledata into 6 groups and then use all those data sets separate in 6 different bootstrap models and then combine the results in DATA. I see boot has strata feature but am not getting it to function. Also are you supposed to subset your data to group and then do the bootstrap sample? Or get a bootstrap sample and then subset your data? Any way, I am wondering how can it be possible to make this more automatic where I can code the program to do the bootstrap estimate for all groups separately, where the models are stratified.

sampledata1 = subset(sampledata, group1 == 1 & group2 == 0)
sampledata2 = subset(sampledata, group1 == 2 & group2 == 0)
sampledata3 = subset(sampledata, group1 == 3 & group2 == 0)
sampledata4 = subset(sampledata, group1 == 1 & group2 == 1)
sampledata5 = subset(sampledata, group1 == 2 & group2 == 1)
sampledata6 = subset(sampledata, group1 == 3 & group2 == 1)

# bootstrapping with 250 replications
results <- boot(data=sampledata1, statistic=rsq,
   R=250, formula=y~x1+x2)
df1 <- data.frame(results$t)
names(df1) <- names(results$t0)
df1$group1 = 1
df1$group2 = 0

# bootstrapping with 250 replications
results <- boot(data=sampledata2, statistic=rsq,
   R=250, formula=y~x1+x2)
df2 <- data.frame(results$t)
names(df2) <- names(results$t0)
df2$group1 = 2
df2$group2 = 0

# bootstrapping with 250 replications
results <- boot(data=sampledata3, statistic=rsq,
   R=250, formula=y~x1+x2)
df3 <- data.frame(results$t)
names(df3) <- names(results$t0)
df3$group1 = 3
df3$group2 = 0

# bootstrapping with 250 replications
results <- boot(data=sampledata4, statistic=rsq,
   R=250, formula=y~x1+x2)
df4 <- data.frame(results$t)
names(df4) <- names(results$t0)
df4$group1 = 1
df4$group2 = 1

# bootstrapping with 250 replications
results <- boot(data=sampledata5, statistic=rsq,
   R=250, formula=y~x1+x2)
df5 <- data.frame(results$t)
names(df5) <- names(results$t0)
df5$group1 = 2
df5$group2 = 1

# bootstrapping with 250 replications
results <- boot(data=sampledata6, statistic=rsq,
   R=250, formula=y~x1+x2)
df6 <- data.frame(results$t)
names(df6) <- names(results$t0)
df6$group1 = 3
df6$group2 = 1

DATA = rbind(df1, df2, df3, df4, df5, df6)

rsq <- function(formula, data, indices) {
  dataSUB <- data %>% filter(GROUP1 == group1, GROUP2 == group2)
  d <- dataSUB[indices,]
  fit <- lm(formula, data=d)
  return(coef(fit))
}

Body:
This should do the trick:

set1 <- c(1,2,3)
set2 <- c(0,1)
for(i in set1) {
    for(j in set2) {
        sampleDataSet = subset(sampledata, group1 == i & group2 == j)
        results <- boot(data=sampleDataSet, statistic=rsq, R=250, formula=y~x1+x2)
        df <- data.frame(results$t)
        names(df) <- names(results$t0)
        df$group1 = i
        df$group2 = j
        assign(paste("df",i+(j*length(set1)),sep=""), df)
    }
}

Note:  if you plan to do this with larger groups, assuming 0 is always in set2 you can just update set1 and set2 and the naming scheme should continue to work.

I hope this helps!


问:
Convert Newtosoft JObject directly to BsonDocument
Try to convert JObject to BsonDocument using this example https://www.newtonsoft.com/json/help/html/WriteJTokenToBson.htm (BsonWriter obsolete, so I use BsonDataWriter)

```<code>var jObject = JObject.Parse("{\"name\":\"value\"}");

using var writer = new BsonDataWriter(new MemoryStream());
jObject.WriteTo(writer);

var bsonData = writer.ToBsonDocument();

Console.WriteLine(bsonData.ToJson());
</code>```

output:

```<code>{ "CloseOutput" : true, "AutoCompleteOnClose" : true, "Formatting" : 0, "DateFormatHandling" : 0, "DateTimeZoneHandling" : 3, "StringEscapeHandling" : 0, "FloatFormatHandling" : 0, "DateFormatString" : null
, "Culture" : { "Name" : "", "UseUserOverride" : false }, "DateTimeKindHandling" : 1 }

</code>```

Expected output is:

```<code>{"name": "value"}
</code>```

How can I fix it?

UPD: I have a JObject, and I want to convert it directly to BSONDocument, avoid serialization to string and string parsing

答:
You can write a JObject to a BSON stream using Newtonsoft's BsonDataWriter like so:

```<code>var json = "{\"name\":\"value\"}";
var jObject = JObject.Parse(json);

using var stream = new MemoryStream(); // Or open a FileStream if you prefer
using (var writer = new BsonDataWriter(stream) { CloseOutput = false })
{
    jObject.WriteTo(writer);
}
// Reset the stream position to 0 if you are going to immediately re-read it.
stream.Position = 0;
</code>```

Then, you can parse the written stream with the MongoDB .NET Driver like so:

```<code>// Parse the BSON using the MongoDB driver
BsonDocument bsonData;
using (var reader = new BsonBinaryReader(stream))
{
    var context = BsonDeserializationContext.CreateRoot(reader);
    bsonData = BsonDocumentSerializer.Instance.Deserialize(context);
}
</code>```

And check the validity of the created document like so:

```<code>// Verify that the BsonDocument is semantically identical to the original JSON.
// Write it to JSON using the MongoDB driver
var newJson = bsonData.ToJson();

Console.WriteLine(newJson); // Prints { "name" : "value" }

// And assert that the old and new JSON are semantically identical
Assert.IsTrue(JToken.DeepEquals(JToken.Parse(json), JToken.Parse(newJson))); // Passes
</code>```

Notes:

When you do var bsonData = writer.ToBsonDocument(); you are actually serializing Newtonsoft's BsonDataWriter using the MongoDB extension method BsonExtensionMethods.ToBsonDocument(), which explains the strange contents of the bsonData document in your test code.

Instead, the serialized BSON can be obtained from the stream to which it was just written.

If you are going to immediately re-read the stream, you can keep it open by setting JsonWriter.CloseOutput = false.  Set the stream position to 0 after writing.

While your approach avoids the overhead of serializing and parsing a JSON string, you are still serializing and deserializing a BSON binary stream.

Demo fiddle here.

Body:
Try to convert JObject to BsonDocument using this example https://www.newtonsoft.com/json/help/html/WriteJTokenToBson.htm (BsonWriter obsolete, so I use BsonDataWriter)

var jObject = JObject.Parse("{\"name\":\"value\"}");

using var writer = new BsonDataWriter(new MemoryStream());
jObject.WriteTo(writer);

var bsonData = writer.ToBsonDocument();

Console.WriteLine(bsonData.ToJson());

output:

{ "CloseOutput" : true, "AutoCompleteOnClose" : true, "Formatting" : 0, "DateFormatHandling" : 0, "DateTimeZoneHandling" : 3, "StringEscapeHandling" : 0, "FloatFormatHandling" : 0, "DateFormatString" : null
, "Culture" : { "Name" : "", "UseUserOverride" : false }, "DateTimeKindHandling" : 1 }

Expected output is:

{"name": "value"}

How can I fix it?

UPD: I have a JObject, and I want to convert it directly to BSONDocument, avoid serialization to string and string parsing

Body:
You can write a JObject to a BSON stream using Newtonsoft's BsonDataWriter like so:

var json = "{\"name\":\"value\"}";
var jObject = JObject.Parse(json);

using var stream = new MemoryStream(); // Or open a FileStream if you prefer
using (var writer = new BsonDataWriter(stream) { CloseOutput = false })
{
    jObject.WriteTo(writer);
}
// Reset the stream position to 0 if you are going to immediately re-read it.
stream.Position = 0;

Then, you can parse the written stream with the MongoDB .NET Driver like so:

// Parse the BSON using the MongoDB driver
BsonDocument bsonData;
using (var reader = new BsonBinaryReader(stream))
{
    var context = BsonDeserializationContext.CreateRoot(reader);
    bsonData = BsonDocumentSerializer.Instance.Deserialize(context);
}

And check the validity of the created document like so:

// Verify that the BsonDocument is semantically identical to the original JSON.
// Write it to JSON using the MongoDB driver
var newJson = bsonData.ToJson();

Console.WriteLine(newJson); // Prints { "name" : "value" }

// And assert that the old and new JSON are semantically identical
Assert.IsTrue(JToken.DeepEquals(JToken.Parse(json), JToken.Parse(newJson))); // Passes

Notes:

When you do var bsonData = writer.ToBsonDocument(); you are actually serializing Newtonsoft's BsonDataWriter using the MongoDB extension method BsonExtensionMethods.ToBsonDocument(), which explains the strange contents of the bsonData document in your test code.

Instead, the serialized BSON can be obtained from the stream to which it was just written.

If you are going to immediately re-read the stream, you can keep it open by setting JsonWriter.CloseOutput = false.  Set the stream position to 0 after writing.

While your approach avoids the overhead of serializing and parsing a JSON string, you are still serializing and deserializing a BSON binary stream.

Demo fiddle here.


问:
Implementing events in C++
After some research on internet for an efficient way to implement events in C++, I found the following methods

Interface class - Applications can override the virtual functions in the derived class

Normal Callback mechanism using function pointers

Delegates using Boost.function

Signals and slots (as used in Qt)

I am confused on advantages and disadvantages of each of these and when to use anyone of this.
Which is the best method and why?
Is there any other solutions which are better than the ones listed?

答:
Have you checked GBL library? It has all facilities that you might need (and probably more) for even-driven design. You can build (real) timed and un-timed models with it. It's pure C++, not polluted with macros. It also makes use of C++0x for improved performance. Also if you use C++0x compiler you get lambda functions working as event handlers -- it's very powerful. GBL supports synchronous and asynchronous event handlers, threads, and fibers. It abstracts event flow via signals and ports. With some ingenuity and careful design you can use asynchronous event handlers and significantly improve performance on multicore/multiprocessor systems. It also has a graphical designer and tracer.

Building and maintaining event-driven applications can be very difficult without visualization, designer helps with that a lot. Debugging event-driven applications can also be very difficult, because you no longer have a sequential execution, rather the execution is jumping from one event handler to another, so having an event tracer helps significantly.

Title: Implementing events in C++


问:
Raise INVALID_CURSOR exception when you access the cursor variable %ROWCOUNT after the cursor is closed
So I am using the following table in oracle

```<code> EMPNO ENAME                DEPTN JOB                  HIREDDATE     SALARY
------ -------------------- ----- -------------------- --------- ----------
   111 Narayan              R22   Electrical           26-DEC-99       5000
   108 Horen                P69   PWD                  10-DEC-95      10000
   130 Roy                  A13   Security             15-SEP-01      25000
   420 Roy                  D12   IT                   15-SEP-99       2500
   100 Allu                 A13   Security             26-JAN-15      15000
</code>```

And I was trying to use the EName to rowcount.

```<code>SQL> DECLARE
  2     temp varchar(20);
  3  BEGIN
  4     SELECT EName into temp from Employee01;
  5     dbms_output.put_line(temp);
  6  EXCEPTION
  7     WHEN too_many_rows THEN
  8     dbms_output.put_line('error trying to SELECT too many rows');
  9  END;
 10  /
</code>```

I was trying to modify this code.

答:
Well, it would help if you posted code you modified, not something that is irrelevant to the question.

Here you go:

line #15 - cursor is closed

line #17 - using c1%rowcount on closed cursor

lines #19-21 - handling INVALID_CURSOR exception; I'm just displaying a message, you'd probably do something smarter

```<code>SQL> set serveroutput on
SQL> declare
  2    cursor c1 is
  3      select empno, ename, job
  4      from emp
  5      where deptno = 10;
  6    c1r     c1%rowtype;
  7    l_cnt   number;
  8  begin
  9    open c1;
 10    loop
 11      fetch c1 into c1r;
 12      exit when c1%notfound;
 13      dbms_output.put_line(c1r.ename ||' - '|| c1r.job);
 14    end loop;
 15    close c1;
 16
 17    l_cnt := c1%rowcount;
 18
 19  exception
 20    when invalid_cursor then
 21      dbms_output.put_line('INVALID_CURSOR has been raised');
 22  end;
 23  /
CLARK - MANAGER
KING - PRESIDENT
MILLER - CLERK
INVALID_CURSOR has been raised

PL/SQL procedure successfully completed.

SQL>
</code>```

Body:
So I am using the following table in oracle

 EMPNO ENAME                DEPTN JOB                  HIREDDATE     SALARY
------ -------------------- ----- -------------------- --------- ----------
   111 Narayan              R22   Electrical           26-DEC-99       5000
   108 Horen                P69   PWD                  10-DEC-95      10000
   130 Roy                  A13   Security             15-SEP-01      25000
   420 Roy                  D12   IT                   15-SEP-99       2500
   100 Allu                 A13   Security             26-JAN-15      15000

And I was trying to use the EName to rowcount.

SQL> DECLARE
  2     temp varchar(20);
  3  BEGIN
  4     SELECT EName into temp from Employee01;
  5     dbms_output.put_line(temp);
  6  EXCEPTION
  7     WHEN too_many_rows THEN
  8     dbms_output.put_line('error trying to SELECT too many rows');
  9  END;
 10  /

I was trying to modify this code.

Body:
Well, it would help if you posted code you modified, not something that is irrelevant to the question.

Here you go:

line #15 - cursor is closed

line #17 - using c1%rowcount on closed cursor

lines #19-21 - handling INVALID_CURSOR exception; I'm just displaying a message, you'd probably do something smarter

SQL> set serveroutput on
SQL> declare
  2    cursor c1 is
  3      select empno, ename, job
  4      from emp
  5      where deptno = 10;
  6    c1r     c1%rowtype;
  7    l_cnt   number;
  8  begin
  9    open c1;
 10    loop
 11      fetch c1 into c1r;
 12      exit when c1%notfound;
 13      dbms_output.put_line(c1r.ename ||' - '|| c1r.job);
 14    end loop;
 15    close c1;
 16
 17    l_cnt := c1%rowcount;
 18
 19  exception
 20    when invalid_cursor then
 21      dbms_output.put_line('INVALID_CURSOR has been raised');
 22  end;
 23  /
CLARK - MANAGER
KING - PRESIDENT
MILLER - CLERK
INVALID_CURSOR has been raised

PL/SQL procedure successfully completed.

SQL>


问:
What is a difference in Java between class B<T> extends A<T> and class B<T> extends A
What is the difference between:

```<code>// 1
class A<T>
class B<T> extends A
</code>```

and

```<code>// 2
class A<T>
class B<T> extends A<T>

</code>```

Is 1 related to the Raw Types like:

```<code>List list = new ArrayList<Integer>();

</code>```

whereas 2 is a preferred form
?

答:
The first one extends the raw type. There is no way then in B to say what type T in class A should be. T in A and T in B are unrelated.

The second one extends A<T>. So T in A and T in B refer to the same type.

Body:
What is the difference between:

// 1
class A<T>
class B<T> extends A

and

// 2
class A<T>
class B<T> extends A<T>

Is 1 related to the Raw Types like:

List list = new ArrayList<Integer>();

whereas 2 is a preferred form
?


问:
VisualDensity is undefined?
I've installed this package login_screen package in flutter that should unlock the visualDensity in Theme Data in flutter but It doesn't but I checked the import and package version and everything but It always give me error that It is undefined.
Here is my code :
pubspec.yaml file:
environment:
  sdk: ">=2.7.0 <3.0.0"

```<code>dependencies:
  flutter:
    sdk: flutter
  flutter_svg: ^0.17.4
  firebase_core: ^0.4.3+1
  firebase_auth: ^0.15.3
  modal_progress_hud: ^0.1.3
  confetti: ^0.4.0
  login_screen: ^0.6.0

dev_dependencies:
  flutter_test:
    sdk: flutter
</code>```

and my main.dart file:

```<code>import 'package:flutter/material.dart';
import 'package:loginkit/ui/login/login.dart';
import 'package:login_screen/login_screen.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        fontFamily: 'Poppins',
        visualDensity:
      ),
      debugShowCheckedModeBanner: false,
      home: Login(),
    );
  }
}
</code>```

答: For me, to fix this issue, I had to run Tools, Flutter, Flutter Upgrade in Android Studio.

Title: VisualDensity is undefined?

Body:
I've installed this package login_screen package in flutter that should unlock the visualDensity in Theme Data in flutter but It doesn't but I checked the import and package version and everything but It always give me error that It is undefined.
Here is my code :
pubspec.yaml file:
environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  flutter_svg: ^0.17.4
  firebase_core: ^0.4.3+1
  firebase_auth: ^0.15.3
  modal_progress_hud: ^0.1.3
  confetti: ^0.4.0
  login_screen: ^0.6.0

dev_dependencies:
  flutter_test:
    sdk: flutter

and my main.dart file:

import 'package:flutter/material.dart';
import 'package:loginkit/ui/login/login.dart';
import 'package:login_screen/login_screen.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        fontFamily: 'Poppins',
        visualDensity:
      ),
      debugShowCheckedModeBanner: false,
      home: Login(),
    );
  }
}


问:
Multiple database drivers scenario: passing interface as type
Scenario: I've got a database type implementing a number of CRUD operations.

I would like to:

abstract away the database layer to support multiple databases

put a cache layer "in front of it" as read-through cache

So my idea was to:

create a database interface for both postgres specific code, and the cache

pass the postgres type to the cache constructor so it can use it to from the database

See below for what I tried, resulting in an error for cacheNew() when assigning :

cannot use dbdriver (variable of type interface{}) as database value in struct literal: missing method GetUser

What is the best way to solve this?

```<code>package main

import "fmt"

type database interface {
    GetUser(string)
}

type postgres struct {
    hostname string
}

func (p *postgres) GetUser(u string) {
    fmt.Printf("Postgres: GetUser %s\n", u)
}

type cache struct {
    db database
}

func cacheNew(dbdriver interface{}) cache {
    return cache{
        db: dbdriver,
    }
}

func (c *cache) GetUser(u string) {
    fmt.Printf("Cache: GetUser %s\n", u)

    c.db.GetUser(u)
}

func main() {
    // var db database

    db := postgres{
        hostname: "x",
    }
    db.GetUser("joe")

    dbViaCache := cacheNew(db)
    dbViaCache.GetUser("joe")
}
</code>```

答:
Use database instead of interface{} in cacheNew function

```<code>func cacheNew(dbdriver database) cache {
</code>```

postgres does not implement database since GetUser method has pointer receiver. So, send the address of postgres type variable in cacheNew

```<code>dbViaCache := cacheNew(&db)
</code>```

Body:
Scenario: I've got a database type implementing a number of CRUD operations.

I would like to:

abstract away the database layer to support multiple databases

put a cache layer "in front of it" as read-through cache

So my idea was to:

create a database interface for both postgres specific code, and the cache

pass the postgres type to the cache constructor so it can use it to from the database

See below for what I tried, resulting in an error for cacheNew() when assigning :

cannot use dbdriver (variable of type interface{}) as database value in struct literal: missing method GetUser

What is the best way to solve this?

package main

import "fmt"

type database interface {
    GetUser(string)
}

type postgres struct {
    hostname string
}

func (p *postgres) GetUser(u string) {
    fmt.Printf("Postgres: GetUser %s\n", u)
}

type cache struct {
    db database
}

func cacheNew(dbdriver interface{}) cache {
    return cache{
        db: dbdriver,
    }
}

func (c *cache) GetUser(u string) {
    fmt.Printf("Cache: GetUser %s\n", u)

    c.db.GetUser(u)
}

func main() {
    // var db database

    db := postgres{
        hostname: "x",
    }
    db.GetUser("joe")

    dbViaCache := cacheNew(db)
    dbViaCache.GetUser("joe")
}

Body:
Use database instead of interface{} in cacheNew function

func cacheNew(dbdriver database) cache {

postgres does not implement database since GetUser method has pointer receiver. So, send the address of postgres type variable in cacheNew

dbViaCache := cacheNew(&db)


答:
If you dig into the HTML, you can see the z-index is -30

```<code><td id="saveursqte_box_26">
    <div class="t" style="z-index: -30; ">Vanille-café
        <div class="r" style="z-index: -40; ">
            <div class="a" style="z-index: -50; "></div>
            <img src="777/galeries/g21_i41_2.jpg" border="0">
        </div>
    </div>
</td>
</code>```

and the  below it has a z-index of -60.

I'm having a looking into the JS to see if I can work out where the z-indexes are being changed, maybe you know?

Title: Certain text not showing on my webpage, jQuery script to blame?

Body:
I'm trying to create a nice simple checkout form with a jquery script I got on the web and I seem to be facing a weird problem that could be due to a couple of things and I'm clueless as to how to fix this.

Maybe you can solve this... Below is my website in development:

[link removed]

If you look at the form (the light gray part that scrolls up and down), I have a list of cupcakes (around 30) that stretch all the way down the frame. My problem is that for no apparent reason the last 5 items don't show up, but if you look at the HTML everything is there.

The script I'm using is featureList : http://jqueryglobe.com/article/feature-list

Is this :

a jQuery limitation?

a
 limitation?

a featureList bug/limitation?

multiple ids tags on html limitation?

is it a stupid error and I've been looking at this code for too long?

How can I solve this?

Thanks

Body:
If you dig into the HTML, you can see the z-index is -30

<td id="saveursqte_box_26">
    <div class="t" style="z-index: -30; ">Vanille-café
        <div class="r" style="z-index: -40; ">
            <div class="a" style="z-index: -50; "></div>
            <img src="777/galeries/g21_i41_2.jpg" border="0">
        </div>
    </div>
</td>

and the <td> below it has a z-index of -60.

I'm having a looking into the JS to see if I can work out where the z-indexes are being changed, maybe you know?


问:
shell script to convert rows to columns
I have a text file with the following format

```<code> Type: XTREMIO
  UID: 51,4f,0c,51,9d,00,05,22
  Vendor: XtremIO
  Product: XtremApp
  Size: 10.00 GB
  Name: knocknarea_jounal
  Replication info: [rpa_A, RPA_B, knocknarea_jounal]
  Array Serial: CKM00150400153
  RPA To volume paths map: None

 Type: XTREMIO
  UID: 51,4f,0c,51,9d,00,05,28
  Vendor: XtremIO
  Product: XtremApp
  Size: 5.00 GB
  Name: test_rep
  Replication info: N/A
  Array Serial: CKM00150400153
  RPA To volume paths map: None
</code>```

My objective is to convert those block into row like this with a delimiter:

```<code>XTREMIO;51,4f,0c,51,9d,00,05,28;XtremIO;XtremApp;5.00 GB;test_rep;CKM00150400153
</code>```

答:
Normally, you should post the code you have written up to know, even if it is not working, so that we can help you instead of working in place of you.

However, there is trivial solution calling awk twice. Assuming your input file is called input, you could try/

```<code>awk 'BEGIN{FS = ": "}{print $2}' input | awk 'BEGIN{RS = ""; FS = "\n"; OFS = ";"}{print $1, $2, $3, $4, $5, $6, $8}'
</code>```

Output:

```<code>XTREMIO;51,4f,0c,51,9d,00,05,22;XtremIO;XtremApp;10.00 GB;knocknarea_jounal;CKM00150400153
XTREMIO;51,4f,0c,51,9d,00,05,28;XtremIO;XtremApp;5.00 GB;test_rep;CKM00150400153
</code>```

Explanation: the first instance of awk is removing everything in the begin of each line until and including the string ": ".

The second one is using the paragraph mode of awk setting the record separator RS to the null string, which means that a record is each set of lines with no blank line, and sets the field separator FS to a newline character. It reads records and outputs the fields as they are, but changing the field separator and the record separator into resp. ";" and a single newline (option by default for ORS).

Title: shell script to convert rows to columns

Body:
I have a text file with the following format

 Type: XTREMIO
  UID: 51,4f,0c,51,9d,00,05,22
  Vendor: XtremIO
  Product: XtremApp
  Size: 10.00 GB
  Name: knocknarea_jounal
  Replication info: [rpa_A, RPA_B, knocknarea_jounal]
  Array Serial: CKM00150400153
  RPA To volume paths map: None

 Type: XTREMIO
  UID: 51,4f,0c,51,9d,00,05,28
  Vendor: XtremIO
  Product: XtremApp
  Size: 5.00 GB
  Name: test_rep
  Replication info: N/A
  Array Serial: CKM00150400153
  RPA To volume paths map: None

My objective is to convert those block into row like this with a delimiter:

XTREMIO;51,4f,0c,51,9d,00,05,28;XtremIO;XtremApp;5.00 GB;test_rep;CKM00150400153

Body:
Normally, you should post the code you have written up to know, even if it is not working, so that we can help you instead of working in place of you.

However, there is trivial solution calling awk twice. Assuming your input file is called input, you could try/

awk 'BEGIN{FS = ": "}{print $2}' input | awk 'BEGIN{RS = ""; FS = "\n"; OFS = ";"}{print $1, $2, $3, $4, $5, $6, $8}'

Output:

XTREMIO;51,4f,0c,51,9d,00,05,22;XtremIO;XtremApp;10.00 GB;knocknarea_jounal;CKM00150400153
XTREMIO;51,4f,0c,51,9d,00,05,28;XtremIO;XtremApp;5.00 GB;test_rep;CKM00150400153

Explanation: the first instance of awk is removing everything in the begin of each line until and including the string ": ".

The second one is using the paragraph mode of awk setting the record separator RS to the null string, which means that a record is each set of lines with no blank line, and sets the field separator FS to a newline character. It reads records and outputs the fields as they are, but changing the field separator and the record separator into resp. ";" and a single newline (option by default for ORS).


问:
How does the light PropsType affect the CSS in reactstrap?
I am learning React via the course on Coursera. Here is the part where the tutor didn't mention how we can utilize the below "special" mechanism for CSS styling.

In my HeaderComponent.js file, the tutor pass the data as props to the Navbar pre-built component as below.

```<code>...
<Navbar light expand="md">
...
</Navbar>
...
</code>```

Below is the documentation of Navbar properties(Link)

```<code>Navbar.propTypes = {
  light: PropTypes.bool,
  dark: PropTypes.bool,
  fixed: PropTypes.string,
  color: PropTypes.string,
  role: PropTypes.string,
  expand: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]),
  tag: PropTypes.oneOfType([PropTypes.func, PropTypes.string])
  // pass in custom element to use
}
</code>```

In the App.css file

```<code>.navbar-light {
  background-color: rgb(211, 81, 81);
}
</code>```

To my surprise, this CSS selector works! From what I knew, to use a class in JSX we should use classNama="navbar-light" in the Navbar tag.

I would like to learn more about this, how can I utilize this mechanism?
For example, if I have a Card reactstrap component, can I use <Card body> then in CSS

```<code>.card-body{
  background-color: rgb(211, 81, 81);
}
</code>```

since the body prop is bool type as well as below

```<code>Card.propTypes = {
  // Pass in a Component to override default element
  tag: PropTypes.oneOfType([PropTypes.func, PropTypes.string]),
  inverse: PropTypes.bool,
  color: PropTypes.string,
  body: PropTypes.bool,
  className: PropTypes.string
};
</code>```

to specify the color of the Card? I can't find any guide online on how to utilize this mechanism.
Thanks in advance.

答:
reactstrap uses a utility called classnames which helps you construct a list of class names.

Example:

```<code>const classes = classnames("class1", "class2");

// `classes` is set to the string "class1 class2"
// Not so useful yet, but read on ...
</code>```

It also lets you perform boolean checks to decide whether to include a class or not.

The following example creates a string of class names that contains the class card-base, and card-large if large is true.

```<code>const classes = classnames(
  "card-base",
  "card-large": large,
);

// If `large` evaluates to `true`, this will result in "card-base card-large"
</code>```

large can be passed in as a prop. Here's a working example:

import classnames from "classnames";

const Card = ({ large, className }) => {
  const classes = classnames(
    className, // Keep the classes that are passed in with the `className` prop
    "card-base",
    "card-large": large,
  );

  return
... rest of the component ...

}

// Validate the props:
Card.propTypes = {
  large: PropTypes.bool,
  className: PropTypes.string // The user can still provide their own classes
};
```

Remember to install the classnames package first: npm install classnames.

PropTypes is used to validate the data a component receives. You add the propTypes property to a component with a list of props and their expected datatypes, and warnings will be shown in the JavaScript console if any validations fail. Prop types have nothing directly to do with CSS or class names. It's a safety mechanism that adds no additional behavior.

Body:
I am learning React via the course on Coursera. Here is the part where the tutor didn't mention how we can utilize the below "special" mechanism for CSS styling.

In my HeaderComponent.js file, the tutor pass the data as props to the Navbar pre-built component as below.

...
<Navbar light expand="md">
...
</Navbar>
...

Below is the documentation of Navbar properties(Link)

Navbar.propTypes = {
  light: PropTypes.bool,
  dark: PropTypes.bool,
  fixed: PropTypes.string,
  color: PropTypes.string,
  role: PropTypes.string,
  expand: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]),
  tag: PropTypes.oneOfType([PropTypes.func, PropTypes.string])
  // pass in custom element to use
}

In the App.css file

.navbar-light {
  background-color: rgb(211, 81, 81);
}

To my surprise, this CSS selector works! From what I knew, to use a class in JSX we should use classNama="navbar-light" in the Navbar tag.

I would like to learn more about this, how can I utilize this mechanism?
For example, if I have a Card reactstrap component, can I use <Card body> then in CSS

.card-body{
  background-color: rgb(211, 81, 81);
}

since the body prop is bool type as well as below

Card.propTypes = {
  // Pass in a Component to override default element
  tag: PropTypes.oneOfType([PropTypes.func, PropTypes.string]),
  inverse: PropTypes.bool,
  color: PropTypes.string,
  body: PropTypes.bool,
  className: PropTypes.string
};

to specify the color of the Card? I can't find any guide online on how to utilize this mechanism.
Thanks in advance.

Body:
reactstrap uses a utility called classnames which helps you construct a list of class names.

Example:

const classes = classnames("class1", "class2");

// `classes` is set to the string "class1 class2"
// Not so useful yet, but read on ...

It also lets you perform boolean checks to decide whether to include a class or not.

The following example creates a string of class names that contains the class card-base, and card-large if large is true.

const classes = classnames(
  "card-base",
  "card-large": large,
);

// If `large` evaluates to `true`, this will result in "card-base card-large"

large can be passed in as a prop. Here's a working example:

import classnames from "classnames";

const Card = ({ large, className }) => {
  const classes = classnames(
    className, // Keep the classes that are passed in with the `className` prop
    "card-base",
    "card-large": large,
  );

  return <div className={classes}>... rest of the component ...</div>
}

// Validate the props:
Card.propTypes = {
  large: PropTypes.bool,
  className: PropTypes.string // The user can still provide their own classes
};

Remember to install the classnames package first: npm install classnames.

PropTypes is used to validate the data a component receives. You add the propTypes property to a component with a list of props and their expected datatypes, and warnings will be shown in the JavaScript console if any validations fail. Prop types have nothing directly to do with CSS or class names. It's a safety mechanism that adds no additional behavior.


问:
What are Global Constraints in constraint programming?
I see that ORTools and CpOptimizer both use global constraints. I know it speeds up the search a lot, but what does it actually do? Like what is the difference between me using (1) or (2) below;

Example for the AllDifferent constraint:

1) x1 != x2, x2 != x3, x1 != x3

and

2) AllDifferent(x1, x2, x3)

???

答:
None. We rebuild the all-different cliques. Still, it will be faster for presolve if you use the AllDifferent formulation.

Now, the CP-SAT is a based on a SAT solver, and prefers Boolean variables.
In your case, you can try removing integer variables, and use arrays of Boolean variables with a sum (boolvars) <= 1.