问:
Filter data by group & preserve empty groups
I wonder how can I filter my data by group, and preserve the groups that are empty?

Example:

```<code>year = c(1,2,3,1,2,3,1,2,3)
site = rep(c("a", "b", "d"), each = 3)
value = c(3,3,0,1,8,5,10,18,27)

df <- data.frame(year, site, value)
</code>```

I want to subset the rows where the value is more than 5. For some groups, this is never true. Filter function simply skips empty groups.

How can I keep my empty groups and have NA instead? Ideally, I would like to use dplyr funtions instead of base R.

My filtering approach, where .preserve does not preserve empty groups:

```<code>df %>%
  group_by(site) %>%
  filter(value > 5, .preserve = TRUE)
</code>```

Expected output:

```<code>    year site  value
  <dbl> <fct> <dbl>
1    NA a        NA
2     2 b         8
3     1 d        10
4     2 d        18
5     3 d        27
</code>```

答:
Using the nesting functionality of tidyr and applying purrr::map

```<code>df %>%
  group_by(site) %>%
  tidyr::nest() %>%
  mutate(data = purrr::map(data, . %>% filter(value > 5))) %>%
  tidyr::unnest(cols=c(data), keep_empty = TRUE)
</code>```

Body:
I wonder how can I filter my data by group, and preserve the groups that are empty?

Example:

year = c(1,2,3,1,2,3,1,2,3)
site = rep(c("a", "b", "d"), each = 3)
value = c(3,3,0,1,8,5,10,18,27)

df <- data.frame(year, site, value)

I want to subset the rows where the value is more than 5. For some groups, this is never true. Filter function simply skips empty groups.

How can I keep my empty groups and have NA instead? Ideally, I would like to use dplyr funtions instead of base R.

My filtering approach, where .preserve does not preserve empty groups:

df %>%
  group_by(site) %>%
  filter(value > 5, .preserve = TRUE)

Expected output:

    year site  value
  <dbl> <fct> <dbl>
1    NA a        NA
2     2 b         8
3     1 d        10
4     2 d        18
5     3 d        27

Body:
Using the nesting functionality of tidyr and applying purrr::map

df %>%
  group_by(site) %>%
  tidyr::nest() %>%
  mutate(data = purrr::map(data, . %>% filter(value > 5))) %>%
  tidyr::unnest(cols=c(data), keep_empty = TRUE)


来源: stackexchange

问:
Python 3: unsupported operand type(s) for -: 'str' and 'float'
I'm currently learning matplot and I saw this code on the official tutorial, but I got the error unsupported operand type(s) for -: 'str' and 'float'. How could I fix this?

```<code>import matplotlib.pyplot as plt
import numpy as np

names = ["a", "b", "c"]
values = [1, 10, 100]

plt.figure(figsize=(9, 3))

plt.subplot(131)
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.suptitle('Categorical Plotting')
plt.show()
</code>```

答: the provided code works well, I do not see any error (I'm using python 3.7):

ContentLicense: CC BY-SA 4.0

Body:
I'm currently learning matplot and I saw this code on the official tutorial, but I got the error unsupported operand type(s) for -: 'str' and 'float'. How could I fix this?

import matplotlib.pyplot as plt
import numpy as np

names = ["a", "b", "c"]
values = [1, 10, 100]

plt.figure(figsize=(9, 3))

plt.subplot(131)
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.suptitle('Categorical Plotting')
plt.show()


问:
MySQL query to assign a unique random number to each row
I wish to attach a column to my table which will be a random number from a sequential list = to the number of rows.

So, if my table had 999 rows, then the numbers 1 to 999 would be assigned randomly and uniquely.

Now, I figured that I could add a dummy TempRandomColumn=Rand(), sort by that and add the numbers sequentially using PHP. But that means 999 MySQL statements.

Is there a way to do this using a single MySQL statement?

Thanks for any pointers.

答:
```<code>SET @i=1;
SELECT t.*, @i:=@i+1 as RAND_NUM FROM your_table t ORDER BY RAND();
</code>```

OwnerDisplayName: Smokey McTokes

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
storing space in DB and displaying giving me problems
My spaces in text field get stored in mysql DB as 'Â nameÂ ' which was just like ' name ' in UI. But when i display it to screen it gets displayed properly. but when i get count of the variable like strlen($var) it gives me count as 8 instead of 6. So any thing wrong like the way i am doing?

答:
This has all the hallmarks of a charset mismatch.  This happens if your database is, for example, using an encoding of UTF8, but your web application is using an encoding of LATIN1.  I'd suggest double-checking that the same encoding scheme is used throughout both your database tables and your application code.  Also make sure that a SET NAMES query is run to explicitly set the charset.

It's also possible that if you're connecting directly to the database with a client (SQLYog or somesuch), then that's using a different encoding and displaying the data differently, even if both the web app in question and the database in question are using the same encoding.

One more thing, strlen doesn't handle encodings that use more than 1 byte per character very well.  You should be using mb_strlen instead.

http://uk3.php.net/manual/en/function.mb-strlen.php


问:
Can't find CMAKE_INSTALL_PREFIX folder
I'm following the guide from:

http://www.azerothcore.org/wiki/Installation

I'm having issues at the very last instructions under "compiling on windows" where I am asked to move a series of DLLs to a folder called CMAKE_INSTALL_PREFIX. I cannot find this folder, despite getting no errors from the compiler? visual studio I don't think things are building properly.

I get 3 warnings when compiling in visual studio,

Warning LNK4221 This object file does not define any previously undefined public symbols, so it will not be used by and link operation that consumes this library scripts Build\src\server\scripts\zone_alterac_mountains.obj 1

Warning LNK4221 This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library scripts \Build\src\server\scripts\zone_burning_steppes.obj 1

Warning C4715 'WorldSocket::ProcessIncoming': not all control paths return a value game c:\users\frith\azerothcore\src\server\game\server\worldsocket.cpp 727

I've restarted the entire process a few times and have made no progress. I'm under the impression I should see something in the destination folder, it is empty.

After some digging I found this in an error log in build/CMakefies

\Build\CMakeFiles\CMakeTmp\CheckIncludeFile.c(1): fatal error C1083: Cannot open include file: 'pthread.h': No such file or directory [\Build\CMakeFiles\CMakeTmp\cmTC_0e035.vcxproj]

I'm totally stuck.

答:
CMAKE_INSTALL_PREFIX is the location where you selected to install AC.

As the guide says:

Change CMAKE_INSTALL_PREFIX to the location where you will run your server from.

this happens in chapter 3) Compiling -> Compiling on Windows

Title: Can't find CMAKE_INSTALL_PREFIX folder


问:
How to add divider in the bottom navigation view
How can I add a divider in the Bottom Navigation view?
Basically a separator between the icons

Thank you

答:
You can easily create a divider between items something like that.</p>

```<code>  <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigation"
        style="@style/BottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_gravity="bottom"
        android:background="@drawable/item_bg"
        android:focusable="false"
        android:foreground="@drawable/ripple"
        android:theme="@style/BottomNavigationTheme"
        app:itemIconSize="@dimen/dimen_20dp"
        app:itemIconTint="@drawable/bottom_navigation_selector"
        app:itemTextColor="@color/color_selector"
        app:labelVisibilityMode="labeled"
        app:layout_behavior="@string/hide_bottom_view_on_scroll_behavior"
        app:layout_scrollFlags="scroll|enterAlways|snap">

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/line"
            android:layout_width="0.8dp"
            android:layout_height="@dimen/dimen_20dp"
            android:layout_marginTop="@dimen/dimen_5dp"
            android:layout_gravity="center"
            android:background="@color/textview_black">

        </androidx.appcompat.widget.AppCompatTextView>

    </com.google.android.material.bottomnavigation.BottomNavigationView>
</code>```

Body:
You can easily create a divider between items something like that.

  <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigation"
        style="@style/BottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_gravity="bottom"
        android:background="@drawable/item_bg"
        android:focusable="false"
        android:foreground="@drawable/ripple"
        android:theme="@style/BottomNavigationTheme"
        app:itemIconSize="@dimen/dimen_20dp"
        app:itemIconTint="@drawable/bottom_navigation_selector"
        app:itemTextColor="@color/color_selector"
        app:labelVisibilityMode="labeled"
        app:layout_behavior="@string/hide_bottom_view_on_scroll_behavior"
        app:layout_scrollFlags="scroll|enterAlways|snap">

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/line"
            android:layout_width="0.8dp"
            android:layout_height="@dimen/dimen_20dp"
            android:layout_marginTop="@dimen/dimen_5dp"
            android:layout_gravity="center"
            android:background="@color/textview_black">

        </androidx.appcompat.widget.AppCompatTextView>

    </com.google.android.material.bottomnavigation.BottomNavigationView>


