问:
Is there a difference between precaching and prefetching?
It seems they are two names for the same idea– is there any difference?</p>

答:
Disclaimer: I do not know of any literature specifically making (or not making) distinctions between precaching and prefetching.

Caching is a harder problem than fetching. Caching involves invalidation (knowing when a cache entry is no longer valid), may involve other aspects such as distributed caches, and may or may not be transparent to the application.

Fetching is related to getting something you will need. Thus, IMHO prefetching (the word) should be used when

you will likely need the data in the immediate future

the data will probably be acessed once

you can discard the data after using it

Think of an instruction prefetch for a branch prediction algorithm on a microprocessor, for example.

Caching is related to having a copy of the actual data on a faster medium, say an L2 cache or a memcached server. Thus, precaching is different than prefetching because of the usage: caching typically involves many reads, and some invalidation mecanism, thus a precaching mechanism would be used to populate some cache with frequently acessed items, for example.


来源: stackexchange

问:
Undefined is not an object for react navigation
I have two components for my project, and I have gone through all the steps for react navigation as follow:

```<code>// App.js
import React from 'react';
import Main from './app/componenets/Main'
import details from './app/componenets/details'
import { createStackNavigator, createAppContainer } from 'react-navigation'

const mainNavigator = createStackNavigator(
  {
    MainScreen: Main,
    detailsScreen: details,
  },
  {
   initialRouteName :'MainScreen'
  }
);
const AppContainer = createAppContainer(mainNavigator);

export default class App extends React.Component{

render() {
return(
  <AppContainer />
);
}
}
</code>```

Then I have my Main.js which I have a method as follow:

```<code>    import React from 'react';
import {
    StyleSheet ,
     Text,
     View,
    } from 'react-native'
import Note from './Note'
import detail from './details'
import { createStackNavigator, createAppContainer } from "react-navigation";

export default class Main extends React.Component {

  static navigationOptions = {
    title: 'To do list',
    headerStyle: {
      backgroundColor: '#f4511e',
    },
  };

  constructor(props){
    super(props);
    this.state = {
      noteArray: [],
      noteText: ''
    }
  }

render() {
    let notes = this.state.noteArray.map((val,key) => {
      return <Note key={key} keyval={key} val={val}
      goToDetailPage= {() => this.goToNoteDetail(key)} />
    });
    const { navigation } = this.props;
    return(
        <View style={styles.container}>
            <View style={styles.footer}>
                <TextInput
                onChangeText={(noteText) => this.setState({noteText})}
                style={styles.textInput}
                placeholder='What is your next Task?'
                placeholderTextColor='white'
                underlineColorAndroid = 'transparent'
                >
                </TextInput>
            </View>
            <TouchableOpacity onPress={this.addNote.bind(this)} style={styles.addButton}>
                <Text style={styles.addButtonText}> + </Text>
            </TouchableOpacity>
        </View>
      );
    }
    //This method is declared in my Note.js
    goToNoteDetail=(key)=>{
      this.props.navigation.navigate('detailsScreen')
      }
}
</code>```

//Styles which I didn't post to be short in code here
But when I try to do the navigation I get this error:
'undefined is not and object(evaluating 'this.props.val.date')
Do I need to pass the props in a way? or should I do anything else? I am new to React native and confused!

答:
in order to access this.props make arrow function or bind the function in constructor.</p>

```<code>goToDetail=()=>{
this.props.navigation.navigate('detailsScreen')
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two components for my project, and I have gone through all the steps for react navigation as follow:

// App.js
import React from 'react';
import Main from './app/componenets/Main'
import details from './app/componenets/details'
import { createStackNavigator, createAppContainer } from 'react-navigation'

const mainNavigator = createStackNavigator(
  {
    MainScreen: Main,
    detailsScreen: details,
  },
  {
   initialRouteName :'MainScreen'
  }
);
const AppContainer = createAppContainer(mainNavigator);

export default class App extends React.Component{

render() {
return(
  <AppContainer />
);
}
}

Then I have my Main.js which I have a method as follow:

    import React from 'react';
import {
    StyleSheet ,
     Text,
     View,
    } from 'react-native'
import Note from './Note'
import detail from './details'
import { createStackNavigator, createAppContainer } from "react-navigation";

export default class Main extends React.Component {

  static navigationOptions = {
    title: 'To do list',
    headerStyle: {
      backgroundColor: '#f4511e',
    },
  };

  constructor(props){
    super(props);
    this.state = {
      noteArray: [],
      noteText: ''
    }
  }

render() {
    let notes = this.state.noteArray.map((val,key) => {
      return <Note key={key} keyval={key} val={val}
      goToDetailPage= {() => this.goToNoteDetail(key)} />
    });
    const { navigation } = this.props;
    return(
        <View style={styles.container}>
            <View style={styles.footer}>
                <TextInput
                onChangeText={(noteText) => this.setState({noteText})}
                style={styles.textInput}
                placeholder='What is your next Task?'
                placeholderTextColor='white'
                underlineColorAndroid = 'transparent'
                >
                </TextInput>
            </View>
            <TouchableOpacity onPress={this.addNote.bind(this)} style={styles.addButton}>
                <Text style={styles.addButtonText}> + </Text>
            </TouchableOpacity>
        </View>
      );
    }
    //This method is declared in my Note.js
    goToNoteDetail=(key)=>{
      this.props.navigation.navigate('detailsScreen')
      }
}

//Styles which I didn't post to be short in code here
But when I try to do the navigation I get this error:
'undefined is not and object(evaluating 'this.props.val.date')
Do I need to pass the props in a way? or should I do anything else? I am new to React native and confused!

Body:
in order to access this.props make arrow function or bind the function in constructor.

goToDetail=()=>{
this.props.navigation.navigate('detailsScreen')
}


问:
Bootstrap 3: (Mobile) Navigation Bar auto close once you click the dropdown
Hi I need your expertise because its working perfectly in desktop mode but if its mobile mode its not working properly once you click the dropdown menu it will automatic close the whole navigation bar, </p>

```<code><li class="dropdown">
                            <a data-toggle="dropdown" > Shop </a>
                            <ul class="dropdown-menu">
                                <li><a href="<?php echo home_url(); ?>/shop">All Inventory</a></li>
                                <li><a href="<?php echo home_url(); ?>/product-category/designer-bags">Designer Bags</a></li>
                                <li><a href="<?php echo home_url(); ?>/product-category/designer-accessories">Designer Accessories</a></li>
                                <li><a href="<?php echo home_url(); ?>/outright-buying/">Outright Buying</a></li>
                                <li><a href="<?php echo home_url(); ?>/Consignment">Consignment</a></li>
                            </ul>
                    </li>
</code>```

答:
The following code expands the sub menus when a click occurs on navbar-toggle
and it change the aria-expanded to the correct value based on the open/close state of sub menu

```<code>function opensubmenus() {
    if ($(window).width() < 768) {
        $("#top-navbar-collapse li").addClass('open');
        $("#top-navbar-collapse li a").attr('aria-expanded','true');
    }else{
        $("#top-navbar-collapse li").removeClass('open');
        $("#top-navbar-collapse li a").attr('aria-expanded','false');
    }
}

$('#top-menu .navbar-toggle').click(function(){
    setTimeout(opensubmenus, 100);
});