问:
Is it possible to modify internal regions in R package maps?
I have a dataset whose rows represent the time frame and whose columns each represent one region of Italy. I need to plot this data on a map of Italy in R (I need the total sum on the entire period, so I'll only have one value per region).
I downloaded the package maps and loaded the map of Italy it_map <- map_data('italy')
Problem is, Italy is divided into 20 regions and tens of provinces. The map shows these province boundaries, but my data is aggregated at regional level.

Is there a way to combine the boundaries of all the provinces into their respective region?
Do I have to modify the "group" column in order to make it the same for all the provinces belonging to one region?

The map dataset is like this:

```<code>long lat group order region subregion
x.x  y.y   1     1   Bozen      NA
x.x  y.y   1     2   Bozen      NA
</code>```

etc...
where of course the column called "region" actually lists provinces.

Also, any suggestions for plotting nicely with ggplot2?
Thanks in advance for all the answers!

答:
You need a "region" column to denote the 20 regions (noting that the region column that is already in there denotes the 95 provinces as you say). Unfortunately, that particular map doesn't seem to have one.

So you'll have to either find another map that has those 20 regions as a column (did you try the mapIT package?) or try to do it yourself - but you'll need to know which provinces belong to which regions.

Create a data frame based on the unique provinces:

data_regions <- data.frame(province=unique(it_map$region), Region=NA, stringsAsFactors = FALSE)

Edit this data frame and fill in the values of the Region column yourself using your knowledge of Italy. Type the names (or assign a code). You should have a total of 20. This may take a bit of time.

Merge this data frame with the map data you already obtained from the maps package.

it_map <- it_map %>%
      rename(province=region) %>%
      inner_join(data_regions)

Plot it.

it_map %>%
  ggplot(aes(long, lat, group = group)) +
  geom_polygon(aes(fill = Region), color="white")

Hope that helps.

Body:
I have a dataset whose rows represent the time frame and whose columns each represent one region of Italy. I need to plot this data on a map of Italy in R (I need the total sum on the entire period, so I'll only have one value per region).
I downloaded the package maps and loaded the map of Italy it_map <- map_data('italy')
Problem is, Italy is divided into 20 regions and tens of provinces. The map shows these province boundaries, but my data is aggregated at regional level.

Is there a way to combine the boundaries of all the provinces into their respective region?
Do I have to modify the "group" column in order to make it the same for all the provinces belonging to one region?

The map dataset is like this:

long lat group order region subregion
x.x  y.y   1     1   Bozen      NA
x.x  y.y   1     2   Bozen      NA

etc...
where of course the column called "region" actually lists provinces.

Also, any suggestions for plotting nicely with ggplot2?
Thanks in advance for all the answers!


问:
Unable to clear AbortController.abort() after called
Good afternoon folks,
Here's an issue that's currently driving me up the wall and I cannot seem to see the wood for the trees.

I have a React Native app with a built in file uploader, part of this uploader is the use of the abortcontroller which allows the code to send a signal to the fetch request to stop the call in-flight
This works perfectly as one would expect the problem is if the user then selects another file or tries to upload the file the cancelled previously my promise returns instantly with the abort error still in place preventing any further uploads and for love nor money can I seem to find a way to stop this from occurring.

Here is the reduced version of my screen (urls removed, some data points removed, etc) to protect the privacy of my system

```<code>import React from 'react';
import {StyleSheet,View,ScrollView,Alert,} from 'react-native';
import AppSettings from '../../constants/AppSettings'
import Colours from '../../constants/Colours';
import CustomHeader from '../../components/CustomHeader';
import CustomButton from '../../components/CustomButton';
import TextContent from '../../components/TextContent';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import Constants from 'expo-constants';
import * as DocumentPicker from 'expo-document-picker';
import * as Permissions from 'expo-permissions';
import CustomInput from '../../components/CustomInput';
import Progressbar from '../../components/ProgressBar';
import * as Network from 'expo-network';

export default class UploadScreen extends React.Component {

  state = {
    file: null,
    filetype: null,
    fileExtention:null,
    uploading: false,
    pickResult: null,
    mainDataLoaded: false,
    docDesc:null,
    enteredPassword:'',
    currentUploadPercent:0,
    uploadTime: 0,
    startPick: false,
  };
render() {

    return (
      <View style={styles.screenContainer}>
      <LinearGradient start={[0, 1]} end={[0,0.9]} colors={['rgba(163, 163, 163,1)', 'rgba(163, 163, 163,0)']} style={{flex:1}} >
        <ScrollView style={styles.scrollContainer} contentContainerStyle={styles.defaultContainer}>
          <View style={{flex:1, alignItems: 'center', justifyContent: 'center', width:'100%' }}>
            <TextContent>Upload file containing: {this.state.docDesc}</TextContent>
            {this._maybeRenderFile()}
            {this._maybeRenderControls()}
            {this._maybeRenderUploadingIndicator()}
          </View>
        </ScrollView>
      </LinearGradient>
      </View>
    );
  }

  _maybeRenderUploadingIndicator = () => {

      if (this.state.uploading) {
      return (
        <View style={{width:'80%',alignItems:'center'}}>
          <Progressbar progress={this.state.currentUploadPercent}/>
          <CustomButton style={{width:'100%'}} onPress={()=>{AbortUpload(this)}} title='Cancel Upload'></CustomButton>
        </View>

      );
    }
  };
  _maybeRenderControls = () => {
    if (!this.state.uploading) {
      return (
        <View style={{width:'100%',alignItems:'center'}}>
          <CustomButton style={{width:'80%'}} onPress={this._pickImage} title='Select file to upload'><MaterialCommunityIcons style={{color:Colours.PrimaryButtonText}} name="folder-open" size={30}/></CustomButton>
        </View>
      );
    }
  };
  _maybeRenderFile = () => {
    if (this.state.file) {
      switch (this.state.filetype) {
        case 'application/pdf':
          const passwordHandler = enteredText => {
            this.setState({enteredPassword: enteredText});
          };
          return (
            <View style={{alignItems:'center'}}>
              <MaterialCommunityIcons style={{color:Colours.PrimaryText}} name="file-pdf" size={100}/>
              <TextContent style={{textAlign:'center'}}>File to upload: {this.state.file}</TextContent>
              <TextContent>If this file requires a password to access please type it below or leave blank if not required.</TextContent>
              {!this.state.uploading && (
                <View>
                  <CustomInput placeholder='PDF Password (if applicable)' autoCapitalize='characters' autoCompleteType='off' autoCorrect={false} textContentType='none' onChangeText={passwordHandler} value={this.state.enteredPassword}/>
                  <CustomButton style={{width:'100%'}} onPress={()=>{this._handleImagePicked(this.state.pickResult)}} title='Upload this file'><MaterialCommunityIcons style={{color:Colours.PrimaryButtonText}} name="file-upload-outline" size={30}/></CustomButton>
                  <TextContent style={{textAlign:'center'}}>Or</TextContent>
                </View>
              )}

            </View>
          );
          break;
        case 'image/jpg':
        case 'image/png':
        case 'image/gif':
          return (
            <View style={{alignItems:'center'}}>
              <MaterialCommunityIcons style={{color:Colours.PrimaryText}} name="file-image" size={100}/>
              <TextContent style={{textAlign:'center'}}>File to upload: {this.state.file}</TextContent>
              {!this.state.uploading && (
                <View>
                  <CustomButton style={{minWidth:'80%'}} onPress={()=>{this._handleImagePicked(this.state.pickResult)}} title='Upload this file'><MaterialCommunityIcons style={{color:Colours.PrimaryButtonText}} name="file-upload-outline" size={30}/></CustomButton>
                  <TextContent style={{textAlign:'center'}}>Or</TextContent>
                </View>
              )}
            </View>
          );
          break;
        default:
          break;
      }

    }
  };

  _askPermission = async (type, failureMessage) => {
    const { status, permissions } = await Permissions.askAsync(type);

    if (status === 'denied') {
      alert(failureMessage);
    }
  };

  _pickImage = async () => {
    await this._askPermission(
      Permissions.CAMERA_ROLL,
      'We need the file permission to access files from your phone...'
    );
    if(!this.state.startPick){
      this.setState({startPick: true})
      let pickerResult = await DocumentPicker.getDocumentAsync({});

      if(pickerResult.type == 'success'){
        this.setState({startPick: false})
        //Get file extention
        var splitAt = pickerResult.name.lastIndexOf(".")
        var fileExt = pickerResult.name.slice(splitAt,pickerResult.name.length).toLowerCase()
        switch (fileExt) {
          case '.pdf':
            this.setState({file: pickerResult.name, filetype: 'application/pdf', pickResult: pickerResult, fileExtention: fileExt})
            break;
          case '.jpg':
            this.setState({file: pickerResult.name, filetype: 'image/jpg', pickResult: pickerResult, fileExtention: fileExt})
            break;
          case '.jpeg':
            this.setState({file: pickerResult.name, filetype: 'image/jpg', pickResult: pickerResult, fileExtention: fileExt})
            break;
          case '.png':
            this.setState({file: pickerResult.name, filetype: 'image/png', pickResult: pickerResult, fileExtention: fileExt})
            break;
          case '.gif':
            this.setState({file: pickerResult.name, filetype: 'image/gif', pickResult: pickerResult, fileExtention: fileExt})
            break;
          default:
            this.setState({file: null, filetype: null, pickResult: null})
            Alert.alert('Unsupported filetype','For security reasons you may only select images or PDF files to upload.')
            break;
        }
      }else{
        //No file selected
        this.setState({file: null, filetype: null, pickResult: null})
        this.setState({startPick: false})
      }
      if(__DEV__){console.log('Result:', pickerResult)}
    }else{
      if(__DEV__){console.log('Pick already started')}
    }

  };
_StatusCheck = async() =>{
  return fetch('Url for server side upload status response')
  .then((response) => response.json())
  .then((responseJson) => {
    return responseJson
  })
  .catch((error) =>{
    console.error(error);
  });
}

  _handleImagePicked = async pickerResult => {
    try {

      if (!pickerResult.cancelled) {
        var thisTime = Date.now()
        this.setState({uploadTime: thisTime})
        var myPromise = new Promise(function(){})
        myPromise = MakeQuerablePromise(new uploadFileAsync(
          pickerResult.uri,
          this.state.docType + '-' + Date.now() + this.state.fileExtention,
          this.state.filetype,
          this.state.docType,
          this.state.docDesc,
          this.state.enteredPassword,
          this.state.quoteID,
          this.state.uploading,
          thisTime,
          controller.signal
        ));
        this.setState({ uploading: true });
        if(__DEV__){
          console.log("Initial fulfilled:", myPromise.isFulfilled());//false
          console.log("Initial rejected:", myPromise.isRejected());//false
          console.log("Initial pending:", myPromise.isPending());//true
        }
        for (let index = 0; index < 1;) {

          var currentStatus = await this._StatusCheck()
          var curTime = new Date()
          if(__DEV__){
            console.log('Time:',curTime.getHours(),':',curTime.getMinutes(),':',curTime.getSeconds())
            console.log('Status:',currentStatus)
            console.log("Promise status- fulfilled:", myPromise.isFulfilled(), "rejected:", myPromise.isRejected(),"pending:", myPromise.isPending());//false
            console.log('Promise Content:',myPromise)
          }
          if(!myPromise.isRejected()){
            if(currentStatus.percent != undefined){
              if(currentStatus.percent < 100){
                this.setState({currentUploadPercent:currentStatus.percent})
                if(__DEV__){
                console.log('Upload progess ' + currentStatus.percent)
                console.log("Promise status: fulfilled:", myPromise.isFulfilled(), "rejected:", myPromise.isRejected(),"pending:", myPromise.isPending());//false
                }
              }else{
                this.setState({currentUploadPercent:currentStatus.percent})
                if(__DEV__){
                console.log('Upload progess 100%')
                console.log("Promise status: fulfilled:", myPromise.isFulfilled(), "rejected:", myPromise.isRejected(),"pending:", myPromise.isPending());//false
                }
              }
            }
          }

          if(myPromise.isFulfilled() == true){
            if(__DEV__){
            console.log("Entered Fulfilled State - Promise status: fulfilled:", myPromise.isFulfilled(), "rejected:", myPromise.isRejected(),"pending:", myPromise.isPending());//false
            }
            index++
          }
          if(myPromise.isRejected() == true){
            if(__DEV__){
            console.log("Entered Rejected State - Promise status: fulfilled:", myPromise.isFulfilled(), "rejected:", myPromise.isRejected(),"pending:", myPromise.isPending());//false
            }
            index++
          }

        }
        if(myPromise.isRejected() == false){
          myPromise.then(response => response.json()).then((responseJson)=>{
            if(__DEV__){
            console.log('Promise Json:',responseJson)
            console.log("Final fulfilled:", myPromise.isFulfilled());//true
            console.log("Final rejected:", myPromise.isRejected());//false
            console.log("Final pending:", myPromise.isPending());//false
          }
            if(responseJson.datapage.result.gitUploadStatus.successful == true){
              //Successful upload
              this.props.navigation.navigate('CaptureThanks')
            }else{
              //Upload had a issue
              Alert.alert('Upload error','There was an issue with the upload, this maybe a temporary issue with your connection or with the server please ensure you have a good steady signal and try again, if the problem persists please contact us. Error Code: '+responseJson.datapage.gitUploadStatus.errorMessage)
            }
          })
        }else{
          //Rejected promise handle failure
          if(myPromise.rejectReason() == 'AbortError'){
            myPromise = MakeQuerablePromise(new Promise(function(resolve, reject){
              resolve('AbortError')
            }))
          }else{
            Alert.alert('Upload error','There was an issue with the upload, this maybe a temporary issue with your connection or with the server please ensure you have a good steady signal and try again, if the problem persists please contact us. Error Code: '+responseJson.datapage.gitUploadStatus.errorMessage)
          }
        }
      }
    } catch (e) {
      if(__DEV__){
        console.log('Error Name:',e.name)
        console.log('Catch Error:',{ e });
      }
        return;
    } finally {
      if(__DEV__){
        console.log('Reached Final')
      }
      myPromise = MakeQuerablePromise(new Promise(function(resolve, reject){
        resolve('Finished')
      }))
      console.log(myPromise)
      this.setState({ uploading: false, currentUploadPercent:0 });
    }
  };
}
function MakeQuerablePromise(promise) {
  // Don't modify any promise that has been already modified.
  if (promise.isResolved){
    return promise
  };
  // Set initial state
  var isPending = true;
  var isRejected = false;
  var isFulfilled = false;
  var rejectReason = '';

  // Observe the promise, saving the fulfillment in a closure scope.
  var result = promise.then(
      function(v) {
          isFulfilled = true;
          isPending = false;
          rejectReason = '';
          return v;
      },
      function(e) {
          isRejected = true;
          isPending = false;
          rejectReason = e.name;
          return e;
      }
  );
  result.isFulfilled = function() { return isFulfilled; };
  result.isPending = function() { return isPending; };
  result.isRejected = function() { return isRejected; };
  result.rejectReason = function() {return rejectReason; };
  return result;
}
const controller = new AbortController;
async function uploadFileAsync(uri,name,type,docType,docDesc,password,quoteid,isUploading,uploadTime,abortSignal) {
  if(!isUploading){

    if(__DEV__){console.log('Making upload request for ',docType,' Document description:', docDesc)}
    let apiUrl = 'Url to push the upload to';

    let formData = new FormData();
    //(method) FormData.append(name: string, value: string | Blob, fileName?: string): void
    formData.append('filename', {
      uri,
      name: name,
      type: type,
      documentType:docType,
      description:docDesc,
      password:password,
      quoteid:quoteid,
    });
    let options = {
      method: 'POST',
      body: formData,
      headers: {
        Accept: 'application/json',
        'Content-Type': 'multipart/form-data',
      },
      signal: abortSignal,

    };
    if(__DEV__){console.log('Options:', options)}
    return fetch(apiUrl, options);
  }else{
    return null
  }
}
async function AbortUpload(stateObject){
  controller.abort()
  stateObject.setState({isUploading: false})
}

UploadScreen.navigationOptions = {
  header: () => <CustomHeader goback={true} title='Document Upload'/>,
  title: AppSettings.AppName + ' ',
  headerTitleStyle:{
    fontFamily: AppSettings.HeaderFont,
  },
  headerStyle: {
      backgroundColor: Colours.HeaderBackground
    },
    headerTintColor: Colours.HeaderText
};
const styles = StyleSheet.create({
  screenContainer:{
      flex:1,
      backgroundColor: Colours.PrimaryBackgroud,
  },
  scrollContainer:{
      flex: 1,
      height:'100%'
  },
  defaultContainer: {
    alignItems: 'center',
  },
});
</code>```

Forgive the nature of my code as I'm still pretty new to react native and only been doing it for a few months now so still getting my head around a lot of the features and systems and only just updated to the latest version of expo (36) yesterday so I could enable the fetch abort.

But it anyone has any clues as to why it seems that after the signal is called once to abort every future request then seems to be getting that same signal regardless that the user has not clicked it again and I am not storing it in state so I can't seem to understand why its persisting to the degree that I even went to the extreme of rebuilding the promises at start and end to ensure they were cleaned every time the upload is fired.

答:
You shared way too much code, but I'll have a try at this.

First of all, I'm surprised it even worked in the first place. You're creating your abort controller like so:

```<code>const controller = new AbortController;
</code>```

While it should be:

```<code>const controller = new AbortController();
</code>```

Now, when it comes to the logic, I believe it's displaying an error because you're using that same controller, which was already canceled.

The trick would be to turn it into a state and update it with a new AbortController as soon as it gets aborted (probably in your AbortUpload method, right after calling controller.abort()).

Body:
Good afternoon folks,
Here's an issue that's currently driving me up the wall and I cannot seem to see the wood for the trees.

I have a React Native app with a built in file uploader, part of this uploader is the use of the abortcontroller which allows the code to send a signal to the fetch request to stop the call in-flight
This works perfectly as one would expect the problem is if the user then selects another file or tries to upload the file the cancelled previously my promise returns instantly with the abort error still in place preventing any further uploads and for love nor money can I seem to find a way to stop this from occurring.

Here is the reduced version of my screen (urls removed, some data points removed, etc) to protect the privacy of my system

import React from 'react';
import {StyleSheet,View,ScrollView,Alert,} from 'react-native';
import AppSettings from '../../constants/AppSettings'
import Colours from '../../constants/Colours';
import CustomHeader from '../../components/CustomHeader';
import CustomButton from '../../components/CustomButton';
import TextContent from '../../components/TextContent';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import Constants from 'expo-constants';
import * as DocumentPicker from 'expo-document-picker';
import * as Permissions from 'expo-permissions';
import CustomInput from '../../components/CustomInput';
import Progressbar from '../../components/ProgressBar';
import * as Network from 'expo-network';

export default class UploadScreen extends React.Component {

  state = {
    file: null,
    filetype: null,
    fileExtention:null,
    uploading: false,
    pickResult: null,
    mainDataLoaded: false,
    docDesc:null,
    enteredPassword:'',
    currentUploadPercent:0,
    uploadTime: 0,
    startPick: false,
  };
render() {

    return (
      <View style={styles.screenContainer}>
      <LinearGradient start={[0, 1]} end={[0,0.9]} colors={['rgba(163, 163, 163,1)', 'rgba(163, 163, 163,0)']} style={{flex:1}} >
        <ScrollView style={styles.scrollContainer} contentContainerStyle={styles.defaultContainer}>
          <View style={{flex:1, alignItems: 'center', justifyContent: 'center', width:'100%' }}>
            <TextContent>Upload file containing: {this.state.docDesc}</TextContent>
            {this._maybeRenderFile()}
            {this._maybeRenderControls()}
            {this._maybeRenderUploadingIndicator()}
          </View>
        </ScrollView>
      </LinearGradient>
      </View>
    );
  }

  _maybeRenderUploadingIndicator = () => {

      if (this.state.uploading) {
      return (
        <View style={{width:'80%',alignItems:'center'}}>
          <Progressbar progress={this.state.currentUploadPercent}/>
          <CustomButton style={{width:'100%'}} onPress={()=>{AbortUpload(this)}} title='Cancel Upload'></CustomButton>
        </View>

      );
    }
  };
  _maybeRenderControls = () => {
    if (!this.state.uploading) {
      return (
        <View style={{width:'100%',alignItems:'center'}}>
          <CustomButton style={{width:'80%'}} onPress={this._pickImage} title='Select file to upload'><MaterialCommunityIcons style={{color:Colours.PrimaryButtonText}} name="folder-open" size={30}/></CustomButton>
        </View>
      );
    }
  };
  _maybeRenderFile = () => {
    if (this.state.file) {
      switch (this.state.filetype) {
        case 'application/pdf':
          const passwordHandler = enteredText => {
            this.setState({enteredPassword: enteredText});
          };
          return (
            <View style={{alignItems:'center'}}>
              <MaterialCommunityIcons style={{color:Colours.PrimaryText}} name="file-pdf" size={100}/>
              <TextContent style={{textAlign:'center'}}>File to upload: {this.state.file}</TextContent>
              <TextContent>If this file requires a password to access please type it below or leave blank if not required.</TextContent>
              {!this.state.uploading && (
                <View>
                  <CustomInput placeholder='PDF Password (if applicable)' autoCapitalize='characters' autoCompleteType='off' autoCorrect={false} textContentType='none' onChangeText={passwordHandler} value={this.state.enteredPassword}/>
                  <CustomButton style={{width:'100%'}} onPress={()=>{this._handleImagePicked(this.state.pickResult)}} title='Upload this file'><MaterialCommunityIcons style={{color:Colours.PrimaryButtonText}} name="file-upload-outline" size={30}/></CustomButton>
                  <TextContent style={{textAlign:'center'}}>Or</TextContent>
                </View>
              )}

            </View>
          );
          break;
        case 'image/jpg':
        case 'image/png':
        case 'image/gif':
          return (
            <View style={{alignItems:'center'}}>
              <MaterialCommunityIcons style={{color:Colours.PrimaryText}} name="file-image" size={100}/>
              <TextContent style={{textAlign:'center'}}>File to upload: {this.state.file}</TextContent>
              {!this.state.uploading && (
                <View>
                  <CustomButton style={{minWidth:'80%'}} onPress={()=>{this._handleImagePicked(this.state.pickResult)}} title='Upload this file'><MaterialCommunityIcons style={{color:Colours.PrimaryButtonText}} name="file-upload-outline" size={30}/></CustomButton>
                  <TextContent style={{textAlign:'center'}}>Or</TextContent>
                </View>
              )}
            </View>
          );
          break;
        default:
          break;
      }

    }
  };

  _askPermission = async (type, failureMessage) => {
    const { status, permissions } = await Permissions.askAsync(type);

    if (status === 'denied') {
      alert(failureMessage);
    }
  };

  _pickImage = async () => {
    await this._askPermission(
      Permissions.CAMERA_ROLL,
      'We need the file permission to access files from your phone...'
    );
    if(!this.state.startPick){
      this.setState({startPick: true})
      let pickerResult = await DocumentPicker.getDocumentAsync({});

      if(pickerResult.type == 'success'){
        this.setState({startPick: false})
        //Get file extention
        var splitAt = pickerResult.name.lastIndexOf(".")
        var fileExt = pickerResult.name.slice(splitAt,pickerResult.name.length).toLowerCase()
        switch (fileExt) {
          case '.pdf':
            this.setState({file: pickerResult.name, filetype: 'application/pdf', pickResult: pickerResult, fileExtention: fileExt})
            break;
          case '.jpg':
            this.setState({file: pickerResult.name, filetype: 'image/jpg', pickResult: pickerResult, fileExtention: fileExt})
            break;
          case '.jpeg':
            this.setState({file: pickerResult.name, filetype: 'image/jpg', pickResult: pickerResult, fileExtention: fileExt})
            break;
          case '.png':
            this.setState({file: pickerResult.name, filetype: 'image/png', pickResult: pickerResult, fileExtention: fileExt})
            break;
          case '.gif':
            this.setState({file: pickerResult.name, filetype: 'image/gif', pickResult: pickerResult, fileExtention: fileExt})
            break;
          default:
            this.setState({file: null, filetype: null, pickResult: null})
            Alert.alert('Unsupported filetype','For security reasons you may only select images or PDF files to upload.')
            break;
        }
      }else{
        //No file selected
        this.setState({file: null, filetype: null, pickResult: null})
        this.setState({startPick: false})
      }
      if(__DEV__){console.log('Result:', pickerResult)}
    }else{
      if(__DEV__){console.log('Pick already started')}
    }

  };
_StatusCheck = async() =>{
  return fetch('Url for server side upload status response')
  .then((response) => response.json())
  .then((responseJson) => {
    return responseJson
  })
  .catch((error) =>{
    console.error(error);
  });
}

  _handleImagePicked = async pickerResult => {
    try {

      if (!pickerResult.cancelled) {
        var thisTime = Date.now()
        this.setState({uploadTime: thisTime})
        var myPromise = new Promise(function(){})
        myPromise = MakeQuerablePromise(new uploadFileAsync(
          pickerResult.uri,
          this.state.docType + '-' + Date.now() + this.state.fileExtention,
          this.state.filetype,
          this.state.docType,
          this.state.docDesc,
          this.state.enteredPassword,
          this.state.quoteID,
          this.state.uploading,
          thisTime,
          controller.signal
        ));
        this.setState({ uploading: true });
        if(__DEV__){
          console.log("Initial fulfilled:", myPromise.isFulfilled());//false
          console.log("Initial rejected:", myPromise.isRejected());//false
          console.log("Initial pending:", myPromise.isPending());//true
        }
        for (let index = 0; index < 1;) {

          var currentStatus = await this._StatusCheck()
          var curTime = new Date()
          if(__DEV__){
            console.log('Time:',curTime.getHours(),':',curTime.getMinutes(),':',curTime.getSeconds())
            console.log('Status:',currentStatus)
            console.log("Promise status- fulfilled:", myPromise.isFulfilled(), "rejected:", myPromise.isRejected(),"pending:", myPromise.isPending());//false
            console.log('Promise Content:',myPromise)
          }
          if(!myPromise.isRejected()){
            if(currentStatus.percent != undefined){
              if(currentStatus.percent < 100){
                this.setState({currentUploadPercent:currentStatus.percent})
                if(__DEV__){
                console.log('Upload progess ' + currentStatus.percent)
                console.log("Promise status: fulfilled:", myPromise.isFulfilled(), "rejected:", myPromise.isRejected(),"pending:", myPromise.isPending());//false
                }
              }else{
                this.setState({currentUploadPercent:currentStatus.percent})
                if(__DEV__){
                console.log('Upload progess 100%')
                console.log("Promise status: fulfilled:", myPromise.isFulfilled(), "rejected:", myPromise.isRejected(),"pending:", myPromise.isPending());//false
                }
              }
            }
          }

          if(myPromise.isFulfilled() == true){
            if(__DEV__){
            console.log("Entered Fulfilled State - Promise status: fulfilled:", myPromise.isFulfilled(), "rejected:", myPromise.isRejected(),"pending:", myPromise.isPending());//false
            }
            index++
          }
          if(myPromise.isRejected() == true){
            if(__DEV__){
            console.log("Entered Rejected State - Promise status: fulfilled:", myPromise.isFulfilled(), "rejected:", myPromise.isRejected(),"pending:", myPromise.isPending());//false
            }
            index++
          }

        }
        if(myPromise.isRejected() == false){
          myPromise.then(response => response.json()).then((responseJson)=>{
            if(__DEV__){
            console.log('Promise Json:',responseJson)
            console.log("Final fulfilled:", myPromise.isFulfilled());//true
            console.log("Final rejected:", myPromise.isRejected());//false
            console.log("Final pending:", myPromise.isPending());//false
          }
            if(responseJson.datapage.result.gitUploadStatus.successful == true){
              //Successful upload
              this.props.navigation.navigate('CaptureThanks')
            }else{
              //Upload had a issue
              Alert.alert('Upload error','There was an issue with the upload, this maybe a temporary issue with your connection or with the server please ensure you have a good steady signal and try again, if the problem persists please contact us. Error Code: '+responseJson.datapage.gitUploadStatus.errorMessage)
            }
          })
        }else{
          //Rejected promise handle failure
          if(myPromise.rejectReason() == 'AbortError'){
            myPromise = MakeQuerablePromise(new Promise(function(resolve, reject){
              resolve('AbortError')
            }))
          }else{
            Alert.alert('Upload error','There was an issue with the upload, this maybe a temporary issue with your connection or with the server please ensure you have a good steady signal and try again, if the problem persists please contact us. Error Code: '+responseJson.datapage.gitUploadStatus.errorMessage)
          }
        }
      }
    } catch (e) {
      if(__DEV__){
        console.log('Error Name:',e.name)
        console.log('Catch Error:',{ e });
      }
        return;
    } finally {
      if(__DEV__){
        console.log('Reached Final')
      }
      myPromise = MakeQuerablePromise(new Promise(function(resolve, reject){
        resolve('Finished')
      }))
      console.log(myPromise)
      this.setState({ uploading: false, currentUploadPercent:0 });
    }
  };
}
function MakeQuerablePromise(promise) {
  // Don't modify any promise that has been already modified.
  if (promise.isResolved){
    return promise
  };
  // Set initial state
  var isPending = true;
  var isRejected = false;
  var isFulfilled = false;
  var rejectReason = '';

  // Observe the promise, saving the fulfillment in a closure scope.
  var result = promise.then(
      function(v) {
          isFulfilled = true;
          isPending = false;
          rejectReason = '';
          return v;
      },
      function(e) {
          isRejected = true;
          isPending = false;
          rejectReason = e.name;
          return e;
      }
  );
  result.isFulfilled = function() { return isFulfilled; };
  result.isPending = function() { return isPending; };
  result.isRejected = function() { return isRejected; };
  result.rejectReason = function() {return rejectReason; };
  return result;
}
const controller = new AbortController;
async function uploadFileAsync(uri,name,type,docType,docDesc,password,quoteid,isUploading,uploadTime,abortSignal) {
  if(!isUploading){

    if(__DEV__){console.log('Making upload request for ',docType,' Document description:', docDesc)}
    let apiUrl = 'Url to push the upload to';

    let formData = new FormData();
    //(method) FormData.append(name: string, value: string | Blob, fileName?: string): void
    formData.append('filename', {
      uri,
      name: name,
      type: type,
      documentType:docType,
      description:docDesc,
      password:password,
      quoteid:quoteid,
    });
    let options = {
      method: 'POST',
      body: formData,
      headers: {
        Accept: 'application/json',
        'Content-Type': 'multipart/form-data',
      },
      signal: abortSignal,

    };
    if(__DEV__){console.log('Options:', options)}
    return fetch(apiUrl, options);
  }else{
    return null
  }
}
async function AbortUpload(stateObject){
  controller.abort()
  stateObject.setState({isUploading: false})
}

UploadScreen.navigationOptions = {
  header: () => <CustomHeader goback={true} title='Document Upload'/>,
  title: AppSettings.AppName + ' ',
  headerTitleStyle:{
    fontFamily: AppSettings.HeaderFont,
  },
  headerStyle: {
      backgroundColor: Colours.HeaderBackground
    },
    headerTintColor: Colours.HeaderText
};
const styles = StyleSheet.create({
  screenContainer:{
      flex:1,
      backgroundColor: Colours.PrimaryBackgroud,
  },
  scrollContainer:{
      flex: 1,
      height:'100%'
  },
  defaultContainer: {
    alignItems: 'center',
  },
});

Forgive the nature of my code as I'm still pretty new to react native and only been doing it for a few months now so still getting my head around a lot of the features and systems and only just updated to the latest version of expo (36) yesterday so I could enable the fetch abort.

But it anyone has any clues as to why it seems that after the signal is called once to abort every future request then seems to be getting that same signal regardless that the user has not clicked it again and I am not storing it in state so I can't seem to understand why its persisting to the degree that I even went to the extreme of rebuilding the promises at start and end to ensure they were cleaned every time the upload is fired.

Body:
You shared way too much code, but I'll have a try at this.

First of all, I'm surprised it even worked in the first place. You're creating your abort controller like so:

const controller = new AbortController;

While it should be:

const controller = new AbortController();

Now, when it comes to the logic, I believe it's displaying an error because you're using that same controller, which was already canceled.

The trick would be to turn it into a state and update it with a new AbortController as soon as it gets aborted (probably in your AbortUpload method, right after calling controller.abort()).


问:
TextView on recyclerview item is not showing on the right place
I am working on a recyclerview view that looks as follows in Android Studio:

As you may see, there are two textViews, one with "Sample" text as one with "TextView" text.

I need to put the second textView just below the first textView, like it is in the image.

The eight circled ImageViews may appear or not, depending on the item values.

The issue is that the item on a real device looks different depending on the item values, if there are not ImageViews (the small grey circles) everything looks as I want,like this

but in case of existing circled ImageViews on the item, the second textView appears much lower, below the second circled ImageViews row, like this:

This is my code for the view:

```<code><RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/profile_image"
            android:layout_width="65dp"
            android:layout_height="65dp"

            android:layout_marginLeft="5dp"
            android:layout_marginTop="5dp"
            android:background="@color/colorWhite"
            android:src="@drawable/ic_account_circle_black_24dp"
            card_view:civ_border_color="#FF000000"
            card_view:civ_border_width="2dp" />

        <TextView
            android:id="@+id/txtUsername"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="3dp"
            android:layout_toRightOf="@id/profile_image"
            android:text="Sample"
            android:textColor="@color/grey_700"
            android:textSize="20dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/txtDate"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/txtUsername"
            android:layout_alignStart="@id/txtUsername"
            android:layout_toRightOf="@id/profile_image"
            android:text="TextView"
            android:textSize="10sp" />

        <LinearLayout
            android:id="@+id/layout_deportes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/txtUsername"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="3dp"
            android:layout_toLeftOf="@id/tres"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/sp1"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp2"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp3"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp4"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/layout_deportes2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/layout_deportes"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="3dp"
            android:layout_toLeftOf="@id/tres"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/sp5"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp6"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_below="@+id/layout_deportes"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp7"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp8"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

        </LinearLayout>
</code>```

I guess something must be wrong on it, but I am not able to find out the reason for the issue.

答:
```<code>  <de.hdodenhof.circleimageview.CircleImageView
    android:id="@+id/profile_image"
    app:civ_border_width="@dimen/dp_2"
    android:layout_width="65dp"
    android:layout_height="65dp"
    android:layout_marginLeft="5dp"
    android:layout_marginTop="5dp"
    android:background="@color/white"
    android:src="@drawable/ic_close_black" />

<TextView
    android:id="@+id/txtUsername"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:layout_marginTop="3dp"
    android:layout_marginBottom="3dp"
    android:layout_toRightOf="@id/profile_image"
    android:text="Sample"
    android:textSize="20dp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/txtDate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/txtUsername"
    android:layout_toRightOf="@id/profile_image"
    android:text="TextView"
    android:textSize="10sp" />

<LinearLayout
    android:id="@+id/layout_deportes"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@id/txtUsername"
    android:layout_marginTop="3dp"
    android:layout_toLeftOf="@id/tres"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/sp1"
        android:src="@drawable/ic_close_black"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_marginRight="5dp"
        android:layout_weight="1"
       />

    <ImageView
        android:id="@+id/sp2"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_marginRight="5dp"
        android:layout_weight="1"
        android:background="@drawable/ic_close_screen"
        />

    <ImageView
        android:id="@+id/sp3"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_marginRight="5dp"
        android:layout_weight="1"
        android:visibility="visible" />

    <ImageView
        android:id="@+id/sp4"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_marginRight="5dp"
        android:layout_weight="1"
        android:visibility="visible" />

</LinearLayout>

<LinearLayout
    android:id="@+id/layout_deportes2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/layout_deportes"
    android:layout_marginTop="3dp"
    android:layout_toRightOf="@id/txtUsername"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/sp5"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_marginRight="5dp"
        android:layout_weight="1"

        android:visibility="visible" />

    <ImageView
        android:id="@+id/sp6"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_below="@+id/layout_deportes"
        android:layout_marginRight="5dp"
        android:layout_weight="1"
        android:visibility="visible" />

    <ImageView
        android:id="@+id/sp7"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_marginRight="5dp"
        android:layout_weight="1"
        android:visibility="visible" />

    <ImageView
        android:id="@+id/sp8"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_marginRight="5dp"
        android:layout_weight="1"
        android:visibility="visible" />

</LinearLayout>
</code>```

Body:
I am working on a recyclerview view that looks as follows in Android Studio:

As you may see, there are two textViews, one with "Sample" text as one with "TextView" text.

I need to put the second textView just below the first textView, like it is in the image.

The eight circled ImageViews may appear or not, depending on the item values.

The issue is that the item on a real device looks different depending on the item values, if there are not ImageViews (the small grey circles) everything looks as I want,like this

but in case of existing circled ImageViews on the item, the second textView appears much lower, below the second circled ImageViews row, like this:

This is my code for the view:

<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/profile_image"
            android:layout_width="65dp"
            android:layout_height="65dp"

            android:layout_marginLeft="5dp"
            android:layout_marginTop="5dp"
            android:background="@color/colorWhite"
            android:src="@drawable/ic_account_circle_black_24dp"
            card_view:civ_border_color="#FF000000"
            card_view:civ_border_width="2dp" />

        <TextView
            android:id="@+id/txtUsername"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="3dp"
            android:layout_toRightOf="@id/profile_image"
            android:text="Sample"
            android:textColor="@color/grey_700"
            android:textSize="20dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/txtDate"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/txtUsername"
            android:layout_alignStart="@id/txtUsername"
            android:layout_toRightOf="@id/profile_image"
            android:text="TextView"
            android:textSize="10sp" />

        <LinearLayout
            android:id="@+id/layout_deportes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/txtUsername"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="3dp"
            android:layout_toLeftOf="@id/tres"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/sp1"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp2"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp3"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp4"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/layout_deportes2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/layout_deportes"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="3dp"
            android:layout_toLeftOf="@id/tres"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/sp5"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp6"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_below="@+id/layout_deportes"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp7"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp8"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

        </LinearLayout>

I guess something must be wrong on it, but I am not able to find out the reason for the issue.


问:
Php if(this) change css positon
I dont really know what to search to fix my soulution, I got this php code:

```<code>if($_SESSION['loggedIn'] == false){
  include("mobilForm.php");
}
</code>```

When my form is included i need to position down an absoulte element, ex top=55% . But when I log in and the form disapears the element is still positioned at top=55% (obviously). Can in php change the position to top=35%?

Ex?

```<code>if($_SESSION['loggedIn']==false){
   include("mobilForm.php");
   $("div").css("top", "35%");
}
</code>```

login:

```<code><?php
include('connect.php');
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '".$username."'";
$result = $con->query($query);
while($row = $result->fetch_object())
{
    if (strcasecmp($username, $row->username) === 0)
    {
            $checkPassword = password_verify($password,$row->password);
            if($checkPassword ){
                $_SESSION['loggedIn'] = true;
                $_SESSION['user'] = $row->username;
                $_SESSION['admin'] = $row->admin;
                $_SESSION['userpic'] = $row->userpic;
                $_SESSION['displayname'] = $row->displayname;
                $_SESSION['id'] = $row->id;
                $now = date("H:i");
                $id = $_SESSION['id'];
                $sql = $con->prepare('UPDATE users SET online =? WHERE id = ?');
                $sql->bind_param("si",$now,$id);
                $sql->execute();
                $sql->close();
                $con->close();
                header("Location:music.php?success");
                exit();
            }
            else{
                echo "<script>
                   alert('Do you even know your password?');
                   window.location.href='music.php?HAHA';
                      </script>";

            }

    }
}

?>
</code>```

Current state  Css

```<code>body:not(.loggedIn) #searchBarN {
top: 65%;
  }

  body.loggedIn #searchBarN {
    top: 35%;
  }
</code>```

html

```<code><body <?php echo isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == true ? 'id="searchBarN"' : ''; ?>>
</code>```

答:
You can add a class to your element with PHP. In this example the class loggedin is added to the body:

```<code><body <?php echo isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == true ? 'class="loggedin"' : ''; ?>
</code>```

And then you can style your element in CSS:

```<code>body:not(.loggedin) #yourform {
  top: 55%;
}

body.loggedin #yourform {
  top: 35%;
}
</code>```

Title: Php if(this) change css positon

Body:
I dont really know what to search to fix my soulution, I got this php code:

if($_SESSION['loggedIn'] == false){
  include("mobilForm.php");
}

When my form is included i need to position down an absoulte element, ex top=55% . But when I log in and the form disapears the element is still positioned at top=55% (obviously). Can in php change the position to top=35%?

Ex?

if($_SESSION['loggedIn']==false){
   include("mobilForm.php");
   $("div").css("top", "35%");
}

login:

<?php
include('connect.php');
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '".$username."'";
$result = $con->query($query);
while($row = $result->fetch_object())
{
    if (strcasecmp($username, $row->username) === 0)
    {
            $checkPassword = password_verify($password,$row->password);
            if($checkPassword ){
                $_SESSION['loggedIn'] = true;
                $_SESSION['user'] = $row->username;
                $_SESSION['admin'] = $row->admin;
                $_SESSION['userpic'] = $row->userpic;
                $_SESSION['displayname'] = $row->displayname;
                $_SESSION['id'] = $row->id;
                $now = date("H:i");
                $id = $_SESSION['id'];
                $sql = $con->prepare('UPDATE users SET online =? WHERE id = ?');
                $sql->bind_param("si",$now,$id);
                $sql->execute();
                $sql->close();
                $con->close();
                header("Location:music.php?success");
                exit();
            }
            else{
                echo "";

            }

    }
}

?>

Current state  Css

body:not(.loggedIn) #searchBarN {
top: 65%;
  }

  body.loggedIn #searchBarN {
    top: 35%;
  }

html

<body <?php echo isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == true ? 'id="searchBarN"' : ''; ?>>

Body:
You can add a class to your element with PHP. In this example the class loggedin is added to the body:

<body <?php echo isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == true ? 'class="loggedin"' : ''; ?>

And then you can style your element in CSS:

body:not(.loggedin) #yourform {
  top: 55%;
}

body.loggedin #yourform {
  top: 35%;
}


问:
Cygwin Perl installation missing CPAN
I'm using the Buildroot makefiles on Cygwin to make some basic Linux systems, which requires several Perl modules.

CPAN does not seem to have installed with Perl, so I can't install any modules them without a lot of work (I know basically nothing about Perl)

How can I get CPAN working? Thanks

Thought I'd return to this in case anyone comes back in the future:
It seems to be unsupported and impossible to use Buildroot on Cygwin, so don't bother unless you really think you can make it work. If you do make it work please let me know :)

答:
From the comments, we came to find:

$ cygcheck -c perl_base
Cygwin Package Information
Package              Version        Status
perl_base            5.30.1-1       OK

$ cygcheck -c perl
Cygwin Package Information
Package              Version        Status
perl                 5.26.3-2       OK
```

At some point, the perl_base package (the essential files) were updated. perl_base doesn't depend on perl (the rest of core perl), so the perl package wasn't updated at that time.

Those two packages need to be upgraded in step. The discrepancies in the versions is causing the problem. Upgrading the perl package to match fixed the problem.

Title: Cygwin Perl installation missing CPAN

Body:
From the comments, we came to find:

$ cygcheck -c perl_base
Cygwin Package Information
Package              Version        Status
perl_base            5.30.1-1       OK

$ cygcheck -c perl
Cygwin Package Information
Package              Version        Status
perl                 5.26.3-2       OK

At some point, the perl_base package (the essential files) were updated. perl_base doesn't depend on perl (the rest of core perl), so the perl package wasn't updated at that time.

Those two packages need to be upgraded in step. The discrepancies in the versions is causing the problem. Upgrading the perl package to match fixed the problem.


问:
Number of numeric values present in NVarchar column in SQL Server 2005
I have a Nvarchar column which contains data related to different data types such as Numerics, Dates and so on.
I wanted to find out number of cells with Numeric data type and number of cells with Date data type.

Thanks

答:
It looks like you just want IsDate() and IsNumeric():

```<code>SELECT Sum(CASE WHEN IsDate(DataColumn) = 1 THEN 1 ELSE 0 END) AS Dates,
    Sum(CASE WHEN IsNumeric(DataColumn) = 1 AND IsDate(DataColumn) = 0 THEN 1 ELSE 0 END) AS Numbers