$(window).resize(opensubmenus);
opensubmenus();
</code>```

Body:
Hi I need your expertise because its working perfectly in desktop mode but if its mobile mode its not working properly once you click the dropdown menu it will automatic close the whole navigation bar,

                             Shop

<a href="<?php echo home_url(); ?>/shop">All Inventory

<a href="<?php echo home_url(); ?>/product-category/designer-bags">Designer Bags

<a href="<?php echo home_url(); ?>/product-category/designer-accessories">Designer Accessories

<a href="<?php echo home_url(); ?>/outright-buying/">Outright Buying

<a href="<?php echo home_url(); ?>/Consignment">Consignment

Body:
The following code expands the sub menus when a click occurs on navbar-toggle
and it change the aria-expanded to the correct value based on the open/close state of sub menu

function opensubmenus() {
    if ($(window).width() < 768) {
        $("#top-navbar-collapse li").addClass('open');
        $("#top-navbar-collapse li a").attr('aria-expanded','true');
    }else{
        $("#top-navbar-collapse li").removeClass('open');
        $("#top-navbar-collapse li a").attr('aria-expanded','false');
    }
}

$('#top-menu .navbar-toggle').click(function(){
    setTimeout(opensubmenus, 100);
});

$(window).resize(opensubmenus);
opensubmenus();


问:
How to get the keyspace name from cassandra session
While i am creating the session giving the keyspace_name as input for the API cluster.connect(keyspaceName).Is there anyway/api where i can get the keyspace_name from the session?

Session Creation

```<code>String cKeyspace="inventory_flip"
Session session = cluster.connect(cKeyspace);
</code>```

How to get keyspace from existing cassandra DB session?

```<code>session.getXXXXX?
</code>```

答:
```<code>public interface Session extends Closeable {

  /**
   * The keyspace to which this Session is currently logged in, if any.
   *
   * <p>This correspond to the name passed to {@link Cluster#connect(String)}, or to the last
   * keyspace logged into through a "USE" CQL query if one was used.
   *
   * @return the name of the keyspace to which this Session is currently logged in, or {@code null}
   *     if the session is logged to no keyspace.
   */
  String getLoggedKeyspace();
</code>```

Body:
While i am creating the session giving the keyspace_name as input for the API cluster.connect(keyspaceName).Is there anyway/api where i can get the keyspace_name from the session?

Session Creation

String cKeyspace="inventory_flip"
Session session = cluster.connect(cKeyspace);

How to get keyspace from existing cassandra DB session?

session.getXXXXX?


问:
how do I run an http request from a dynamic IP webpage, thru an AWS static IP, since the endpoint API needs to be from a whitelisted IP?
I am working on a project where I have a Wix site (the important thing is that thru Wix I am forced to use a dynamic IP).

The API that I want to send requests to, only accepts whitelisted IPs. I can easily add a whitelisted IP to the list. In fact, I've already got an AWS EC2 server running node/fetch, that has an elastic IP, which is whitelisted, getting good responses.

The problem is, and it be a noob question, How do i connect my wix back-end to AWS thru my elastic IP to an external API, and get info back.

back-end --> AWS --> API endpoint
API endpoint --> AWS --> back-end

I've done my due diligence, and have even asked a similar question myself and not received answers. I need a HTTP guru. thanks in advance

I've not worked on the Wix to AWS part yet, but as for the AWS to API part I have created an EC2 server, connected thru ssh, installed node, installed fetch, used filzilla to drop a js file i wrote on my local machine. I hooked up an elastic IP that i whitelisted for the API endpoint to the EC2 server/instance. I ran the js file and i am able to get auth, add data and pull data back.

I don;t know how to integrate all of the AWS services however, I am new to AWS and while I am amazed at what I can do sometimes, other times, i get overwhelmed with all the connections and products.

I've successfully created an SQS queue, and pushed to lambda functions, i get 200 responses from the API, but they are not the typical "not whitelisted IP" responses. they refer to 127.0.0.1:443. i researched this port and seen its usually used as a secure port.

i've made requests with API gateway, i get the "not whitelisted IP" response, which is expected since the IPs change dynamically on API gateway.

My vision is that I'll need to incorporate
-SQS
-Lambda
-API Gateway
-VPC
-and probably abandon my EC2

///its a basic node-fetch request

答: the solution I discovered is to use Wix Corvid to send to an SQS query in AWS. then write code and host it on an EC2 instance, with a whitelisted IP. the node script on the EC2 calls the SQS queue and does a fetch with the proper message forwarded on. since you can assign a static IP to EC2s using Elastic IP in AWS, this solves the problem. the EC2 and SQS (AWS Services) act as a proxy which passes all info to the endpoint.</p>


问:
In place reinitialization of objects
I'm working on an embedded system, where memory is scarce, and more importantly, since there's a soft realtime constraint (i.e. it's a bug if we don't make the deadline, but no one dies), I cannot use dynamic memory allocation.

However, there's the occasional need to re-initialize a subsystem, and there's been a number of bugs related to not-quite-everything getting either cleaned up or reset correctly. This is of course exactly the problem that constructors and destructors are supposed to solve, but since we don't allocate dynamically, we can't use the idiom where we'd destruct the object and then allocate a new one from scratch (mostly the objects of relevance here are globals).

So in the end there's usually setup code in a constructor, and a reinitialize -type function, which resemble each other but are not identical, since the reinitialize function also does a lot of what a destructor would do.

One way out that I'm thinking of is to write a "renew" -template (this is just a draft, may contain erors and possibly not complet):

```<code>template<typename T, typename .. Args>
void renew(T & obj, Args&&... args) {
  obj.~T();
  new(&obj) T(std::forward<Args>(args)...);
}
</code>```

which could be used to reinitialize non-dynamically alloctated variables. So for example

```<code>A a{17};
... //Do something with a
renew(a, 14);
...//work with the new a, no need to reallocate memory
</code>```

This would allow getting some of the advantages of constructors and destructors (primarily single way to initialize and deinitialize an object) without dynamic memory allocation. Note that the usage above is simplified, in practice this would mostly be used in very specific points in the main loop and on global objects representing the actual physical subsystems.

Question: is this a sensible way of going about it? Or is there a better alternative?

There's a very similar question here Calling a constructor to re-initialize object. I'm asking much the same thing but specifically in context of embedded programming, where I can't do things the usual way with dynamic allocation.

答:
I cannot use dynamic memory allocation

Then the keywords new and delete cannot be allowed to exist in your source. Also make sure to nuke the .heap segment from your memory map.

Similarly, you don't need/want RAII for any class that's some manner of driver. In buzz word terms, any such class must be a "singleton". Or rather, a class that allows for n number of static instances, where n is the number of hardware devices of that type present.

As for the solution to your problem, it is simply this:

```<code>public:
  void construct() { ... }

  Foo()
  : /* init internal stuff here if needed */
  {
    /* init internal stuff here if needed */
    construct();
  }
</code>```

Where the constructor ensures that everything has default values, and construct is written so that it either works on non-initialized internals (null etc), or in case the internals are set, free up resources.

But there should not even be anything for you to "free up", since this is an embedded system. If you need to gracefully terminate on-going data transmissions, NVM writes etc, that code shouldn't be in the destructor. Because you shouldn't need a destructor (nor should you need the rest of the rule of three), since you should only have one instance of the class.

Title: In place reinitialization of objects

Body:
I'm working on an embedded system, where memory is scarce, and more importantly, since there's a soft realtime constraint (i.e. it's a bug if we don't make the deadline, but no one dies), I cannot use dynamic memory allocation.

However, there's the occasional need to re-initialize a subsystem, and there's been a number of bugs related to not-quite-everything getting either cleaned up or reset correctly. This is of course exactly the problem that constructors and destructors are supposed to solve, but since we don't allocate dynamically, we can't use the idiom where we'd destruct the object and then allocate a new one from scratch (mostly the objects of relevance here are globals).

So in the end there's usually setup code in a constructor, and a reinitialize -type function, which resemble each other but are not identical, since the reinitialize function also does a lot of what a destructor would do.

One way out that I'm thinking of is to write a "renew" -template (this is just a draft, may contain erors and possibly not complet):

template<typename T, typename .. Args>
void renew(T & obj, Args&&... args) {
  obj.~T();
  new(&obj) T(std::forward<Args>(args)...);
}

which could be used to reinitialize non-dynamically alloctated variables. So for example

A a{17};
... //Do something with a
renew(a, 14);
...//work with the new a, no need to reallocate memory

This would allow getting some of the advantages of constructors and destructors (primarily single way to initialize and deinitialize an object) without dynamic memory allocation. Note that the usage above is simplified, in practice this would mostly be used in very specific points in the main loop and on global objects representing the actual physical subsystems.

Question: is this a sensible way of going about it? Or is there a better alternative?

There's a very similar question here Calling a constructor to re-initialize object. I'm asking much the same thing but specifically in context of embedded programming, where I can't do things the usual way with dynamic allocation.

Body:
I cannot use dynamic memory allocation

Then the keywords new and delete cannot be allowed to exist in your source. Also make sure to nuke the .heap segment from your memory map.

Similarly, you don't need/want RAII for any class that's some manner of driver. In buzz word terms, any such class must be a "singleton". Or rather, a class that allows for n number of static instances, where n is the number of hardware devices of that type present.

As for the solution to your problem, it is simply this:

public:
  void construct() { ... }

  Foo()
  : /* init internal stuff here if needed */
  {
    /* init internal stuff here if needed */
    construct();
  }

Where the constructor ensures that everything has default values, and construct is written so that it either works on non-initialized internals (null etc), or in case the internals are set, free up resources.

But there should not even be anything for you to "free up", since this is an embedded system. If you need to gracefully terminate on-going data transmissions, NVM writes etc, that code shouldn't be in the destructor. Because you shouldn't need a destructor (nor should you need the rest of the rule of three), since you should only have one instance of the class.


问:
How to iterate through list, per test in SilkTest?
I wrote Lists (Name, Item, etc.) for my Green Mountain Outpost Applikation.
I want the applikation to run automaticaly the testcase with 1 Persone and Item at the time. So that the app. runs 1 Person from list throug, than the second test with another.

Testcase

Function

List for Name, Item, etc.

答:
You can mention the data in Excel and make the test case as data driven.

Each row will be having one data combination.


问:
How do I sequentially fill a big range of cells in Google Sheets?
I want to fill an entire column of Google Sheets with numbers from -4000 to 4000, but I can't find an easy way of doing it.

I'm aware of the auto-fill solution of google sheets that allows you to write two sequential numbers and then select them and use the drag-and-drop approach, but for big numbers, this is not a feasible approach.

Is there a way of automating it using some formula or some built-in option?

答:
input 1 in A1

input =A1 + 1 in A2

copy formula from A2

press CMD + Shift + Arrow_down - this will select entire column except first cell

press CMD + V to paste formula


问:
format of number on downloading in csv format
Following code returns hours for given seconds, which is working.

```<code><?php

$hrs = seconds_to_dezi(278280);
echo $hrs;
$filename = "test";
header("Content-type: application/vnd-ms-excel");
header("Content-Disposition: attachment; filename=$filename.xls");

function seconds_to_dezi($s) {
    $n = false;
    if ($s < 0) {
        $n = true;
        $s = -$s;
    }
    $h = round($s / 3600,2);
    $h = number_format($h,2, ',', ' ');
    $h = str_replace(".",",",$h);

    if ($n == true) {
        return ("-" . $h);
    } else {
        return ($h);
    }
}

?>
</code>```

Actual output in excel:- 77,3

Expected output is:- 77,30

i.e on downloading values in csv format, the trailing zero after decimal is truncated. I want to have that zero in excel.

答: The function is returning 77,30. The thing is that Excel doesn't show the final 0, but it's there. Open the file with a text editor.</p>

ContentLicense: CC BY-SA 3.0

Body:
Following code returns hours for given seconds, which is working.

<?php

$hrs = seconds_to_dezi(278280);
echo $hrs;
$filename = "test";
header("Content-type: application/vnd-ms-excel");
header("Content-Disposition: attachment; filename=$filename.xls");

function seconds_to_dezi($s) {
    $n = false;
    if ($s < 0) {
        $n = true;
        $s = -$s;
    }
    $h = round($s / 3600,2);
    $h = number_format($h,2, ',', ' ');
    $h = str_replace(".",",",$h);

    if ($n == true) {
        return ("-" . $h);
    } else {
        return ($h);
    }
}

?>

Actual output in excel:- 77,3

Expected output is:- 77,30

i.e on downloading values in csv format, the trailing zero after decimal is truncated. I want to have that zero in excel.


问:
How to correctly overlay two images with opencv
I am trying to overlay a transparent PNG over a JPG image, I somehow cannot get it to work, what I tried:

```<code>import cv2
import numpy as np

a = cv2.imread("a.jpeg")
b = cv2.imread("b.png", cv2.IMREAD_UNCHANGED)

# add alpha channel to jpeg
(h, w) = a.shape[:2]
a = np.dstack([a, np.ones((h, w), dtype="uint8") * 0])

c = cv2.add(b,a)
cv2.imwrite("out.jpeg", c)
</code>```

The following code will combine the two images, but the PNG transparency is not correct, it's somehow more opaque than it should be. ( I read this could be a issue with opencv ? not reading alpha correctly from png )

What I am trying to do is simply stack two image over another, a background JPG and put over a PNG that has some transparent zones, both images are the same size.

Thanks!

答:
I found a example on github I modified a bit, works as expected:</p>

```<code>import numpy as np
import cv2

img = cv2.imread('1_calib.jpeg')
overlay_t = cv2.imread('ol.png',-1) # -1 loads with transparency

def overlay_transparent(bg_img, img_to_overlay_t):
    # Extract the alpha mask of the RGBA image, convert to RGB
    b,g,r,a = cv2.split(img_to_overlay_t)
    overlay_color = cv2.merge((b,g,r))

    mask = cv2.medianBlur(a,5)

    # Black-out the area behind the logo in our original ROI
    img1_bg = cv2.bitwise_and(bg_img.copy(),bg_img.copy(),mask = cv2.bitwise_not(mask))

    # Mask out the logo from the logo image.
    img2_fg = cv2.bitwise_and(overlay_color,overlay_color,mask = mask)

    # Update the original image with our new ROI
    bg_img = cv2.add(img1_bg, img2_fg)

    return bg_img

cv2.imshow('image',overlay_transparent(img, overlay_t))
cv2.waitKey(0)
</code>```

Body:
I am trying to overlay a transparent PNG over a JPG image, I somehow cannot get it to work, what I tried:

import cv2
import numpy as np

a = cv2.imread("a.jpeg")
b = cv2.imread("b.png", cv2.IMREAD_UNCHANGED)

# add alpha channel to jpeg
(h, w) = a.shape[:2]
a = np.dstack([a, np.ones((h, w), dtype="uint8") * 0])

c = cv2.add(b,a)
cv2.imwrite("out.jpeg", c)

The following code will combine the two images, but the PNG transparency is not correct, it's somehow more opaque than it should be. ( I read this could be a issue with opencv ? not reading alpha correctly from png )

What I am trying to do is simply stack two image over another, a background JPG and put over a PNG that has some transparent zones, both images are the same size.

Thanks!

Body:
I found a example on github I modified a bit, works as expected:

import numpy as np
import cv2

img = cv2.imread('1_calib.jpeg')
overlay_t = cv2.imread('ol.png',-1) # -1 loads with transparency

def overlay_transparent(bg_img, img_to_overlay_t):
    # Extract the alpha mask of the RGBA image, convert to RGB
    b,g,r,a = cv2.split(img_to_overlay_t)
    overlay_color = cv2.merge((b,g,r))

    mask = cv2.medianBlur(a,5)

    # Black-out the area behind the logo in our original ROI
    img1_bg = cv2.bitwise_and(bg_img.copy(),bg_img.copy(),mask = cv2.bitwise_not(mask))

    # Mask out the logo from the logo image.
    img2_fg = cv2.bitwise_and(overlay_color,overlay_color,mask = mask)

    # Update the original image with our new ROI
    bg_img = cv2.add(img1_bg, img2_fg)

    return bg_img

cv2.imshow('image',overlay_transparent(img, overlay_t))
cv2.waitKey(0)


问:
Python add entire column to csv file, without reading the file content
I need to add columns to a csv file using Python. The only way i can think of doing this is reading the whole file, editing each row to add 1 element, and then write again to the file. However i really don't want to do it this way because of the size of the file (over 32000 rows, seems a lot of reading and writing everytime i want to add a column). Even using the csv module i think the principle would be the same, read everything, edit and write again.

to be clear, below is a csv file example.

```<code>1,2
1,2
1,2
1,2
</code>```

i want to add a third column so the file would become:

```<code>1,2,3
1,2,3
1,2,3
1,2,3
</code>```

If i wanted to add an entire row (or line) i could use open(csvfile, 'a') and "append" the last row to the file. Is there a similar option to add a column?

答: unfortunately this is not possible. Text files files are sequences and if you want to add something in between you have to shift all the remaining content (and therefore you have to read and write it).</p>

Body:
I need to add columns to a csv file using Python. The only way i can think of doing this is reading the whole file, editing each row to add 1 element, and then write again to the file. However i really don't want to do it this way because of the size of the file (over 32000 rows, seems a lot of reading and writing everytime i want to add a column). Even using the csv module i think the principle would be the same, read everything, edit and write again.

to be clear, below is a csv file example.

1,2
1,2
1,2
1,2

i want to add a third column so the file would become:

1,2,3
1,2,3
1,2,3
1,2,3

If i wanted to add an entire row (or line) i could use open(csvfile, 'a') and "append" the last row to the file. Is there a similar option to add a column?


问:
How can I pass this String obtained to jsonObject format?
Executing the code I get a String with the following value "idStation=6107AAE80593E4B2&timestamp=1558524847&pm1=0.800&pm2_5=1.510&pm10=2.650&temperature=22.380&humidity=40.379&pressure=93926.656&luminosity=131&coC=0.440923810000&no2C=0.000000000000&o3C=8.210327100000&batteryLevel=27&batteryCurrent=0&baterryVolts=3.63"

My goal is to convert that String into JsonObject format where each value is separated, that is, idstation = 6107AAE80593E4B2, etc., and to be able to continue treating the data later

the idea is to take for example the value of no2 and save it in a variable of type (Map String, Object)

```<code>eventPayload.put ("no2", String.valueOf (no2));
</code>```

the value of the string is coded in the variable "sinCifrar"

I tried the following code, but I have problems:

```<code>'String jsonString = sinCifrar;
JSONObject jsonk = new JSONObject(jsonString);
            no2 = (((jsonk.getDouble("pressure")/101325.0)*(jsonk.getDouble("no2C")/1000)*46.0055)/(0.082*(jsonk.getDouble("temperature")+273.15)))*1000000.0;
            co = (((jsonk.getDouble("pressure")/101325.0)*(jsonk.getDouble("coC")/1000)*28.01)/(0.082*(jsonk.getDouble("temperature")+273.15)))*1000000.0;
            o3 = (((jsonk.getDouble("pressure")/101325.0)*(jsonk.getDouble("o3C")/1000)*48.0)/(0.082*(jsonk.getDouble("temperature")+273.15)))*1000000.0;'
</code>```

I get the following error:

```<code>org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
</code>```

Since it is not a string created from the beginning, but it is obtained after executing several methods, I can not leave it with the requested format, any idea?

答:
The string is not a valid JSON but what you want , can be acheived using simple java code as below

```<code>public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
    String test = "idStation=6107AAE80593E4B2&timestamp=1558524847&pm1=0.800&pm2_5=1.510&pm10=2.650&temperature=22.380"
            + "&humidity=40.379&pressure=93926.656&luminosity=131&coC=0.440923810000&no2C=0.000000000000&o3C=8.210327100000&"
            + "batteryLevel=27&batteryCurrent=0&baterryVolts=3.63";
    String[] result = test.split("&");
    Map<String, String> map = new HashMap<String, String>();
    for (String string : result) {
        String[] str = string.split("=");
        map.put(str[0], str[1]);
    }
    double pressure = Double.valueOf(map.get("pressure"));
    double no2C = Double.valueOf(map.get("no2C"));
    double tempreture = Double.valueOf(map.get("temperature"));
    double o3C = Double.valueOf(map.get("o3C"));
    double cOC = Double.valueOf(map.get("coC"));
    System.out.println("Pressure:: "+pressure+" , no2c :: "+no2C+", tempreture:: "+tempreture+" ,o3C:: "+o3C+" ,coC:: "+cOC);
}
</code>```

output

```<code>Pressure:: 93926.656 , no2c :: 0.0, tempreture:: 22.38 ,o3C:: 8.2103271 ,coC:: 0.44092381
</code>```

From the map you can get any Key value you want.

Body:
Executing the code I get a String with the following value "idStation=6107AAE80593E4B2&timestamp=1558524847&pm1=0.800&pm2_5=1.510&pm10=2.650&temperature=22.380&humidity=40.379&pressure=93926.656&luminosity=131&coC=0.440923810000&no2C=0.000000000000&o3C=8.210327100000&batteryLevel=27&batteryCurrent=0&baterryVolts=3.63"

My goal is to convert that String into JsonObject format where each value is separated, that is, idstation = 6107AAE80593E4B2, etc., and to be able to continue treating the data later

the idea is to take for example the value of no2 and save it in a variable of type (Map String, Object)

eventPayload.put ("no2", String.valueOf (no2));

the value of the string is coded in the variable "sinCifrar"

I tried the following code, but I have problems:

'String jsonString = sinCifrar;
JSONObject jsonk = new JSONObject(jsonString);
            no2 = (((jsonk.getDouble("pressure")/101325.0)*(jsonk.getDouble("no2C")/1000)*46.0055)/(0.082*(jsonk.getDouble("temperature")+273.15)))*1000000.0;
            co = (((jsonk.getDouble("pressure")/101325.0)*(jsonk.getDouble("coC")/1000)*28.01)/(0.082*(jsonk.getDouble("temperature")+273.15)))*1000000.0;
            o3 = (((jsonk.getDouble("pressure")/101325.0)*(jsonk.getDouble("o3C")/1000)*48.0)/(0.082*(jsonk.getDouble("temperature")+273.15)))*1000000.0;'

I get the following error:

org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]

Since it is not a string created from the beginning, but it is obtained after executing several methods, I can not leave it with the requested format, any idea?

Body:
The string is not a valid JSON but what you want , can be acheived using simple java code as below

public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
    String test = "idStation=6107AAE80593E4B2&timestamp=1558524847&pm1=0.800&pm2_5=1.510&pm10=2.650&temperature=22.380"
            + "&humidity=40.379&pressure=93926.656&luminosity=131&coC=0.440923810000&no2C=0.000000000000&o3C=8.210327100000&"
            + "batteryLevel=27&batteryCurrent=0&baterryVolts=3.63";
    String[] result = test.split("&");
    Map<String, String> map = new HashMap<String, String>();
    for (String string : result) {
        String[] str = string.split("=");
        map.put(str[0], str[1]);
    }
    double pressure = Double.valueOf(map.get("pressure"));
    double no2C = Double.valueOf(map.get("no2C"));
    double tempreture = Double.valueOf(map.get("temperature"));
    double o3C = Double.valueOf(map.get("o3C"));
    double cOC = Double.valueOf(map.get("coC"));
    System.out.println("Pressure:: "+pressure+" , no2c :: "+no2C+", tempreture:: "+tempreture+" ,o3C:: "+o3C+" ,coC:: "+cOC);
}

output

Pressure:: 93926.656 , no2c :: 0.0, tempreture:: 22.38 ,o3C:: 8.2103271 ,coC:: 0.44092381

From the map you can get any Key value you want.


问:
how to repeat characters in a string
I'm trying to link two tables, one has an 'EntityRef' that's made of four alpha characters and a sequential number...

```<code>EntityRef
=========
SWIT1
LIVE32
KIRB48
MEHM38
BRAD192
</code>```

The table that I'm trying to link to stores the reference in a 15 character field where the 4 alphas are at the start and the numbers are at the end but with zeros in between to make up the 15 characters...

```<code>EntityRef
=========
SWIT00000000001
LIVE00000000032
</code>```

So, to get theses to link, my options are to either remove the zeros on one field or add the zeros on the other.

I've gone for the later as it seems to be a simpler approach and eliminates the risk of getting into problems if the numeric element contains a zero.

So, the alpha is always 4 characters at the beginning and the number is the remainder and 15 minus the LEN() of the EntityRef is the number of zeros that I need to insert...

```<code>left(entityref,4) as 'Alpha',
right(entityref,len(EntityRef)-4) as 'Numeric',
15-len(EntityRef) as 'No.of Zeros'