FROM YourTable
</code>```

This is assuming that you have a single date format, and that that format is supported by SQL Server's dateformat option. To define the correct format, you would use SET DateFormat. See MSDN Documentation on IsDate.

You mention that '20041201' could be a valid date, which is why I added the extra IsDate() check in the numeric count (I assume you wouldn't want to count it as both a date and a number).

Body:
It looks like you just want IsDate() and IsNumeric():

SELECT Sum(CASE WHEN IsDate(DataColumn) = 1 THEN 1 ELSE 0 END) AS Dates,
    Sum(CASE WHEN IsNumeric(DataColumn) = 1 AND IsDate(DataColumn) = 0 THEN 1 ELSE 0 END) AS Numbers
FROM YourTable

This is assuming that you have a single date format, and that that format is supported by SQL Server's dateformat option. To define the correct format, you would use SET DateFormat. See MSDN Documentation on IsDate.

You mention that '20041201' could be a valid date, which is why I added the extra IsDate() check in the numeric count (I assume you wouldn't want to count it as both a date and a number).


问:
Show pandas Dataframe in webpage and dynamically filter using Dash
I am trying to display a data frame with Dash. The data frame that I have is https://www.kaggle.com/timoboz/superbowl-history-1967-2020. My goal is to show the data frame on the webpage with one search button that dynamically searches all the columns and filters the data frame.

So far, I have the following code that displays the dataframe.

```<code>import pandas as pd
import dash
import dash_table
from dash.dependencies import Input, Output
df  = pd.read_csv('./Data/superbowl.csv')
PAGE_SIZE = 10
app = dash.Dash(__name__)

app.layout = dash_table.DataTable(
    id='datatable-paging',
    columns=[
        {"name": i, "id": i} for i in df.columns #sorted(df.columns)
    ],
    page_current=0,
    page_size=PAGE_SIZE,
    page_action='custom',

    sort_action='custom',
    sort_mode='single',
    sort_by=[]
)

@app.callback(
    Output('datatable-paging', 'data'),
    [Input('datatable-paging', "page_current"),
     Input('datatable-paging', "page_size"),
     Input('datatable-paging', 'sort_by')])
def update_table(page_current,page_size,sort_by):
    if len(sort_by):
        dff = df.sort_values(
            sort_by[0]['column_id'],
            ascending=sort_by[0]['direction'] == 'asc',
            inplace=False
        )
    else:
        # No sort is applied
        dff = df

    return dff.iloc[
           page_current * page_size:(page_current + 1) * page_size
           ].to_dict('records')

if __name__ == '__main__':
    app.run_server(debug=True)
</code>```

After reading through the documentation https://dash.plot.ly/datatable/callbacks especially 'Backend Paging with Filtering', I couldn't find a way to have like a single textbox that would search all the columns and filter the data frame for the matched entries.

答:
The best way to do this would be to use an input component for your search query. This can then update the table by doing a pandas filter. This returns all the rows where any cell contains the text.

Example filter callback below:

```<code>@app.callback(
    Output('datatable', 'data'),
    [Input('filter-input', 'value')])