Alpha   Numeric No.of Zeros
=====   ======= ===========
SWIT    1       10
LIVE    32      9
KIRB    48      9
MEHM    38      9
MALL    36      9
</code>```

So, I need to concatenate the three elements but I don't know how to create the string of zeros to the specified length...how do I do that??

```<code>Concat(Alpha, '0'*[No. of Zeros], Numeric)
</code>```

What is the correct way to repeat a character a specified number of times?

答:
With casting to integer the numeric part:

```<code>select *
from t1 inner join t2
on concat(left(t2.EntityRef, 4), cast(right(t2.EntityRef, 11) as bigint)) = t1.EntityRef
</code>```

See the demo.

Title: how to repeat characters in a string

Body:
I'm trying to link two tables, one has an 'EntityRef' that's made of four alpha characters and a sequential number...

EntityRef
=========
SWIT1
LIVE32
KIRB48
MEHM38
BRAD192

The table that I'm trying to link to stores the reference in a 15 character field where the 4 alphas are at the start and the numbers are at the end but with zeros in between to make up the 15 characters...

EntityRef
=========
SWIT00000000001
LIVE00000000032

So, to get theses to link, my options are to either remove the zeros on one field or add the zeros on the other.

I've gone for the later as it seems to be a simpler approach and eliminates the risk of getting into problems if the numeric element contains a zero.

So, the alpha is always 4 characters at the beginning and the number is the remainder and 15 minus the LEN() of the EntityRef is the number of zeros that I need to insert...

left(entityref,4) as 'Alpha',
right(entityref,len(EntityRef)-4) as 'Numeric',
15-len(EntityRef) as 'No.of Zeros'

Alpha   Numeric No.of Zeros
=====   ======= ===========
SWIT    1       10
LIVE    32      9
KIRB    48      9
MEHM    38      9
MALL    36      9

So, I need to concatenate the three elements but I don't know how to create the string of zeros to the specified length...how do I do that??

Concat(Alpha, '0'*[No. of Zeros], Numeric)

What is the correct way to repeat a character a specified number of times?

Body:
With casting to integer the numeric part:

select *
from t1 inner join t2
on concat(left(t2.EntityRef, 4), cast(right(t2.EntityRef, 11) as bigint)) = t1.EntityRef

See the demo.


问:
How to check Oracle database for long running queries
My application, which uses an Oracle database, is going slow or appears to have stopped completely.

How can find out which queries are most expensive, so I can investigate further?

答:
You can check the long-running queries details like % completed and remaining time using the below query:

```<code> SELECT SID, SERIAL#, OPNAME, CONTEXT, SOFAR,
 TOTALWORK,ROUND(SOFAR/TOTALWORK*100,2) "%_COMPLETE"
 FROM V$SESSION_LONGOPS
 WHERE OPNAME NOT LIKE '%aggregate%'
       AND TOTALWORK != 0
       AND SOFAR <> TOTALWORK;