def update_table(filter_string):
    dff = df[df.apply(lambda row: row.str.contains(filter_string, regex=False).any(), axis=1)]
    return dff.to_dict('records')
</code>```

Your input component below (note the use of debounce - this means that the callback will only be actioned when the user presses enter):

With import dash_core_components as dcc

```<code>dcc.Input(value='', id='filter-input', placeholder='Filter', debounce=True)
</code>```

Taking your current code and putting this all together:

```<code>import pandas as pd
import dash
import dash_table
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

df = pd.read_csv('./Data/superbowl.csv')
PAGE_SIZE = 10
app = dash.Dash(__name__)

app.layout = html.Div([
    dcc.Input(value='', id='filter-input', placeholder='Filter', debounce=True),
    dash_table.DataTable(
        id='datatable-paging',
        columns=[
            {"name": i, "id": i} for i in df.columns  # sorted(df.columns)
        ],
        page_current=0,
        page_size=PAGE_SIZE,
        page_action='custom',

        sort_action='custom',
        sort_mode='single',
        sort_by=[]
    )
])

@app.callback(
    Output('datatable-paging', 'data'),
    [Input('datatable-paging', 'page_current'),
     Input('datatable-paging', 'page_size'),
     Input('datatable-paging', 'sort_by'),
     Input('filter-input', 'value')])
def update_table(page_current, page_size, sort_by, filter_string):
    # Filter
    dff = df[df.apply(lambda row: row.str.contains(filter_string, regex=False).any(), axis=1)]
    # Sort if necessary
    if len(sort_by):
        dff = dff.sort_values(
            sort_by[0]['column_id'],
            ascending=sort_by[0]['direction'] == 'asc',
            inplace=False
        )

    return dff.iloc[
           page_current * page_size:(page_current + 1) * page_size
           ].to_dict('records')

if __name__ == '__main__':
    app.run_server(debug=True)

</code>```

Hope this helps,

Ollie

Body:
I am trying to display a data frame with Dash. The data frame that I have is https://www.kaggle.com/timoboz/superbowl-history-1967-2020. My goal is to show the data frame on the webpage with one search button that dynamically searches all the columns and filters the data frame.

So far, I have the following code that displays the dataframe.

import pandas as pd
import dash
import dash_table
from dash.dependencies import Input, Output
df  = pd.read_csv('./Data/superbowl.csv')
PAGE_SIZE = 10
app = dash.Dash(__name__)

app.layout = dash_table.DataTable(
    id='datatable-paging',
    columns=[
        {"name": i, "id": i} for i in df.columns #sorted(df.columns)
    ],
    page_current=0,
    page_size=PAGE_SIZE,
    page_action='custom',

    sort_action='custom',
    sort_mode='single',
    sort_by=[]
)

@app.callback(
    Output('datatable-paging', 'data'),
    [Input('datatable-paging', "page_current"),
     Input('datatable-paging', "page_size"),
     Input('datatable-paging', 'sort_by')])
def update_table(page_current,page_size,sort_by):
    if len(sort_by):
        dff = df.sort_values(
            sort_by[0]['column_id'],
            ascending=sort_by[0]['direction'] == 'asc',
            inplace=False
        )
    else:
        # No sort is applied
        dff = df

    return dff.iloc[
           page_current * page_size:(page_current + 1) * page_size
           ].to_dict('records')

if __name__ == '__main__':
    app.run_server(debug=True)

After reading through the documentation https://dash.plot.ly/datatable/callbacks especially 'Backend Paging with Filtering', I couldn't find a way to have like a single textbox that would search all the columns and filter the data frame for the matched entries.

Body:
The best way to do this would be to use an input component for your search query. This can then update the table by doing a pandas filter. This returns all the rows where any cell contains the text.

Example filter callback below:

@app.callback(
    Output('datatable', 'data'),
    [Input('filter-input', 'value')])
def update_table(filter_string):
    dff = df[df.apply(lambda row: row.str.contains(filter_string, regex=False).any(), axis=1)]
    return dff.to_dict('records')

Your input component below (note the use of debounce - this means that the callback will only be actioned when the user presses enter):

With import dash_core_components as dcc

dcc.Input(value='', id='filter-input', placeholder='Filter', debounce=True)

Taking your current code and putting this all together:

import pandas as pd
import dash
import dash_table
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

df = pd.read_csv('./Data/superbowl.csv')
PAGE_SIZE = 10
app = dash.Dash(__name__)

app.layout = html.Div([
    dcc.Input(value='', id='filter-input', placeholder='Filter', debounce=True),
    dash_table.DataTable(
        id='datatable-paging',
        columns=[
            {"name": i, "id": i} for i in df.columns  # sorted(df.columns)
        ],
        page_current=0,
        page_size=PAGE_SIZE,
        page_action='custom',

        sort_action='custom',
        sort_mode='single',
        sort_by=[]
    )
])

@app.callback(
    Output('datatable-paging', 'data'),
    [Input('datatable-paging', 'page_current'),
     Input('datatable-paging', 'page_size'),
     Input('datatable-paging', 'sort_by'),
     Input('filter-input', 'value')])
def update_table(page_current, page_size, sort_by, filter_string):
    # Filter
    dff = df[df.apply(lambda row: row.str.contains(filter_string, regex=False).any(), axis=1)]
    # Sort if necessary
    if len(sort_by):
        dff = dff.sort_values(
            sort_by[0]['column_id'],
            ascending=sort_by[0]['direction'] == 'asc',
            inplace=False
        )

    return dff.iloc[
           page_current * page_size:(page_current + 1) * page_size
           ].to_dict('records')

if __name__ == '__main__':
    app.run_server(debug=True)

Hope this helps,

Ollie


问:
Enforce method signature using annotations
I have written a custom annotation that I use to find methods that can be invoked via a IoT platform. It's a method level annotation:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DirectMethod {

    String value();

}
```

<p>I look this annotation up in runtime, and to have the call succeed, the expected signature must be:</p>

<pre class="lang-java prettyprint-override"><code>@DeviceMethod("metod")
public ReturnType methodName(final String data) {...}
</code>```

i.e, the return type and the input parameters are crucial.

Is there any way to have an annotation be "smart" when its target type is METHOD? Like integrated IDE warnings and such. Or do I simply have to process each annotation manually at startup and have the startup procedure fail if any method breaks my intended method contract?

答:
Yes, you can write annotation processor to validate your calls, the only downside of this is that annotation processors needs to be passed to javac (gradle and maven support easy syntax to register them) so someone could just not do it and not see any warnings/errors.

But otherwise all you need to do is create special annotation and processor, like that:

```<code>@SupportedAnnotationTypes("com.gotofinal.direct.DirectMethod")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class DirectAnnProcessor extends AbstractProcessor {

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        TypeElement stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String");
        TypeElement expectedReturnType = processingEnv.getElementUtils().getTypeElement("com.gotofinal.direct.ReturnType");

        for (Element element : roundEnv.getElementsAnnotatedWith(DirectMethod.class)) {
            if (! (element instanceof ExecutableElement)) {
                processingEnv.getMessager().printMessage(Kind.ERROR, "Annotation should be on method.");
                continue;
            }
            ExecutableElement executableElement = (ExecutableElement) element;
            if (! executableElement.getReturnType().equals(expectedReturnType)) {
                processingEnv.getMessager().printMessage(Kind.ERROR, "Method should return ReturnType");
            }
            List<? extends VariableElement> parameters = executableElement.getParameters();
            if (parameters.size() != 1 && parameters.get(0).asType().equals(stringType)) {
                processingEnv.getMessager().printMessage(Kind.ERROR, "Method should have single String argument");
            }
        }
        return true; // no further processing of this annotation type
    }
}
</code>```

And register it in META-INF/services/javax.annotation.processing.Processor file:

```<code>com.gotofinal.direct.DirectAnnProcessor
</code>```

And then you can add such lib to maven/gradle as annotation processor and it should report any issues. In gradle such library must be added using annotationProcessor "my:lib:0.1" declaration.

Body:
I have written a custom annotation that I use to find methods that can be invoked via a IoT platform. It's a method level annotation:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DirectMethod {

    String value();

}

I look this annotation up in runtime, and to have the call succeed, the expected signature must be:

@DeviceMethod("metod")
public ReturnType methodName(final String data) {...}

i.e, the return type and the input parameters are crucial.

Is there any way to have an annotation be "smart" when its target type is METHOD? Like integrated IDE warnings and such. Or do I simply have to process each annotation manually at startup and have the startup procedure fail if any method breaks my intended method contract?

Body:
Yes, you can write annotation processor to validate your calls, the only downside of this is that annotation processors needs to be passed to javac (gradle and maven support easy syntax to register them) so someone could just not do it and not see any warnings/errors.

But otherwise all you need to do is create special annotation and processor, like that:

@SupportedAnnotationTypes("com.gotofinal.direct.DirectMethod")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class DirectAnnProcessor extends AbstractProcessor {

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        TypeElement stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String");
        TypeElement expectedReturnType = processingEnv.getElementUtils().getTypeElement("com.gotofinal.direct.ReturnType");

        for (Element element : roundEnv.getElementsAnnotatedWith(DirectMethod.class)) {
            if (! (element instanceof ExecutableElement)) {
                processingEnv.getMessager().printMessage(Kind.ERROR, "Annotation should be on method.");
                continue;
            }
            ExecutableElement executableElement = (ExecutableElement) element;
            if (! executableElement.getReturnType().equals(expectedReturnType)) {
                processingEnv.getMessager().printMessage(Kind.ERROR, "Method should return ReturnType");
            }
            List<? extends VariableElement> parameters = executableElement.getParameters();
            if (parameters.size() != 1 && parameters.get(0).asType().equals(stringType)) {
                processingEnv.getMessager().printMessage(Kind.ERROR, "Method should have single String argument");
            }
        }
        return true; // no further processing of this annotation type
    }
}

And register it in META-INF/services/javax.annotation.processing.Processor file:

com.gotofinal.direct.DirectAnnProcessor

And then you can add such lib to maven/gradle as annotation processor and it should report any issues. In gradle such library must be added using annotationProcessor "my:lib:0.1" declaration.


问:
Is there a way of extract output of bash script in Azure Pipeline
I have plenty of bash scripts with various variables that being piped into various scripts.

I've been wondering if I can extract an output of bash script that is activated by Azure Pipeline to be a pipeline variable for the rest of the Pipeline runtime?

Example:
foo=$(date + %Y%m%d_%H%M%S) output: 20200219_143400, I'd like to get the output for later use on the pipeline.

答:
Depends on how you design your pipeline you can use Azure Pipeline variables:

Inside the same Job:

```<code>- job: Job1
  steps:
  - bash: |
      $WORKDIR/foo.sh
      echo "##vso[task.setvariable variable=foo]$foo"
    name: FooStep
  - bash: |
      $WORKDIR/nextscript.sh $(FooStep.foo)
    name: NextScript

# ...
</code>```

Different jobs:

```<code>- job: Job1
  steps:
  - bash: |
      $WORKDIR/foo.sh
      echo "##vso[task.setvariable variable=foo;isOutput=true]$foo"
    name: FooStep
- job: Job2
  dependsOn: Job1
  steps:
  - bash: |
      $WORKDIR/job2script.sh $[ dependencies.Job1.outputs['FooStep.foo'] ]
    name: Job2ScriptStep