</code>```

For the complete list of troubleshooting steps, you can check here:Troubleshooting long running sessions

OwnerDisplayName: Maven Lee

Body:
You can check the long-running queries details like % completed and remaining time using the below query:

 SELECT SID, SERIAL#, OPNAME, CONTEXT, SOFAR,
 TOTALWORK,ROUND(SOFAR/TOTALWORK*100,2) "%_COMPLETE"
 FROM V$SESSION_LONGOPS
 WHERE OPNAME NOT LIKE '%aggregate%'
       AND TOTALWORK != 0
       AND SOFAR <> TOTALWORK;

For the complete list of troubleshooting steps, you can check here:Troubleshooting long running sessions


问:
Extract Pattern Matches / Remove Everything From Line Except Pattern
I'm currently using grep to try to extract specific text from each line of a file. It's successfully extracting the matches, however, I would like it to retain any lines that don't have matches (leave them as a blank line).

This is what I've tried so far (to get the name of the city on each line):

```<code>grep -o -P '(?<="city":").*?(?=")' input.txt
</code>```

Example input:

```<code>email":"addictedtotlick7@gmail.com","last_name":"THOMPSON","first_name":"ERIN",,"__v":0,,,,"state":"NY","city":"north tonawanda"}
first_name":"chris","last_name":"caul",,"email":"dawgzn@mail.com",,,,"__v":0}
email":"lesliebo993@hotmail.com",,"first_name":"LESLIE","last_name":"RAMBO",,"city":"DOTHAN","state":"AL",,,"__v":0,
email":"malala@yahoo.com",,,"state":"GA","city":"NORCROSS",,"last_name":"KEO","first_name":"CATHY",,"__v":0,
email":"kdela@gmail.com",,"state":"FL","city":"HOLLYWOOD",,"last_name":"DE LA CRUZ","first_name":"KIDA",,"__v":0,
</code>```

Desired output:

```<code>north tonawanda

DOTHAN
NORCROSS
HOLLYWOOD
</code>```

Happy to try something in SED too if it's easier, but would prefer to avoid AWK as I have to work with big files, not sure I have enough RAM.

答:
I suggest another awk script

```<code>awk 'match($0,/(?<=\"city\":\").*?(?=\")/,m){$0=m[0]}1' input.txt
</code>```

No problem with RAM and awk.

This script process each line.
If current line match RegExp (?<="city":").*?(?="), then overwrite current line with match. Print current line.

Body:
I'm currently using grep to try to extract specific text from each line of a file. It's successfully extracting the matches, however, I would like it to retain any lines that don't have matches (leave them as a blank line).

This is what I've tried so far (to get the name of the city on each line):

grep -o -P '(?<="city":").*?(?=")' input.txt

Example input:

email":"addictedtotlick7@gmail.com","last_name":"THOMPSON","first_name":"ERIN",,"__v":0,,,,"state":"NY","city":"north tonawanda"}
first_name":"chris","last_name":"caul",,"email":"dawgzn@mail.com",,,,"__v":0}
email":"lesliebo993@hotmail.com",,"first_name":"LESLIE","last_name":"RAMBO",,"city":"DOTHAN","state":"AL",,,"__v":0,
email":"malala@yahoo.com",,,"state":"GA","city":"NORCROSS",,"last_name":"KEO","first_name":"CATHY",,"__v":0,
email":"kdela@gmail.com",,"state":"FL","city":"HOLLYWOOD",,"last_name":"DE LA CRUZ","first_name":"KIDA",,"__v":0,

Desired output:

north tonawanda

DOTHAN
NORCROSS
HOLLYWOOD

Happy to try something in SED too if it's easier, but would prefer to avoid AWK as I have to work with big files, not sure I have enough RAM.

Body:
I suggest another awk script

awk 'match($0,/(?<=\"city\":\").*?(?=\")/,m){$0=m[0]}1' input.txt

No problem with RAM and awk.

This script process each line.
If current line match RegExp (?<="city":").*?(?="), then overwrite current line with match. Print current line.


答:
I found the answer as soon as I posted the question (sometimes it helps you think it through!).</p>

```<code>(left(entityref,4) + replicate('0',15-len(EntityRef)) +
right(entityref,len(EntityRef)-4)),
</code>```

Title: how to repeat characters in a string

Body:
I found the answer as soon as I posted the question (sometimes it helps you think it through!).

(left(entityref,4) + replicate('0',15-len(EntityRef)) +
right(entityref,len(EntityRef)-4)),


问:
How recover sybase database (unknown db version)
I have a database file (*.db) that need to be recovered.

The bad is, the end-user have null idea of the version of the database. Not know the password. The original developer is lost. The computer where was installed was formatted. We have not experience in this database software. Yeah, nightmare.

My guess is a old database. I'm trying to open it in Sybase 11, dev edition.

I follow this steps: http://dcx.sybase.com/1101en/sachanges_en11/unloading-reloading-upgrading-newjasper.html

I try to use the UNLOAD utility from command line & from the Sybase central utility. From command line I do:

```<code>./dbinfo -c "DBF=/Users/mamcx/Downloads/CEMDE_ENDOCRINO_S.A.DB;UID=DBA;PWD=sql"
SQL Anywhere Information Utility Version 11.0.1.2045
Unable to start specified database: '/Users/mamcx/Downloads/CEMDE_ENDOCRINO_S.A.DB' was created by a different version of the software
</code>```

Ok, I try to unload:

```<code>./dbunload -c "DBF=/Users/mamcx/Downloads/CEMDE_ENDOCRINO_S.A.DB;UID=DBA;PWD=sql" -n /Users/mamcx/Desktop/
SQL Anywhere Unload Utility Version 11.0.1.2045
Connecting and initializing
***** SQL error: Unable to start database server
</code>```

Ok, from the server admin tool:

```<code>dbunload -v -c "UID=dba;PWD=***;DBF=/Users/mamcx/Downloads/CEMDE_ENDOCRINO_S.A.DB" -an "/Users/mamcx/Desktop/baba.db" -ap 4096 -ea None -ii -sa -so _sc866192545
Connecting and initializing
***** SQL error: Unable to start database server
An error occurred while attempting to unload the database '/Users/mamcx/Downloads/CEMDE_ENDOCRINO_S.A.DB'.
</code>```

Exist a way to know the version of the database server used to create this? Is possible to recover this file?

答:
Try to simply start a server with that database and capture the output with -z -o server.out. The server.out file should contain a more specific error telling you why it can't start the database. This error can occur if you are trying to start something that is not a SQL Anywhere database.

You may also want to post this question over at http://sqlanywhere-forum.sap.com/.

Body:
I have a database file (*.db) that need to be recovered.

The bad is, the end-user have null idea of the version of the database. Not know the password. The original developer is lost. The computer where was installed was formatted. We have not experience in this database software. Yeah, nightmare.

My guess is a old database. I'm trying to open it in Sybase 11, dev edition.

I follow this steps: http://dcx.sybase.com/1101en/sachanges_en11/unloading-reloading-upgrading-newjasper.html

I try to use the UNLOAD utility from command line & from the Sybase central utility. From command line I do:

./dbinfo -c "DBF=/Users/mamcx/Downloads/CEMDE_ENDOCRINO_S.A.DB;UID=DBA;PWD=sql"
SQL Anywhere Information Utility Version 11.0.1.2045
Unable to start specified database: '/Users/mamcx/Downloads/CEMDE_ENDOCRINO_S.A.DB' was created by a different version of the software

Ok, I try to unload:

./dbunload -c "DBF=/Users/mamcx/Downloads/CEMDE_ENDOCRINO_S.A.DB;UID=DBA;PWD=sql" -n /Users/mamcx/Desktop/
SQL Anywhere Unload Utility Version 11.0.1.2045
Connecting and initializing
***** SQL error: Unable to start database server

Ok, from the server admin tool:

dbunload -v -c "UID=dba;PWD=***;DBF=/Users/mamcx/Downloads/CEMDE_ENDOCRINO_S.A.DB" -an "/Users/mamcx/Desktop/baba.db" -ap 4096 -ea None -ii -sa -so _sc866192545
Connecting and initializing
***** SQL error: Unable to start database server
An error occurred while attempting to unload the database '/Users/mamcx/Downloads/CEMDE_ENDOCRINO_S.A.DB'.

Exist a way to know the version of the database server used to create this? Is possible to recover this file?


问:
how to remove https links from a string column in pandas
I have the following dataframe:

```<code>import pandas as pd
df = pd.DataFrame({'col':['text https://random.website1.com text', 'text https://random.website2.com']})
</code>```

I would like to remove all the links from this column.

Any ideas ?

答:
Using regex.

Ex:

```<code>import pandas as pd
df = pd.DataFrame({'col':['text https://random.website1.com text', 'text https://random.website2.com']})
#Ref https://stackoverflow.com/questions/10475027/extracting-url-link-using-regular-expression-re-string-matching-python
df["col_new"] = df["col"].str.replace(r'https?://[^\s<>"]+|www\.[^\s<>"]+', "")
print(df)

                                     col     col_new