# ...
</code>```

So, you need to "print to pipeline console" with ##vso[task.setvariable] all variables you need to save to output, and after to pass them as scripts arguments values.

Body:
Depends on how you design your pipeline you can use Azure Pipeline variables:

Inside the same Job:

- job: Job1
  steps:
  - bash: |
      $WORKDIR/foo.sh
      echo "##vso[task.setvariable variable=foo]$foo"
    name: FooStep
  - bash: |
      $WORKDIR/nextscript.sh $(FooStep.foo)
    name: NextScript

# ...

Different jobs:

- job: Job1
  steps:
  - bash: |
      $WORKDIR/foo.sh
      echo "##vso[task.setvariable variable=foo;isOutput=true]$foo"
    name: FooStep
- job: Job2
  dependsOn: Job1
  steps:
  - bash: |
      $WORKDIR/job2script.sh $[ dependencies.Job1.outputs['FooStep.foo'] ]
    name: Job2ScriptStep

# ...

So, you need to "print to pipeline console" with ##vso[task.setvariable] all variables you need to save to output, and after to pass them as scripts arguments values.


问:
gcloud app enigne. where to create virtualenv? external directory to my project?
I'm starting to use gcloud and appengine and I don't know which is the best way to manage virtualenvs.

On the one hand, https://cloud.google.com/appengine/docs/standard/python3/quickstart

Create an isolated Python environment in a directory external to your project and activate it

But on the other hand, https://cloud.google.com/python/setup

```<code>cd your-project
python3 -m venv venv
</code>```

So, what should I do? I understand that the logic of creating the virtualenv outside the directory is due to not deploying the virtualenv when deploying the gcloud app, but there is no way to exclude it? If I'm working with vs code, I think that the virtualenv should be in the same folder where is the project.

Thanks for the help, my first question in stackoverflow!

答:
This might help.

gcloud app engine do not need a separate virtual environment.

please refer to the official document carefully.
https://cloud.google.com/appengine/docs/standard/python3/quickstart

Visit this link you sent in your question.
https://cloud.google.com/python/setup

They've mentioned clearly that this is.
To run the Hello World app on your local computer:

Write your dependencies in requirements.txt and keep it in root foler of your project, gcp app engine will internally manage all your dependencies(packages).

consider the hierarchy.

```<code>ProjectFolder
->AppFolder
->manage.py
->requirements.txt
</code>```

let me know if you need anything else.

Body:
I'm starting to use gcloud and appengine and I don't know which is the best way to manage virtualenvs.

On the one hand, https://cloud.google.com/appengine/docs/standard/python3/quickstart

Create an isolated Python environment in a directory external to your project and activate it

But on the other hand, https://cloud.google.com/python/setup

cd your-project
python3 -m venv venv

So, what should I do? I understand that the logic of creating the virtualenv outside the directory is due to not deploying the virtualenv when deploying the gcloud app, but there is no way to exclude it? If I'm working with vs code, I think that the virtualenv should be in the same folder where is the project.

Thanks for the help, my first question in stackoverflow!

Body:
This might help.

gcloud app engine do not need a separate virtual environment.

please refer to the official document carefully.
https://cloud.google.com/appengine/docs/standard/python3/quickstart

Visit this link you sent in your question.
https://cloud.google.com/python/setup

They've mentioned clearly that this is.
To run the Hello World app on your local computer:

Write your dependencies in requirements.txt and keep it in root foler of your project, gcp app engine will internally manage all your dependencies(packages).

consider the hierarchy.

ProjectFolder
->AppFolder
->manage.py
->requirements.txt

let me know if you need anything else.


问:
Icon corrupted with Powershell exe to ico converter
i'm looking for a powershell script to extract the .ico of an executable.

I found some tools that seems to work like this one:

```<code>[System.Reflection.Assembly]::LoadWithPartialName('System.Drawing')  | Out-Null

$folder = "C:\TMP_7423\icons"
md $folder -ea 0 | Out-Null

dir $env:windir *.exe -ea 0 -rec |
  ForEach-Object {
    $baseName = [System.IO.Path]::GetFileNameWithoutExtension($_.FullName)
    Write-Progress "Extracting Icon" $baseName
    [System.Drawing.Icon]::ExtractAssociatedIcon($_.FullName).ToBitmap().Save("$folder\$BaseName.ico")
}
</code>```

But the problem is, that I want to use a powershell to exe converter for another tool that have a function to directly put an icon in the generated .exe. And I wanna use the extracted ico for the generated executable.
The problem is that the ps1 to exe converter do not work with any icon generated by the ico extractor.
But, the thing is that the ps1 to exe converter work when I use .ico that I found on the internet.

So, do you have any executable .ico extractor that do not extract corrupted ico but normal .ico that we could find on the internet ?

Thank you in advance ! :)

答:
Probably the ps1 to exe converter needs a proper .ICO and your code uses ToBitmap().Save(), which will not save the image info in ico format. For that, you need to use the Save() method of the extracted icon itself.

Unfortunately, the parameter for this Save method can only be a stream object, not simply a path.

Try:

```<code>Add-Type -AssemblyName System.Drawing

$folder = "C:\TMP_7423\icons"
if (!(Test-Path -Path $folder -PathType Container)) {
    $null = New-Item -Path $folder -ItemType Directory
}
Get-ChildItem -Path $env:windir -Filter '*.exe' -Recurse |
  ForEach-Object {
    Write-Progress "Extracting Icon $($_.BaseName)"
    $ico = [System.Drawing.Icon]::ExtractAssociatedIcon($_.FullName)
    $target = Join-Path -Path $folder -ChildPath ('{0}.ico' -f $_.BaseName)
    # create a filestream object
    $stream = [System.IO.FileStream]::new($target, [IO.FileMode]::Create, [IO.FileAccess]::Write)
    # save as ICO format to the filestream
    $ico.Save($stream)
    # remove the stream object
    $stream.Dispose()
    $ico.Dispose()
}
</code>```

Body:
i'm looking for a powershell script to extract the .ico of an executable.

I found some tools that seems to work like this one:

[System.Reflection.Assembly]::LoadWithPartialName('System.Drawing')  | Out-Null

$folder = "C:\TMP_7423\icons"
md $folder -ea 0 | Out-Null

dir $env:windir *.exe -ea 0 -rec |
  ForEach-Object {
    $baseName = [System.IO.Path]::GetFileNameWithoutExtension($_.FullName)
    Write-Progress "Extracting Icon" $baseName
    [System.Drawing.Icon]::ExtractAssociatedIcon($_.FullName).ToBitmap().Save("$folder\$BaseName.ico")
}

But the problem is, that I want to use a powershell to exe converter for another tool that have a function to directly put an icon in the generated .exe. And I wanna use the extracted ico for the generated executable.
The problem is that the ps1 to exe converter do not work with any icon generated by the ico extractor.
But, the thing is that the ps1 to exe converter work when I use .ico that I found on the internet.

So, do you have any executable .ico extractor that do not extract corrupted ico but normal .ico that we could find on the internet ?

Thank you in advance ! :)

Body:
Probably the ps1 to exe converter needs a proper .ICO and your code uses ToBitmap().Save(), which will not save the image info in ico format. For that, you need to use the Save() method of the extracted icon itself.

Unfortunately, the parameter for this Save method can only be a stream object, not simply a path.

Try:

Add-Type -AssemblyName System.Drawing

$folder = "C:\TMP_7423\icons"
if (!(Test-Path -Path $folder -PathType Container)) {
    $null = New-Item -Path $folder -ItemType Directory
}
Get-ChildItem -Path $env:windir -Filter '*.exe' -Recurse |
  ForEach-Object {
    Write-Progress "Extracting Icon $($_.BaseName)"
    $ico = [System.Drawing.Icon]::ExtractAssociatedIcon($_.FullName)
    $target = Join-Path -Path $folder -ChildPath ('{0}.ico' -f $_.BaseName)
    # create a filestream object
    $stream = [System.IO.FileStream]::new($target, [IO.FileMode]::Create, [IO.FileAccess]::Write)
    # save as ICO format to the filestream
    $ico.Save($stream)
    # remove the stream object
    $stream.Dispose()
    $ico.Dispose()
}


问:
Fetch data from another dataframe
I had asked a question earlier but it was closed as the initial question was considered as duplicate.

But I am trying to something different from that thread as well as duplicate thread.

String Replacement From Another DataFrame.

So please don't close this thread.
Thanks.

I need to replace my column depending upon data from another dataframe.
Have to search for respective "name" from the other dataframe and include the "change_name" in the df1

DataFrame 1:

```<code>ID  name
1   cat
2   jack
3   snake
4   monkey
</code>```

DataFrame 2:

```<code>name    change_name
cat     meow
jack    oooo
snake   ssss
monkey
note    money
pencil pen
</code>```

Expected Output:

```<code>ID  name
1   cat      meow
2   jack     oooo
3   snake    ssss
4   monkey   nan
5   note    money
6   pencil pen
</code>```

I had to do like below:

```<code>def map_name(name):
    elif name == 'cat':
        return 'meow'
    elif name == 'jack':
        return 'oooo'
    elif name == 'snake':
        return 'ssss'
    elif name == 'monkey ':
        return None
    else
        return name
</code>```

df1['name'] = df1['name'].apply(map_name)

As the list is small, I have hardcoded here but the list might grow. Can someone tell how to do the same functionality using dataframes? Thanks.

答:
A simple merge would do it.

And then since you want the rows in df2 which are not in df1 concat them.

```<code>pd.concat([df1.merge(df2),df2[~df2['name'].isin(df1['name'])]]
</code>```

Result:

```<code>In [23]: pd.concat([df1.merge(df2),df2[~df2['name'].isin(df1['name'])]])
Out[23]:
    ID    name change_name
0  1.0     cat        meow
1  2.0    jack        oooo
2  3.0   snake        ssss
3  4.0  monkey        None
4  NaN    note       money
5  NaN  pencil         pen
</code>```

Title: Fetch data from another dataframe

Body:
I had asked a question earlier but it was closed as the initial question was considered as duplicate.

But I am trying to something different from that thread as well as duplicate thread.

String Replacement From Another DataFrame.

So please don't close this thread.
Thanks.

I need to replace my column depending upon data from another dataframe.
Have to search for respective "name" from the other dataframe and include the "change_name" in the df1

DataFrame 1:

ID  name
1   cat
2   jack
3   snake
4   monkey

DataFrame 2:

name    change_name
cat     meow
jack    oooo
snake   ssss
monkey
note    money
pencil pen

Expected Output:

ID  name
1   cat      meow
2   jack     oooo
3   snake    ssss
4   monkey   nan
5   note    money
6   pencil pen

I had to do like below:

def map_name(name):
    elif name == 'cat':
        return 'meow'
    elif name == 'jack':
        return 'oooo'
    elif name == 'snake':
        return 'ssss'
    elif name == 'monkey ':
        return None
    else
        return name

df1['name'] = df1['name'].apply(map_name)

As the list is small, I have hardcoded here but the list might grow. Can someone tell how to do the same functionality using dataframes? Thanks.

Body:
A simple merge would do it.

And then since you want the rows in df2 which are not in df1 concat them.

pd.concat([df1.merge(df2),df2[~df2['name'].isin(df1['name'])]]

Result:

In [23]: pd.concat([df1.merge(df2),df2[~df2['name'].isin(df1['name'])]])
Out[23]:
    ID    name change_name
0  1.0     cat        meow
1  2.0    jack        oooo
2  3.0   snake        ssss
3  4.0  monkey        None
4  NaN    note       money
5  NaN  pencil         pen