0  text https://random.website1.com text  text  text
1       text https://random.website2.com       text
</code>```

Body:
I have the following dataframe:

import pandas as pd
df = pd.DataFrame({'col':['text https://random.website1.com text', 'text https://random.website2.com']})

I would like to remove all the links from this column.

Any ideas ?

Body:
Using regex.

Ex:

import pandas as pd
df = pd.DataFrame({'col':['text https://random.website1.com text', 'text https://random.website2.com']})
#Ref https://stackoverflow.com/questions/10475027/extracting-url-link-using-regular-expression-re-string-matching-python
df["col_new"] = df["col"].str.replace(r'https?://[^\s<>"]+|www\.[^\s<>"]+', "")
print(df)

                                     col     col_new
0  text https://random.website1.com text  text  text
1       text https://random.website2.com       text


问:
Macros vs functions
Early steps with macros and looking for clarification.

(defmacro nil! (x)
  (list 'setf x nil))
```

<p>Paul Graham writes on p169 of ANSI CL</p>

<blockquote>
  <p><code>nil!</code>, <code>ntimes</code> and <code>while</code> all have to be written as macros because all have to control the way in which their arguments are evaluated.</p>
</blockquote>

<p>I looked at <code>nil!</code> and thought, wait a minute, I want to try writing that as a function. Turned out he's right, as expected, but looking to pin down why. If I do</p>

<pre class="lang-lisp prettyprint-override"><code>(defun nil!f (x)
  (setf x nil))

(setf a 9)
(nil!f a)
; a is still 9, not nil
</code>```

Having forced myself into this, I note this is an odd use of a function, because I would not normally setf a parameter. If I was going to setf in a function it would more likely be a global, not a parameter.

If I have it correct, the parameter x creates a new lexical scope, which obscures the a which i set at the top level. Meaning we can pass in a value to a function, but not a variable.

Whereas with macros we can deal in variables.

Of course we can do this

(defun nil!f-a ()
  (setf a nil))
```

but now we lost the ability to pass in a variable to this particular function so it's a stumped version of original.

Hence the exact thing a macro allows you to do here is...  ?

Second question, is this a true statement

"In CL you cannot pass a variable into a function"

Here I yield...

答:
```<code>(defun nil!f (x)
  (setf x nil))
</code>```

If you do that, you can only set the new local variable x to nil. In plain Common Lisp it is not possible that this has another effect.

```<code>(defmacro nil! (x)
  (list 'setf x nil))

(nil! foo)
</code>```

Above expression will be replaced before execution with

```<code>(setf foo nil)
</code>```

We can check that:

```<code>CL-USER 110 > (macroexpand-1 '(nil! foo))
(SETF FOO NIL)
</code>```

Thus, since it is before execution, you can do all kinds of source (!) manipulation then.

"In CL you cannot pass a variable into a function"

That's true for lexical variables. Dynamically bound variables could be passed in as symbols.

Dynamically bound:

```<code>CL-USER 111 > (flet ((f (sym)
                       (symbol-value sym)))
                (let ((a 10))
                  (declare (special a))
                  (f 'a)))
10
</code>```

Lexically bound:

```<code>CL-USER 112 > (flet ((f (sym)
                       (symbol-value sym)))
                (let ((a 10))
                  (f 'a)))

Error: The variable A is unbound.
</code>```

Title: Macros vs functions

Body:
Early steps with macros and looking for clarification.

(defmacro nil! (x)
  (list 'setf x nil))

Paul Graham writes on p169 of ANSI CL

nil!, ntimes and while all have to be written as macros because all have to control the way in which their arguments are evaluated.

I looked at nil! and thought, wait a minute, I want to try writing that as a function. Turned out he's right, as expected, but looking to pin down why. If I do

(defun nil!f (x)
  (setf x nil))

(setf a 9)
(nil!f a)
; a is still 9, not nil

Having forced myself into this, I note this is an odd use of a function, because I would not normally setf a parameter. If I was going to setf in a function it would more likely be a global, not a parameter.

If I have it correct, the parameter x creates a new lexical scope, which obscures the a which i set at the top level. Meaning we can pass in a value to a function, but not a variable.

Whereas with macros we can deal in variables.

Of course we can do this

(defun nil!f-a ()
  (setf a nil))

but now we lost the ability to pass in a variable to this particular function so it's a stumped version of original.

Hence the exact thing a macro allows you to do here is...  ?

Second question, is this a true statement

"In CL you cannot pass a variable into a function"

Here I yield...

Body:
(defun nil!f (x)
  (setf x nil))

If you do that, you can only set the new local variable x to nil. In plain Common Lisp it is not possible that this has another effect.

(defmacro nil! (x)
  (list 'setf x nil))

(nil! foo)

Above expression will be replaced before execution with

(setf foo nil)

We can check that:

CL-USER 110 > (macroexpand-1 '(nil! foo))
(SETF FOO NIL)

Thus, since it is before execution, you can do all kinds of source (!) manipulation then.

"In CL you cannot pass a variable into a function"

That's true for lexical variables. Dynamically bound variables could be passed in as symbols.

Dynamically bound:

CL-USER 111 > (flet ((f (sym)
                       (symbol-value sym)))
                (let ((a 10))
                  (declare (special a))
                  (f 'a)))
10

Lexically bound:

CL-USER 112 > (flet ((f (sym)
                       (symbol-value sym)))
                (let ((a 10))
                  (f 'a)))

Error: The variable A is unbound.


问:
scipy.optimize failure with a "vectorized" implementation
I have an optimization problem (1d) coded in 2 ways - one using a for loop and an other using numpy arrays. The for loop version works fine but the numpy one fails.
Actually it is a bit more complicated, it can work with different starting points (!!) or if I choose an other optimization algo like CG.

The 2 versions (functions and gradients) are giving the same results and the returned types are also the same as far as I can tell.

Here is my example, what am I missing?

```<code>import numpy as np
from scipy.optimize import minimize

# local params
v1 = np.array([1., 1.])
v2 = np.array([1., 2.])
# local functions
def f1(x):
    s = 0
    for i in range(len(v1)):
        s += (v1[i]*x-v2[i])**2
    return 0.5*s/len(v1)
def df1(x):
    g = 0
    for i in range(len(v1)):
        g += v1[i]*(v1[i]*x-v2[i])
    return g/len(v1)
def f2(x):
    return 0.5*np.sum((v1*x-v2)**2)/len(v1)
def df2(x):
    return np.sum(v1*(v1*x-v2))/len(v1)

x0 = 10. # x0 = 2 works
# tests...
assert np.abs(f1(x0)-f2(x0)) < 1.e-6 and np.abs(df1(x0)-df2(x0)) < 1.e-6 \
        and np.abs((f1(x0+1.e-6)-f1(x0))/(1.e-6)-df1(x0)) < 1.e-4

# BFGS for f1: OK
o = minimize(f1, x0, method='BFGS', jac=df1)
if not o.success:
    print('FAILURE', o)
else:
    print('SUCCESS min = %f reached at %f' % (f1(o.x[0]), o.x[0]))
# BFGS for f2: failure
o = minimize(f2, x0, method='BFGS', jac=df2)
if not o.success:
    print('FAILURE', o)
else:
    print('SUCCESS min = %f reached at %f' % (f2(o.x[0]), o.x[0]))
</code>```

The error I get is

```<code>A1 = I - sk[:, numpy.newaxis] * yk[numpy.newaxis, :] * rhok
IndexError: invalid index to scalar variable.
</code>```

but I doesn't really helps me since it can work with some other starting values.

I am using an all new fresh python install (python 3.5.2, scipy 0.18.1 and numpy 1.11.3).

答:
The solver expects the return value of jacobian df2 to be the same shape as its input x. Even though you passed in a scalar here, it's actually converted into a single element ndarray. Since you used np.sum, your result became scalar and that causes strange things to happen.

Enclose the scalar result of df2 with np.array, and your code should work.

Body:
I have an optimization problem (1d) coded in 2 ways - one using a for loop and an other using numpy arrays. The for loop version works fine but the numpy one fails.
Actually it is a bit more complicated, it can work with different starting points (!!) or if I choose an other optimization algo like CG.

The 2 versions (functions and gradients) are giving the same results and the returned types are also the same as far as I can tell.

Here is my example, what am I missing?

import numpy as np
from scipy.optimize import minimize

# local params
v1 = np.array([1., 1.])
v2 = np.array([1., 2.])
# local functions
def f1(x):
    s = 0
    for i in range(len(v1)):
        s += (v1[i]*x-v2[i])**2
    return 0.5*s/len(v1)
def df1(x):
    g = 0
    for i in range(len(v1)):
        g += v1[i]*(v1[i]*x-v2[i])
    return g/len(v1)
def f2(x):
    return 0.5*np.sum((v1*x-v2)**2)/len(v1)
def df2(x):
    return np.sum(v1*(v1*x-v2))/len(v1)

x0 = 10. # x0 = 2 works
# tests...
assert np.abs(f1(x0)-f2(x0)) < 1.e-6 and np.abs(df1(x0)-df2(x0)) < 1.e-6 \
        and np.abs((f1(x0+1.e-6)-f1(x0))/(1.e-6)-df1(x0)) < 1.e-4

# BFGS for f1: OK
o = minimize(f1, x0, method='BFGS', jac=df1)
if not o.success:
    print('FAILURE', o)
else:
    print('SUCCESS min = %f reached at %f' % (f1(o.x[0]), o.x[0]))
# BFGS for f2: failure
o = minimize(f2, x0, method='BFGS', jac=df2)
if not o.success:
    print('FAILURE', o)
else:
    print('SUCCESS min = %f reached at %f' % (f2(o.x[0]), o.x[0]))

The error I get is

A1 = I - sk[:, numpy.newaxis] * yk[numpy.newaxis, :] * rhok
IndexError: invalid index to scalar variable.

but I doesn't really helps me since it can work with some other starting values.

I am using an all new fresh python install (python 3.5.2, scipy 0.18.1 and numpy 1.11.3).


问:
How to get the celery.Task object from the @app.task
I have a task function:

```<code>@app.task(base=ProcessingTask)
def do_processing_task(args):
</code>```

ProcessingTask inherits celery.Task:

```<code>class ProcessingTask(celery.Task):
    def on_success(self, res, task_id, args, kwargs):
</code>```

I start the task remotely with

```<code>result = app.send_task("workerTasks.do_processing_task", args=[args])
</code>```

(I don't have access to the workerTasks file from the server file which calls this, so send_task is the route I need to take)

Within do_processing_task I'd like to get the instance of the ProcessingTask object so I can add some data to it that I can use in do_processing_task::on_success.

Is this possible?  Thanks.

答:
Bound tasks

A task being bound means the first argument to the task will always be the task instance (self), just like Python bound methods:

```<code>logger = get_task_logger(__name__)

@task(bind=True)
def add(self, x, y):
    logger.info(self.request.id)
</code>```

Body:
I have a task function:

@app.task(base=ProcessingTask)
def do_processing_task(args):

ProcessingTask inherits celery.Task:

class ProcessingTask(celery.Task):
    def on_success(self, res, task_id, args, kwargs):

I start the task remotely with

result = app.send_task("workerTasks.do_processing_task", args=[args])

(I don't have access to the workerTasks file from the server file which calls this, so send_task is the route I need to take)

Within do_processing_task I'd like to get the instance of the ProcessingTask object so I can add some data to it that I can use in do_processing_task::on_success.

Is this possible?  Thanks.

Body:
Bound tasks

A task being bound means the first argument to the task will always be the task instance (self), just like Python bound methods:

logger = get_task_logger(__name__)

@task(bind=True)
def add(self, x, y):
    logger.info(self.request.id)


问:
Need to fetch date, and get for how many hours date is booked from mysql
I am working on hotel booking, In which i am storing pickup_date and return_date data, table name is booked, I need to get date from booked table and need to check for how many hours that date is booked, can anyone please help me for this query, i don't have idea how to get that, Here i have added my table data, and also added my required output

Booked table

I need its output as below :

```<code>|----Date---|---Duration---|
|2019-06-06 |    18.15     |
|2019-06-07 |    19.45     |
|2019-06-08 |    21.15     |
|2019-06-09 |    24.00     |
|2019-06-10 |    24.00     |
|2019-06-11 |    24.00     |
|2019-06-12 |    09.00     |
</code>```

答:
You can use function TIMEDIFF()

```<code>SELECT pickup_date, TIMEDIFF(return_date, pickup_date) duration FROM booked
</code>```

Duration will be returned in format HH:MM:SS. Not exactly what you want but you can play with that result

Body:
I am working on hotel booking, In which i am storing pickup_date and return_date data, table name is booked, I need to get date from booked table and need to check for how many hours that date is booked, can anyone please help me for this query, i don't have idea how to get that, Here i have added my table data, and also added my required output

Booked table

I need its output as below :

|----Date---|---Duration---|
|2019-06-06 |    18.15     |
|2019-06-07 |    19.45     |
|2019-06-08 |    21.15     |
|2019-06-09 |    24.00     |
|2019-06-10 |    24.00     |
|2019-06-11 |    24.00     |
|2019-06-12 |    09.00     |

Body:
You can use function TIMEDIFF()

SELECT pickup_date, TIMEDIFF(return_date, pickup_date) duration FROM booked

Duration will be returned in format HH:MM:SS. Not exactly what you want but you can play with that result


问:
How do I set the value in a command shell for dotnet core
Running dotnet core command dotnet run in a command line I found this

You can opt out of telemetry by setting a DOTNET_CLI_TELEMETRY_OPTOUT environment variable to 1 using your favorite shell.

How do I set this variable?

Thanks for your time.

答:
For fish shell user,</p>

```<code>set -Ux DOTNET_CLI_TELEMETRY_OPTOUT 1
</code>```

Body:
For fish shell user,

set -Ux DOTNET_CLI_TELEMETRY_OPTOUT 1


问:
javascript - Show symbol rather text in button
I'm using a button to open a menu but I liked that this one shows up the menu symbol instead of the 'Menu' text.

As below:

☰ ->  ☰

✖ -> ✖

function toggleText(button_id) {
  var el = document.getElementById(button_id);
  if (el.firstChild.data == "✖") {
    el.firstChild.data = '☰';
  } else {
    el.firstChild.data = "✖";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="playlist-toggle" class="btn-playlist" onclick="toggleText(this.id);">☰</button></code>```

答:
Try using innerHTML and pass the button element directly using this:

function toggleText(button) {
  if (button.innerHTML == "✖" || button.innerHTML == "✖") {
    button.innerHTML = '☰';
  } else {
    button.innerHTML = '✖';
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="playlist-toggle" class="btn-playlist" onclick="toggleText(this);">☰</button></code>```

Note: The innerHTML can be either ✖ or ✖, so check for both.

Body:
I'm using a button to open a menu but I liked that this one shows up the menu symbol instead of the 'Menu' text.

As below:

&#9776; ->  ☰

&#10006; -> ✖

function toggleText(button_id) {
  var el = document.getElementById(button_id);
  if (el.firstChild.data == "✖") {
    el.firstChild.data = '☰';
  } else {
    el.firstChild.data = "✖";
  }
}

<button id="playlist-toggle" class="btn-playlist" onclick="toggleText(this.id);">☰</button>

Body:
Try using innerHTML and pass the button element directly using this:

function toggleText(button) {
  if (button.innerHTML == "&#10006;" || button.innerHTML == "✖") {
    button.innerHTML = '&#9776;';
  } else {
    button.innerHTML = '&#10006;';
  }
}

<button id="playlist-toggle" class="btn-playlist" onclick="toggleText(this);">&#9776;</button>

Note: The innerHTML can be either &#10006; or ✖, so check for both.


问:
Wordpress xmlrpc.php 301 Moved Permanently
I have a site setup on Digital Ocean using their Wordpress droplet installer. I have then installed Jetpack.

The Site Health tool reported that Jetpack is not connected and that I should visit the Jetpack.com debugger.  I did so and put my website in. The error I get:

```<code>XML-RPC is not responding correctly ( 200 )
</code>```

When visiting the url mywebaddress.com/xmlrpc.php I just get redirected to the main URL of the site.

As recommended by Jetpack I went to a terminal and ran

```<code>curl -A 'Jetpack by WordPress.com' -d '<methodCall><methodName>demo.sayHello</methodName></methodCall>' https://mywebaddress.com/xmlrpc.php
</code>```

When I do so I get the following coming back.

```<code><!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="https://mywebaddress.com/">here</a>.</p>
<hr>
<address>Apache/2.4.29 (Ubuntu) Server at mywebaddress.com Port 443</address>
</body></html>
</code>```

I have checked the .htaccess file and this contains only comments.
I have checked /etc/apache2/apache2.conf and can find no redirects there.

So my question is, can anyone tell me what might be causing this 301 Redirect?

答:
Found the answer
I have just located this file:

/etc/apache2/conf-enabled/block-xmlrpc.conf

This had this inside

```<code><IfModule mod_rewrite.c>
    <Directory / >
        Redirect 301 /xmlrpc.php /
    </Directory>
</IfModule>
</code>```

This file was causing the redirect. Have commented out its contents for now.
I didn't create this, so I must assume DigitalOcean create it when doing the Wordpress one click install

Body:
I have a site setup on Digital Ocean using their Wordpress droplet installer. I have then installed Jetpack.

The Site Health tool reported that Jetpack is not connected and that I should visit the Jetpack.com debugger.  I did so and put my website in. The error I get:

XML-RPC is not responding correctly ( 200 )

When visiting the url mywebaddress.com/xmlrpc.php I just get redirected to the main URL of the site.

As recommended by Jetpack I went to a terminal and ran

curl -A 'Jetpack by WordPress.com' -d '<methodCall><methodName>demo.sayHello</methodName></methodCall>' https://mywebaddress.com/xmlrpc.php

When I do so I get the following coming back.

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>301 Moved Permanently</title>

Moved Permanently

The document has moved here.

<address>Apache/2.4.29 (Ubuntu) Server at mywebaddress.com Port 443</address>

I have checked the .htaccess file and this contains only comments.
I have checked /etc/apache2/apache2.conf and can find no redirects there.

So my question is, can anyone tell me what might be causing this 301 Redirect?

Body:
Found the answer
I have just located this file:

/etc/apache2/conf-enabled/block-xmlrpc.conf

This had this inside

<IfModule mod_rewrite.c>
    <Directory / >
        Redirect 301 /xmlrpc.php /
    </Directory>
</IfModule>

This file was causing the redirect. Have commented out its contents for now.
I didn't create this, so I must assume DigitalOcean create it when doing the Wordpress one click install


问:
Spring Security 3.1.3 request querystring stripped
I am securing my application using Spring Security 3.1.3 and I have a requirement to allow users to login via a link in a third-party application.

However, the link in the third-party application will redirect to a specific resource and not to the login page, where the resource that the user wishes
to access will be defined as a querystring parameter. So, for example, the link would be of the form :

//server.com/app/build/panel.jsp?resourceid='blah'

When a user clicks this link they should be taken to the login page defined in my Spring Security configuration and if authenticated then should be redirected
to the original link including the querystring parameter. The querystring parameter has no influence on how the user should be authenticated it's
merely an id of resource.

Now, this all works fine apart from the querystring, which gets stripped by Spring Security before it enters the request processing flow.

This is shown in the debug output from Spring Security;

org.springframework.security.web.savedrequest.HttpSessionRequestCache: DefaultSavedRequest added to Session:
  DefaultSavedRequest[http://server.com:8080/app/build/panel.jsp]

ie, the querystring is not saved and resourceid='blah' has been removed.

Note, I'm currently using Ant matching. I have no need to actually match against the querystring.

In earlier versions of Spring Security, it seemed like you could influence this behaviour by using a BeanPostProcessor as per this post,
Spring Security - Url with request parameters rules ignored. But the method
DefaultFilterInvocationSecurityMetadataSource.setStripQueryStringFromUrls() has been removed from Spring Security 3.1.3.

How do I configure Spring Security to not strip the querystring from the original request? So that when the user is redirected after the login to
the original URL the querystring parameter will be retained?

Many Thanks
Howard

答:
For others on a similar issue, refer  the link:
https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html

Extract:There is a danger that when an application is deployed in a container which does not strip path parameters from these values, an attacker could add them to the requested URL in order to cause a pattern match to succeed or fail unexpectedly.

However this stripping is meant to firmly protect the pattern matching for login. It doesnt means the query parameters are not available from the HTTP request, they should be.


问:
Error with loops in javascript?
I have, in multiple parts of my code, snippits similar to this:

```<code>function updateScore() {
    var currentPoints=0;
    for (nni=0;nni<currentSession.Questions.length+1;nni++) {
        currentPoints+=currentSession.Questions[nni].Score;
    }
    alert('hi');
    document.getElementById('quiz_score').innerHTML='%'+(currentPoints/currentSession.TotalPoints)*100
}
</code>```

Everything works fine... until after the loop.  This happens in multiple cases.  The alert won't even show after the loop ends.  It's like the function just stops...

I'm also having problems where the iterator (in this case, nni) stays global.  Basically, I can't use that variable ever again in my code because for some reason, if I change nni, it messes up the for loop.  I'm obvisouly not doing something right.  I'm a self tought Javascripter (basically googling anything I don't know, I've never taken a lesson).  I must be missing something about for loops.

Thanks if you can!

答:
Your nni variable is global because it is not declared with the var keyword:

```<code> function updateScore() {
        var currentPoints = 0;
        // nni declared with var:
        for (var nni = 0; nni < currentSession.Questions.length + 1; nni++) {
            currentPoints += currentSession.Questions[nni].Score;
        }

        alert('hi');
        document.getElementById('quiz_score').innerHTML= '%' + ((currentPoints / currentSession.TotalPoints) * 100)
    }
</code>```

Also, your evaluation statement is run every time with your incrementation. Move your length evaluation to your declarations:

```<code>for (var nni = 0, len = currentSession.Questions.length + 1; nni < len; nni++) {
</code>```

Title: Error with loops in javascript?

Body:
I have, in multiple parts of my code, snippits similar to this:

function updateScore() {
    var currentPoints=0;
    for (nni=0;nni<currentSession.Questions.length+1;nni++) {
        currentPoints+=currentSession.Questions[nni].Score;
    }
    alert('hi');
    document.getElementById('quiz_score').innerHTML='%'+(currentPoints/currentSession.TotalPoints)*100
}

Everything works fine... until after the loop.  This happens in multiple cases.  The alert won't even show after the loop ends.  It's like the function just stops...

I'm also having problems where the iterator (in this case, nni) stays global.  Basically, I can't use that variable ever again in my code because for some reason, if I change nni, it messes up the for loop.  I'm obvisouly not doing something right.  I'm a self tought Javascripter (basically googling anything I don't know, I've never taken a lesson).  I must be missing something about for loops.

Thanks if you can!

Body:
Your nni variable is global because it is not declared with the var keyword:

 function updateScore() {
        var currentPoints = 0;
        // nni declared with var:
        for (var nni = 0; nni < currentSession.Questions.length + 1; nni++) {
            currentPoints += currentSession.Questions[nni].Score;
        }

        alert('hi');
        document.getElementById('quiz_score').innerHTML= '%' + ((currentPoints / currentSession.TotalPoints) * 100)
    }

Also, your evaluation statement is run every time with your incrementation. Move your length evaluation to your declarations:

for (var nni = 0, len = currentSession.Questions.length + 1; nni < len; nni++) {


问:
Spotfire How To Change Calculate Totals Using Iron Python
I have a Cross Table in my Spotfire Dashboard and am trying to change the "Calculate Totals" option using an Iron Python script.

I've found this link on Spotfire API. So, from what I understood, this information is stored in myVis.Totals. But, for whatever the reason, this seems to be a read-only property as can be seen here.

Have any of you ever had this problem and would know how to fix it?

This is my code:

from Spotfire.Dxp.Application.Visuals import *

# myVis is a script parameter of the type "Visualisation"
myVis = myVis.As[Visualization]()
myVis.Totals = CrossTableTotals.CalculationMode.SumOfCellValues
```

<p>This is the error I'm getting:</p>

```Traceback (most recent call last):
  File "<string>", line 5, in <module>
AttributeError: can't assign to read-only property Totals of type 'CrossTablePlot'

System.MissingMemberException: can't assign to read-only property Totals of type 'CrossTablePlot'
   at CallSite.Target(Closure , CallSite , Object , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
   at Microsoft.Scripting.Interpreter.DynamicInstruction`3.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 arg1)
   at IronPython.Compiler.PythonScriptCode.RunWorker(CodeContext ctx)
   at Microsoft.Scripting.Hosting.ScriptSource.Execute(ScriptScope scope)
   at Spotfire.Dxp.Application.IronPython27.IronPythonScriptEngine.ExecuteForDebugging(String scriptCode, Dictionary`2 scope, Stream outputStream)
```

答:
Try this

myVis.Totals.DefaultCalculationMode=CrossTableTotals.CalculationMode.SumOfCellValues

Gaia

Body:
I have a Cross Table in my Spotfire Dashboard and am trying to change the "Calculate Totals" option using an Iron Python script.

I've found this link on Spotfire API. So, from what I understood, this information is stored in myVis.Totals. But, for whatever the reason, this seems to be a read-only property as can be seen here.

Have any of you ever had this problem and would know how to fix it?

This is my code:

from Spotfire.Dxp.Application.Visuals import *

# myVis is a script parameter of the type "Visualisation"
myVis = myVis.As[Visualization]()
myVis.Totals = CrossTableTotals.CalculationMode.SumOfCellValues

This is the error I'm getting:

Traceback (most recent call last):
  File "<string>", line 5, in <module>
AttributeError: can't assign to read-only property Totals of type 'CrossTablePlot'

System.MissingMemberException: can't assign to read-only property Totals of type 'CrossTablePlot'
   at CallSite.Target(Closure , CallSite , Object , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
   at Microsoft.Scripting.Interpreter.DynamicInstruction`3.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 arg1)
   at IronPython.Compiler.PythonScriptCode.RunWorker(CodeContext ctx)
   at Microsoft.Scripting.Hosting.ScriptSource.Execute(ScriptScope scope)
   at Spotfire.Dxp.Application.IronPython27.IronPythonScriptEngine.ExecuteForDebugging(String scriptCode, Dictionary`2 scope, Stream outputStream)


问:
Train and accept the added Questions in QnA programmatically
I am trying to add questions to existing questions in my knowledge base in QnA Maker like this:

 public async static void CallTrain(string host, FeedbackRecords feedbackRecords, string kbId, string key, CancellationToken cancellationToken)
   {
         var uri = host + "/knowledgebases/" + kbId + "/train/";

         using (var client = new HttpClient())
         {
             using (var request = new HttpRequestMessage())
             {
                 request.Method = HttpMethod.Post;
                 request.RequestUri = new Uri(uri);
                 request.Content = new
                       StringContent(JsonConvert.SerializeObject(feedbackRecords),
                       Encoding.UTF8, "application/json");
                 request.Headers.Add("Authorization", "EndpointKey " + key);

                 var response = await client.SendAsync(request, cancellationToken);
                 await response.Content.ReadAsStringAsync();
             }
         }
     }
```

<p>FeedbackRecords sample:</p>

```[
  {
    "userId":"xxx",
    "userQuestion":"what is your name",
    "qnaId":1
  }
]

```

Everything works fine and the questions were added, BUT I must accept the added questions in the QnA Maker Portal first to see them.

So my question is how to accept all the questions progrmatically and retrain the knowledge base?

答:
Unfortunately it doesn't look like this is possible using the QnA Maker API.

Edit

This has been confirmed as per the OPs comment below it has been confirmed that this is not currently available but it is on the development backlog so may be available at the link I provided above in the future.

Body:
I am trying to add questions to existing questions in my knowledge base in QnA Maker like this:

 public async static void CallTrain(string host, FeedbackRecords feedbackRecords, string kbId, string key, CancellationToken cancellationToken)
   {
         var uri = host + "/knowledgebases/" + kbId + "/train/";

         using (var client = new HttpClient())
         {
             using (var request = new HttpRequestMessage())
             {
                 request.Method = HttpMethod.Post;
                 request.RequestUri = new Uri(uri);
                 request.Content = new
                       StringContent(JsonConvert.SerializeObject(feedbackRecords),
                       Encoding.UTF8, "application/json");
                 request.Headers.Add("Authorization", "EndpointKey " + key);

                 var response = await client.SendAsync(request, cancellationToken);
                 await response.Content.ReadAsStringAsync();
             }
         }
     }

FeedbackRecords sample:

[
  {
    "userId":"xxx",
    "userQuestion":"what is your name",
    "qnaId":1
  }
]

Everything works fine and the questions were added, BUT I must accept the added questions in the QnA Maker Portal first to see them.

So my question is how to accept all the questions progrmatically and retrain the knowledge base?


问:
HTML Input Time, where min is pm (late) and max is am (early)
I have an input box, with a type of "time". I want to have a late time (23:00pm) as a min value, and an early time (6:00am) as a max value - creating a range of 23pm - 6am. (ie. 11pm, 12pm, 1am, 2am, 3am, 4am, 5am, 6am).

I've tried using Javascript, although I want to use it as a last resort. I don't want the native component to show up with values that I don't want the user to select (for example, on mobile devices).

Setting the 'min' value to 00:00:00 and the 'max' value to "06:00:00" works as intended. It's when the min value is before midnight it becomes an issue.

I'd expect the min and max values to create a range, but that doesn't work as expected.

答:
I experimented a little using the :invalid CSS pseudo-class but I couldn't come up with anything.

Note that in Firefox (unlike Chrome), the browser does not include up and down arrows on any <input type="time"> form element, so the min and max attributes have no effect.

I note that Mozilla Developer Network says the following:

By default, <input type="time"> does not apply any validation to
  entered values, other than the user agent's interface generally not
  allowing you to enter anything other than a time value. This is
  helpful (assuming the time input is fully supported by the user
  agent), but you can't entirely rely on the value to be a proper time
  string, since it might be an empty string (""), which is allowed. It's
  also possible for the value to look roughly like a valid time but not
  be correct, such as 25:05.

Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/time#Validation


问:
Angular 4 - get input value
I would like to know how to get the value from an input on angular 4.
I looked over the documentation on angular and the example with the key event doesn't work very well for me and I can't find a proper example how to do this so please help me out

The problem:
I try to read the input's value and after submiting the value to another component that will add the value to a select tag(e.g. send the name of the person to a list for a select tag)

答:
You can also use template reference variables

<form (submit)="onSubmit(player.value)">
   <input #player placeholder="player name">
</form>
```

<pre class="lang-js prettyprint-override"><code>onSubmit(playerName: string) {
  console.log(playerName)
}
</code>```

Title: Angular 4 - get input value

Body:
You can also use template reference variables

<form (submit)="onSubmit(player.value)">
   <input #player placeholder="player name">
</form>

onSubmit(playerName: string) {
  console.log(playerName)
}


问:
Determine if your action was requested directly or redirected to?
Say I'm on:

```<code>example.com/foo
</code>```

I click on a button that goes to the root_path, typically it would be:

```<code>example.com/
</code>```

In the controller action that receives the request it's determined that the user should be redirected to:

```<code>example.com/bar
</code>```

In the controller action that receives that request I now wish to know if the user has been redirected via the root_path, so I check out the request.referer. But I discover that the referer is not example.com/, but example.com/foo.

I have inspected the request object, but it seems there is no trace of the paths a request have been redirected through. Is that correct, or is there a tell?

Here is the log:

```<code>Started GET "/" for 127.0.0.1 at 2019-05-29 09:40:37 +0200
Processing by HomeController#index as HTML
  Parameters: {}
Redirected to https://example.com/bar
Completed 302 Found in 21ms

Started GET "/bar" for 127.0.0.1 at 2019-05-29 09:40:37 +0200
Processing by BarController#index as HTML
  Parameters: {}
Completed 200 OK in 285ms (Views: 274.1ms)
</code>```

I realise I could add a param when redirecting, but before that I want to make sure the informations are not already in the session.

答:
You can, for example, use flash to set some custom property like :redirected_from:

redirect_to '/foo', flash: { redirected_from: request.path }
```

Which you can later read in example.com/bar controller action

Body:
Say I'm on:

example.com/foo

I click on a button that goes to the root_path, typically it would be:

example.com/

In the controller action that receives the request it's determined that the user should be redirected to:

example.com/bar

In the controller action that receives that request I now wish to know if the user has been redirected via the root_path, so I check out the request.referer. But I discover that the referer is not example.com/, but example.com/foo.

I have inspected the request object, but it seems there is no trace of the paths a request have been redirected through. Is that correct, or is there a tell?

Here is the log:

Started GET "/" for 127.0.0.1 at 2019-05-29 09:40:37 +0200
Processing by HomeController#index as HTML
  Parameters: {}
Redirected to https://example.com/bar
Completed 302 Found in 21ms

Started GET "/bar" for 127.0.0.1 at 2019-05-29 09:40:37 +0200
Processing by BarController#index as HTML
  Parameters: {}
Completed 200 OK in 285ms (Views: 274.1ms)

I realise I could add a param when redirecting, but before that I want to make sure the informations are not already in the session.

Body:
You can, for example, use flash to set some custom property like :redirected_from:

redirect_to '/foo', flash: { redirected_from: request.path }

Which you can later read in example.com/bar controller action


问:
Python add entire column to csv file, without reading the file content
I need to add columns to a csv file using Python. The only way i can think of doing this is reading the whole file, editing each row to add 1 element, and then write again to the file. However i really don't want to do it this way because of the size of the file (over 32000 rows, seems a lot of reading and writing everytime i want to add a column). Even using the csv module i think the principle would be the same, read everything, edit and write again.

to be clear, below is a csv file example.

```<code>1,2
1,2
1,2
1,2
</code>```

i want to add a third column so the file would become:

```<code>1,2,3
1,2,3
1,2,3
1,2,3
</code>```

If i wanted to add an entire row (or line) i could use open(csvfile, 'a') and "append" the last row to the file. Is there a similar option to add a column?

答:
For an original csv file, say foo.csv

```<code>1,2
1,2
1,2
1,2
</code>```

Just create another file holding the column to be added, say bar.csv

```<code>3
3
3
3
</code>```

Then, Unix's paste command can be called from within python using os.system as

```<code>import os
os.system("paste foo.csv  bar.csv -d ',' > output.csv")
</code>```

This gives the result output.csv as

```<code>1,2,3
1,2,3
1,2,3
1,2,3
</code>```

Body:
I need to add columns to a csv file using Python. The only way i can think of doing this is reading the whole file, editing each row to add 1 element, and then write again to the file. However i really don't want to do it this way because of the size of the file (over 32000 rows, seems a lot of reading and writing everytime i want to add a column). Even using the csv module i think the principle would be the same, read everything, edit and write again.

to be clear, below is a csv file example.

1,2
1,2
1,2
1,2

i want to add a third column so the file would become:

1,2,3
1,2,3
1,2,3
1,2,3

If i wanted to add an entire row (or line) i could use open(csvfile, 'a') and "append" the last row to the file. Is there a similar option to add a column?

Body:
For an original csv file, say foo.csv

1,2
1,2
1,2
1,2

Just create another file holding the column to be added, say bar.csv

3
3
3
3

Then, Unix's paste command can be called from within python using os.system as

import os
os.system("paste foo.csv  bar.csv -d ',' > output.csv")

This gives the result output.csv as

1,2,3
1,2,3
1,2,3
1,2,3


问:
Compare the columns of a dataframe in reverse order and create a new column with the index of the column which has value 0
I have imported data from a csv file into my program and then used set_index to set 'rule_id' as index. I used this code:

```<code>df = pd.read_excel('stack.xlsx')
df.set_index(['rule_id'])
</code>```

and the data looks like this:

Now I want to compare one column with another but in reverse order , for eg; I want to compare 'c' data with 'b' , then compare 'b' with 'a' and so on and create another column after the comparison which contains the index of the column where the value was zero. If both the columns have value 0 , then Null should be updated in the new column and if both the comparison values are other than 0 , then also Null should be updated in the new column.
The result should look like this:

I am not able to write the code of how should I approach this problem, if you guys could help me , that would be great.

Edit: A minor edit. I have imported the data from an excel which looks like this , this is just a part of data , there are multiple columns:

Then I used pivot_table to manipulate the data as per my requirement using this code:

```<code>df = df.pivot_table(index = 'rule_id' , columns = ['date'], values = 'rid_fc', fill_value = 0)
</code>```

and my data looks like this now:

Now I want to compare one column with another but in reverse order , for eg; I want to compare '2019-04-25 16:36:32' data with '2019-04-25 16:29:05' , then compare '2019-04-25 16:29:05' with '2019-04-25 16:14:14' and so on and create another column after the comparison which contains the index of the column where the value was zero. If both the columns have value 0 , then Null should be updated in the new column and if both the comparison values are other than 0 , then also Null should be updated in the new column.

答:
You can make use of this code snippet. I did not have time to perfect it with loops etc. so please make the change as per requirements.

import pandas as pd
import numpy as np

# Data
print(df.head())
   a  b  c
0  0  7  6
1  0  0  1
2  0  2  2

cp = df.copy()
cp[cp != 0] = 1
cp['comp1'] = cp['a'] + cp['b']
cp['comp2'] = cp['b'] + cp['c']

# Logic
cp = cp.replace([0, 1, 2], [1, np.nan, 0])
cp[['a', 'b', 'c']] = df[['a', 'b', 'c']]

# Results
print(cp.head())
   a  b  c  comp1  comp2
0  0  7  6    NaN    0.0
1  0  0  1    1.0    NaN
2  0  2  2    NaN    0.0
```

Body:
I have imported data from a csv file into my program and then used set_index to set 'rule_id' as index. I used this code:

df = pd.read_excel('stack.xlsx')
df.set_index(['rule_id'])

and the data looks like this:

Now I want to compare one column with another but in reverse order , for eg; I want to compare 'c' data with 'b' , then compare 'b' with 'a' and so on and create another column after the comparison which contains the index of the column where the value was zero. If both the columns have value 0 , then Null should be updated in the new column and if both the comparison values are other than 0 , then also Null should be updated in the new column.
The result should look like this:

I am not able to write the code of how should I approach this problem, if you guys could help me , that would be great.

Edit: A minor edit. I have imported the data from an excel which looks like this , this is just a part of data , there are multiple columns:

Then I used pivot_table to manipulate the data as per my requirement using this code:

df = df.pivot_table(index = 'rule_id' , columns = ['date'], values = 'rid_fc', fill_value = 0)

and my data looks like this now:

Now I want to compare one column with another but in reverse order , for eg; I want to compare '2019-04-25 16:36:32' data with '2019-04-25 16:29:05' , then compare '2019-04-25 16:29:05' with '2019-04-25 16:14:14' and so on and create another column after the comparison which contains the index of the column where the value was zero. If both the columns have value 0 , then Null should be updated in the new column and if both the comparison values are other than 0 , then also Null should be updated in the new column.


问:
Can a JVM array be realloc()'d?
So the C language has a realloc() procedure that can be used to grow allocated [edit] memory in-place.

Does the equivalent concept exist for the JVM/Java? Either for Arrays or nio.Buffers? I don't mind whether this is part of the JDK or as an external library e.g. sun.unsafe.

答:
First of all, the C function realloc is not a tool that can grow arrays, but rather, memory previously allocated via malloc, calloc, or realloc. In contrast, C arrays may reside on the stack or the static memory area and may even be embedded in a larger structure.

Then, the function has the semantics of invalidating the original pointer like free does and returning a new pointer. So if you have copies of the pointer flying around, it’s your duty of replacing all occurrences with the new pointer.

Of course, Java does not support invalidating references. Guaranteeing the validity of every non-null object reference, is the fundamental property of Java’s memory management.

So if you want the equivalent of C’s realloc, you’d have to use pointers and not arrays. Then sun.misc.Unsafe has all related operations

public long allocateMemory(long bytes)

public long reallocateMemory(long address, long bytes)

public void freeMemory(long address)

public float getXyz(long address)¹

public void putXyz(long address, xyz x)¹

¹ where “xyz” stands for a primitive type

If you want to resize an array, use

```<code>array = Arrays.copyOf(array, newSize);
</code>```

this will not invalidate old references, so if you fail to replace all references to the old array, code using these old references will access the old array.

But if array is the only reference to the particular array or your code provenly replaces all existing references, a JVM may in theory enable an in-place resizing operation instead of copying the contents, see also Does Java JIT cheat when running JDK code?

But checking the necessary preconditions might be more expensive than copying the array contents. The only scenario where I can imagine an applicability, would be if the array was the last object allocated by the same thread, so it could be proven that the reference did not escape yet and there’s no object behind the array within the allocation space.

For a JVM having such an optimization, you may get the benefit automatically when repeatedly adding to an ArrayList, as that class ensures that it is the only holder of the reference to its internal array and it uses Arrays.copyOf internally for resizing.

Title: Can a JVM array be realloc()'d?

Body:
First of all, the C function realloc is not a tool that can grow arrays, but rather, memory previously allocated via malloc, calloc, or realloc. In contrast, C arrays may reside on the stack or the static memory area and may even be embedded in a larger structure.

Then, the function has the semantics of invalidating the original pointer like free does and returning a new pointer. So if you have copies of the pointer flying around, it’s your duty of replacing all occurrences with the new pointer.

Of course, Java does not support invalidating references. Guaranteeing the validity of every non-null object reference, is the fundamental property of Java’s memory management.

So if you want the equivalent of C’s realloc, you’d have to use pointers and not arrays. Then sun.misc.Unsafe has all related operations

public long allocateMemory(long bytes)

public long reallocateMemory(long address, long bytes)

public void freeMemory(long address)

public float getXyz(long address)¹

public void putXyz(long address, xyz x)¹

¹ where “xyz” stands for a primitive type

If you want to resize an array, use

array = Arrays.copyOf(array, newSize);

this will not invalidate old references, so if you fail to replace all references to the old array, code using these old references will access the old array.

But if array is the only reference to the particular array or your code provenly replaces all existing references, a JVM may in theory enable an in-place resizing operation instead of copying the contents, see also Does Java JIT cheat when running JDK code?

But checking the necessary preconditions might be more expensive than copying the array contents. The only scenario where I can imagine an applicability, would be if the array was the last object allocated by the same thread, so it could be proven that the reference did not escape yet and there’s no object behind the array within the allocation space.

For a JVM having such an optimization, you may get the benefit automatically when repeatedly adding to an ArrayList, as that class ensures that it is the only holder of the reference to its internal array and it uses Arrays.copyOf internally for resizing.


答:
Just change the actual text of the button rather than the child. Also note that the innerHTML can be either the entity or the rendered entity, so check that too:

function toggleText(button_id) {
  var el = document.getElementById(button_id);
  if (["✖", "✖"].includes(el.innerHTML)) {
    el.innerHTML = '☰';
  } else {
    el.innerHTML = "✖";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="playlist-toggle" class="btn-playlist" onclick="toggleText(this.id);">☰</button></code>```

Title: javascript - Show symbol rather text in button

Body:
Just change the actual text of the button rather than the child. Also note that the innerHTML can be either the entity or the rendered entity, so check that too:

function toggleText(button_id) {
  var el = document.getElementById(button_id);
  if (["&#10006;", "✖"].includes(el.innerHTML)) {
    el.innerHTML = '&#9776;';
  } else {
    el.innerHTML = "&#10006;";
  }
}

<button id="playlist-toggle" class="btn-playlist" onclick="toggleText(this.id);">&#9776;</button>