问:
how to use SVG Image in Splash Screen on Expo eject
I separated 'Expo' using 'Expo object'. And I want to use SVG for resolution of splash screen. But I don't know how to do that.

I just know how to use the image in only Android.

I don't know Ios Splash Screen

Android(splash_backgroud.xml):

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/splashBackground"/>

    <item><bitmap android:gravity="center" android:src="@drawable/splash" /></item>

</layer-list>
</code>```

I created the file ic_splash.xml using the SVG image as drawable =>
  NEW => Vector Asset.

But I don't know how to apply it.

I don't know what to do with the iPhone.

Tell me how to apply the iPhone and Android.

Please help us a lot. Thank you in advance.

答:
I hid the basic splash screen and used the screen I made.

Basically, only the png, jpeg extension picture files are available on Androidand ios.

example.js

import React from 'react';
import { Image, Text, View } from 'react-native';
import { Asset, SplashScreen } from 'expo';
import SvgUri from "expo-svg-uri";

export default class App extends React.Component {
  state = {
    isReady: false,
  };

  componentDidMount() {
    SplashScreen.preventAutoHide();
  }

  render() {
    if (!this.state.isReady) {
      return (
        <View style={{ flex: 1 }}>
          <SvgUri
            width="200"
            height="200"
            source={require('./assets/images/splash.svg')}
            onLoad={this._cacheResourcesAsync}
          />
        </View>
      );
    }

    return (
      <View style={{ flex: 1 }}>
        <Image source={require('./assets/images/expo-icon.png')} />
        <Image source={require('./assets/images/slack-icon.png')} />
      </View>
    );
  }

  _cacheResourcesAsync = async () => {
    SplashScreen.hide();
    const images = [
      require('./assets/images/expo-icon.png'),
      require('./assets/images/slack-icon.png'),
    ];

    const cacheImages = images.map((image) => {
      return Asset.fromModule(image).downloadAsync();
    });

    await Promise.all(cacheImages);
    this.setState({ isReady: true });
  }
}
```

Body:
I separated 'Expo' using 'Expo object'. And I want to use SVG for resolution of splash screen. But I don't know how to do that.

I just know how to use the image in only Android.

I don't know Ios Splash Screen

Android(splash_backgroud.xml):

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/splashBackground"/>

    <item><bitmap android:gravity="center" android:src="@drawable/splash" /></item>

</layer-list>

I created the file ic_splash.xml using the SVG image as drawable =>
  NEW => Vector Asset.

But I don't know how to apply it.

I don't know what to do with the iPhone.

Tell me how to apply the iPhone and Android.

Please help us a lot. Thank you in advance.


来源: stackexchange

问:
How to resolve "cannot move out of borrowed content" due to filtering read_dir output?
I'm trying to use read_dir to read the contents of a directory and then filter for just the files:

```<code>let xs = std::fs::read_dir(".")?
    .filter(|r_entry| {
        r_entry.and_then(|entry| {
            let m = entry.metadata()?;
            Ok(m.is_file())
        })
        .unwrap_or(false)
    })
    .collect::<Result<Vec<_>>>();
</code>```

(playground)

The error message is:

error[E0507]: cannot move out of borrowed content
 --> src/main.rs:6:13
  |
6 |             r_entry
  |             ^^^^^^^ cannot move out of borrowed content
```

I've tried various combinations of & and * around r_entry to no avail. What is happening?

答:
The predicate in filter only allows you to borrow r_entry. When you call and_then, this attempts a move. Instead, you can use the reference in a match like this:

```<code>fn main() -> Result<()> {
    let xs = std::fs::read_dir(".")?
        .filter(|r_entry| match r_entry {
            Ok(entry) => entry.metadata().map(|m| m.is_file()).unwrap_or(false),
            Err(_) => false,
        })
        .collect::<Result<Vec<_>>>();

    println!("{:?}", xs);
    Ok(())
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to use read_dir to read the contents of a directory and then filter for just the files:

let xs = std::fs::read_dir(".")?
    .filter(|r_entry| {
        r_entry.and_then(|entry| {
            let m = entry.metadata()?;
            Ok(m.is_file())
        })
        .unwrap_or(false)
    })
    .collect::<Result<Vec<_>>>();

(playground)

The error message is:

error[E0507]: cannot move out of borrowed content
 --> src/main.rs:6:13
  |
6 |             r_entry
  |             ^^^^^^^ cannot move out of borrowed content

I've tried various combinations of & and * around r_entry to no avail. What is happening?

Body:
The predicate in filter only allows you to borrow r_entry. When you call and_then, this attempts a move. Instead, you can use the reference in a match like this:

fn main() -> Result<()> {
    let xs = std::fs::read_dir(".")?
        .filter(|r_entry| match r_entry {
            Ok(entry) => entry.metadata().map(|m| m.is_file()).unwrap_or(false),
            Err(_) => false,
        })
        .collect::<Result<Vec<_>>>();

    println!("{:?}", xs);
    Ok(())
}


问:
SQL query taking longer time to execute
I'm trying to execute the query. It take 32 min to execute. I have tried NOLOCK but only optimized it with 3 min.
the query is given below:-</p>

```<code>SELECT PO.payday, PO.facility, PO.department, PO.workcenter, PO.shift, PO.team, PO.orderno, PO.fg_productno,
       PO.sfg_productno, NoCarton = '1', NoPack = 5, NoCigarette = PO.nocigarette, VNC.sampleid, VNC.comment,
       VNC.createdby, SampleDateTime = dbo.AF_GetUTCToLocal(VNC.UTCStartDate),
       SampleTime = Cast(CONVERT(CHAR(10), VNC.utcstartdate, 101) AS DATETIME), VNC.ncgroup,  VNC.productcomponent,
       VNC.nc, VNC.ncname, VNC.weightingfactor, VNC.ConsumerSensitive, VNC.[lowunits], VNC.[low %], VNC.[highunits],
       VNC.[high %], VNC.vqi, VNC.deepcontrol,
       --Modification done for CHE10045964
       PO.ResourceClassName
FROM
(SELECT PayDay = WCS.payday, Facility = R.facility, Department = R.department, WorkCenter = R.workcenter,
        Shift = WCS.workperiod, Team = SD.teamid, OrderNo = WO.orderno,
        FG_ProductNo = P.productno + Isnull('.' + P.productrevision, ''),
        SFG_ProductNo = CASE
                        WHEN UCHSC.attribute_ != P.productno
                        THEN UCHSC.attribute_
                         ELSE NULL
                         END,
        WO.actualstartdate, WO.actualcompletiondate,
        NoCigarette = dbo.Af_getunitcharacteristicattribute(OD.unitid,'ZPPPI_ITEM_PACK') ,
        RC.Name as ResourceClassName
        FROM   order_header OH
               INNER JOIN dbo.wip_order WO ON OH.orderno = WO.orderno
               INNER JOIN dbo.order_detail OD ON OD.orderno = WO.orderno
               INNER JOIN dbo. product P ON WO.productid = P.id
               INNER JOIN dbo.resource_ R ON R.resourcename = WO.resourcename AND R.resourcetype = WO.resourcetype
               Inner Join dbo.Resource_Class RC ON R.ResourceClassID = RC.ID
               INNER JOIN dbo.work_center_work_schedule WCS ON WO.oawipentityid = WCS.id
               INNER JOIN at_work_center_work_schedule_detail SD ON WCS.id = SD.workcenterworkscheduleid
               LEFT JOIN dbo.unit_characteristic UCHSC ON UCHSC.unitid = OD.unitid
                                                       AND UCHSC.characteristic = 'ZPPPI_SPA_CIGARETTE'
        WHERE  OH.ordertype = 23
        GROUP  BY WCS.payday, R.facility, R.department, R.workcenter, WCS.workperiod, SD.teamid,
                  WO.orderno, P.productno + Isnull('.' + P.productrevision, ''),
                  CASE
                    WHEN UCHSC.attribute_ != P.productno THEN UCHSC.attribute_
                    ELSE NULL
                  END,
                  WO.actualstartdate, WO.actualcompletiondate,
                  dbo.Af_getunitcharacteristicattribute(OD.unitid,'ZPPPI_ITEM_PACK'),
                  RC.Name
) PO INNER JOIN
(
SELECT NC.orderno, NC.sampleid, NC.comment, NC.deepcontrol, NC.createdby, NC.utcstartdate, NC.ncgroup, NC.productcomponent,
       NC.nc, NC.ncname, NC.weightingfactor, NC.ConsumerSensitive, NC.[lowunits], NC.[low %], NC.[highunits], NC.[high %],
       VQI = Round(NC.weightingfactor * ( Log (1 + [low %] / 3.0 + [high %]) ), 0),
       --Added By Sukanya Biswas(CHE10045964)
       NC.WorkCenter
FROM  (SELECT orderno, b.sampleid, b.comment, b.deepcontrol, b.utcstartdate, b.ncgroup, b.productcomponent,
              b.nc, b.ncname, b.weightingfactor, b.ConsumerSensitive, b.createdby,
              [LowUnits] = Isnull(b.[1], 0),
              [Low %] = CASE CONVERT(NVARCHAR(1),b.deepcontrol) + b.ncgroup
                            WHEN '0Bundle'   THEN   CASE WHEN (Isnull(b.[1], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 100 END
                            WHEN '1Bundle'   THEN   CASE WHEN (Isnull(b.[1], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 100 END
                            WHEN '0Pack'      THEN   CASE WHEN (Isnull(b.[1], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * NoofCigarette  END
                            WHEN '1Pack'      THEN   CASE WHEN (Isnull(b.[1], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * NoofCigarette  END
                            WHEN '0Cigarette' THEN   CASE WHEN (Isnull(b.[1], 0) * 5  ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 5   END
                            WHEN '1Cigarette' THEN   CASE WHEN (Isnull(b.[1], 0) * 1  ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 1   END
                            WHEN '0Filter'   THEN   CASE WHEN (Isnull(b.[1], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 10  END
                            WHEN '1Filter'   THEN   CASE WHEN (Isnull(b.[1], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 10  END
                        ELSE Isnull(b.[1], 0)
                        END, [HighUnits] = Isnull(b.[2], 0),
             [High %] = CASE CONVERT(NVARCHAR(1),b.deepcontrol) + b.ncgroup
                            WHEN '0Bundle'   THEN   CASE WHEN (Isnull(b.[2], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 100 END
                            WHEN '1Bundle'   THEN   CASE WHEN (Isnull(b.[2], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 100 END
                            WHEN '0Pack'      THEN   CASE WHEN (Isnull(b.[2], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * NoofCigarette  END
                            WHEN '1Pack'      THEN   CASE WHEN (Isnull(b.[2], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * NoofCigarette  END
                            WHEN '0Cigarette' THEN   CASE WHEN (Isnull(b.[2], 0) * 5  ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 5   END
                            WHEN '1Cigarette' THEN   CASE WHEN (Isnull(b.[2], 0) * 1  ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 1   END
                            WHEN '0Filter'   THEN   CASE WHEN (Isnull(b.[2], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 10  END
                            WHEN '1Filter'   THEN   CASE WHEN (Isnull(b.[2], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 10  END
                            ELSE Isnull(b.[2], 0)
                         END ,
                         --Added By Sukanya Biswas(CHE10045964)
                         B.WorkCenter
            FROM (SELECT D .orderno, SampleID = DTS.id,
            --Added By Sukanya Biswas(CHE10045964)
            DL.WorkCenter,
                         Comment = CASE Isnull(DTS.comment_, '')
                         WHEN '' THEN 'N/A'
                         ELSE DTS.comment_
                         END, UTCStartDate = DTS.actualstartdate, NC.ncgroup, NC.productcomponent, NC.nc, NC.ncname,
                                          NC.weightingfactor, NC.ConsumerSensitive,
                                          Severity = Isnull(QD.qualitydefectseverityid, 0),
                                          QD.noofdefects, DTS.createdby, DeepControl = DTS.overridesumresults,
                                          NoofCigarette = dbo.Af_getunitcharacteristicattribute(OD.unitid,'ZPPPI_ITEM_PACK')
                  FROM   dbo.disposition D
                  INNER JOIN dbo.disposition_line DL ON D .disposition = DL.disposition
                  --Inner Join dbo.Work_Center WC ON DL.Workcenter = WC.Workcenter
                  INNER JOIN dbo.disposition_test DT ON DT.disposition = D .disposition
                                                     AND DT.linesequenceno =  DL.linesequenceno
                  INNER JOIN dbo.disposition_test_sample DTS ON DTS.dispositiontestid = DT.id
                  LEFT JOIN quality_defect QD ON QD.dispositiontestsampleid = DTS.id
                  INNER JOIN dbo.AV_RPT_VSI_Nonconformity NC ON Isnull(QD.defectreasoncode, '00.00.00') = NC.nc
                  LEFT JOIN ORDER_DETAIL OD ON OD.ORDERNO=D.ORDERNO
                  WHERE  DL.linecode = 'VQ'

                  ) A
                  PIVOT (Sum(a.noofdefects)
                  FOR severity IN ([1],[2]))
          B)
      NC
</code>```

答:
As per your query filter and columns needed, please make index on respected columns.
By default SQL will create clustered index on your primary key, but you may create some other unclustered index on your table to make your execution faster.

You may find this link for your reference or Google it there are hundreds of article available on Internet for same.
"https://learn.microsoft.com/en-us/sql/t-sql/statements/create-index-transact-sql?view=sql-server-2017"

Title: SQL query taking longer time to execute

Body:
I'm trying to execute the query. It take 32 min to execute. I have tried NOLOCK but only optimized it with 3 min.
the query is given below:-

SELECT PO.payday, PO.facility, PO.department, PO.workcenter, PO.shift, PO.team, PO.orderno, PO.fg_productno,
       PO.sfg_productno, NoCarton = '1', NoPack = 5, NoCigarette = PO.nocigarette, VNC.sampleid, VNC.comment,
       VNC.createdby, SampleDateTime = dbo.AF_GetUTCToLocal(VNC.UTCStartDate),
       SampleTime = Cast(CONVERT(CHAR(10), VNC.utcstartdate, 101) AS DATETIME), VNC.ncgroup,  VNC.productcomponent,
       VNC.nc, VNC.ncname, VNC.weightingfactor, VNC.ConsumerSensitive, VNC.[lowunits], VNC.[low %], VNC.[highunits],
       VNC.[high %], VNC.vqi, VNC.deepcontrol,
       --Modification done for CHE10045964
       PO.ResourceClassName
FROM
(SELECT PayDay = WCS.payday, Facility = R.facility, Department = R.department, WorkCenter = R.workcenter,
        Shift = WCS.workperiod, Team = SD.teamid, OrderNo = WO.orderno,
        FG_ProductNo = P.productno + Isnull('.' + P.productrevision, ''),
        SFG_ProductNo = CASE
                        WHEN UCHSC.attribute_ != P.productno
                        THEN UCHSC.attribute_
                         ELSE NULL
                         END,
        WO.actualstartdate, WO.actualcompletiondate,
        NoCigarette = dbo.Af_getunitcharacteristicattribute(OD.unitid,'ZPPPI_ITEM_PACK') ,
        RC.Name as ResourceClassName
        FROM   order_header OH
               INNER JOIN dbo.wip_order WO ON OH.orderno = WO.orderno
               INNER JOIN dbo.order_detail OD ON OD.orderno = WO.orderno
               INNER JOIN dbo. product P ON WO.productid = P.id
               INNER JOIN dbo.resource_ R ON R.resourcename = WO.resourcename AND R.resourcetype = WO.resourcetype
               Inner Join dbo.Resource_Class RC ON R.ResourceClassID = RC.ID
               INNER JOIN dbo.work_center_work_schedule WCS ON WO.oawipentityid = WCS.id
               INNER JOIN at_work_center_work_schedule_detail SD ON WCS.id = SD.workcenterworkscheduleid
               LEFT JOIN dbo.unit_characteristic UCHSC ON UCHSC.unitid = OD.unitid
                                                       AND UCHSC.characteristic = 'ZPPPI_SPA_CIGARETTE'
        WHERE  OH.ordertype = 23
        GROUP  BY WCS.payday, R.facility, R.department, R.workcenter, WCS.workperiod, SD.teamid,
                  WO.orderno, P.productno + Isnull('.' + P.productrevision, ''),
                  CASE
                    WHEN UCHSC.attribute_ != P.productno THEN UCHSC.attribute_
                    ELSE NULL
                  END,
                  WO.actualstartdate, WO.actualcompletiondate,
                  dbo.Af_getunitcharacteristicattribute(OD.unitid,'ZPPPI_ITEM_PACK'),
                  RC.Name
) PO INNER JOIN
(
SELECT NC.orderno, NC.sampleid, NC.comment, NC.deepcontrol, NC.createdby, NC.utcstartdate, NC.ncgroup, NC.productcomponent,
       NC.nc, NC.ncname, NC.weightingfactor, NC.ConsumerSensitive, NC.[lowunits], NC.[low %], NC.[highunits], NC.[high %],
       VQI = Round(NC.weightingfactor * ( Log (1 + [low %] / 3.0 + [high %]) ), 0),
       --Added By Sukanya Biswas(CHE10045964)
       NC.WorkCenter
FROM  (SELECT orderno, b.sampleid, b.comment, b.deepcontrol, b.utcstartdate, b.ncgroup, b.productcomponent,
              b.nc, b.ncname, b.weightingfactor, b.ConsumerSensitive, b.createdby,
              [LowUnits] = Isnull(b.[1], 0),
              [Low %] = CASE CONVERT(NVARCHAR(1),b.deepcontrol) + b.ncgroup
                            WHEN '0Bundle'   THEN   CASE WHEN (Isnull(b.[1], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 100 END
                            WHEN '1Bundle'   THEN   CASE WHEN (Isnull(b.[1], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 100 END
                            WHEN '0Pack'      THEN   CASE WHEN (Isnull(b.[1], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * NoofCigarette  END
                            WHEN '1Pack'      THEN   CASE WHEN (Isnull(b.[1], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * NoofCigarette  END
                            WHEN '0Cigarette' THEN   CASE WHEN (Isnull(b.[1], 0) * 5  ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 5   END
                            WHEN '1Cigarette' THEN   CASE WHEN (Isnull(b.[1], 0) * 1  ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 1   END
                            WHEN '0Filter'   THEN   CASE WHEN (Isnull(b.[1], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 10  END
                            WHEN '1Filter'   THEN   CASE WHEN (Isnull(b.[1], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 10  END
                        ELSE Isnull(b.[1], 0)
                        END, [HighUnits] = Isnull(b.[2], 0),
             [High %] = CASE CONVERT(NVARCHAR(1),b.deepcontrol) + b.ncgroup
                            WHEN '0Bundle'   THEN   CASE WHEN (Isnull(b.[2], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 100 END
                            WHEN '1Bundle'   THEN   CASE WHEN (Isnull(b.[2], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 100 END
                            WHEN '0Pack'      THEN   CASE WHEN (Isnull(b.[2], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * NoofCigarette  END
                            WHEN '1Pack'      THEN   CASE WHEN (Isnull(b.[2], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * NoofCigarette  END
                            WHEN '0Cigarette' THEN   CASE WHEN (Isnull(b.[2], 0) * 5  ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 5   END
                            WHEN '1Cigarette' THEN   CASE WHEN (Isnull(b.[2], 0) * 1  ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 1   END
                            WHEN '0Filter'   THEN   CASE WHEN (Isnull(b.[2], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 10  END
                            WHEN '1Filter'   THEN   CASE WHEN (Isnull(b.[2], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 10  END
                            ELSE Isnull(b.[2], 0)
                         END ,
                         --Added By Sukanya Biswas(CHE10045964)
                         B.WorkCenter
            FROM (SELECT D .orderno, SampleID = DTS.id,
            --Added By Sukanya Biswas(CHE10045964)
            DL.WorkCenter,
                         Comment = CASE Isnull(DTS.comment_, '')
                         WHEN '' THEN 'N/A'
                         ELSE DTS.comment_
                         END, UTCStartDate = DTS.actualstartdate, NC.ncgroup, NC.productcomponent, NC.nc, NC.ncname,
                                          NC.weightingfactor, NC.ConsumerSensitive,
                                          Severity = Isnull(QD.qualitydefectseverityid, 0),
                                          QD.noofdefects, DTS.createdby, DeepControl = DTS.overridesumresults,
                                          NoofCigarette = dbo.Af_getunitcharacteristicattribute(OD.unitid,'ZPPPI_ITEM_PACK')
                  FROM   dbo.disposition D
                  INNER JOIN dbo.disposition_line DL ON D .disposition = DL.disposition
                  --Inner Join dbo.Work_Center WC ON DL.Workcenter = WC.Workcenter
                  INNER JOIN dbo.disposition_test DT ON DT.disposition = D .disposition
                                                     AND DT.linesequenceno =  DL.linesequenceno
                  INNER JOIN dbo.disposition_test_sample DTS ON DTS.dispositiontestid = DT.id
                  LEFT JOIN quality_defect QD ON QD.dispositiontestsampleid = DTS.id
                  INNER JOIN dbo.AV_RPT_VSI_Nonconformity NC ON Isnull(QD.defectreasoncode, '00.00.00') = NC.nc
                  LEFT JOIN ORDER_DETAIL OD ON OD.ORDERNO=D.ORDERNO
                  WHERE  DL.linecode = 'VQ'

                  ) A
                  PIVOT (Sum(a.noofdefects)
                  FOR severity IN ([1],[2]))
          B)
      NC


问:
how to search for values when the selector is an array
I have the following json document on my couch db.

```<code>{
  {
      "_id": "someid|goes|here",
      "collected": {
          "tags": ["abc", "def", "ghi"]
      }
  },
  {
      "_id": "someid1|goes|here",
      "collected": {
           "tags": ["abc", "klm","pqr"]
      },
  },
  {
      "_id": "someid2|goes|here",
      "collected": {
           "tags": ["efg", "hij","klm"]
      },
  }
}
</code>```

How can I get the records where collected.tags contains abc? What I have tried so far is

```<code>{
   "selector": {
      "collected.tags": {
         "$regex": "abc"
      }
   }
}
</code>```

答:
If I've understood correctly you are querying this from 3 different documents. Using the $elemMatch operator as per CouchDb Documentation it's possible to return all documents where at least one element that is matched based on the specified criteria. If so use the following query to filter out the text "abc":

```<code>{
  "selector": {
    "collected.tags": {
      "$elemMatch": {
        "$regex": "abc"
      }
    }
  }
}
</code>```

Hope this helps out. :)

Body:
I have the following json document on my couch db.

{
  {
      "_id": "someid|goes|here",
      "collected": {
          "tags": ["abc", "def", "ghi"]
      }
  },
  {
      "_id": "someid1|goes|here",
      "collected": {
           "tags": ["abc", "klm","pqr"]
      },
  },
  {
      "_id": "someid2|goes|here",
      "collected": {
           "tags": ["efg", "hij","klm"]
      },
  }
}

How can I get the records where collected.tags contains abc? What I have tried so far is

{
   "selector": {
      "collected.tags": {
         "$regex": "abc"
      }
   }
}

Body:
If I've understood correctly you are querying this from 3 different documents. Using the $elemMatch operator as per CouchDb Documentation it's possible to return all documents where at least one element that is matched based on the specified criteria. If so use the following query to filter out the text "abc":

{
  "selector": {
    "collected.tags": {
      "$elemMatch": {
        "$regex": "abc"
      }
    }
  }
}

Hope this helps out. :)


问:
"you do not have a secure keyguard!" when starting saferoom demo on moto g6 emulator API 28
attempting to run the saferoom demo running against an emulator defined as Pie (API 28).  using android studio 3.4 on a Lenovo Windows 10 Professional system.  sdk for API 28 is being used.

At open the app shows the message "You do not have a secure keyguard!" as a long toast on the emulated screen.

How is this corrected?

no change to the code from Github clone.

答:
resolved by opening settings in the emulator and setting a pin number for log on to the emulator.  However - each time the emulator is restarted, the settings need to be changed again.  Maybe there is a way to control this in code or some setting in android studio?

What I meant by "the settings need to be changed again" was a mistake.  Once set up with a pin, the emulator does retain the pin across restarts.  The app itself asks for the pin.  Apparently pin, password, or fingerprint must be set up through the settings app in the emulator at least once in order for the emulator to have a secure keyguard.  for my app, requesting the pin at startup is a good thing.

Thanks for the question.  it helped clarify things for me.


问:
Parameter error, SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
So I'm getting SQLSTATE[HY093]: Invalid parameter number: parameter was not defined, when I try to submit my form.  I have a reservations folder with a index.php file that has an include file as reservations.html.php which has the forms in html.  </p>

<p>So my forms in the reservations.html.php when filled out and has a value in first name will then try to post all the values in the form into the reservations table I have created in mysql.  Below are my code in the index.php </p>

```<code><?php

// Edit or Replace this try/catch statement to work with the current PHT configuration
include '../includes/db.inc.php';

// Modify the If statement so the try only runs if the First Name field has been submitted AND the honeypot field is empty ''
if (isset($_POST['myfname'])) {
    $myFName = $_POST['myfname'];
    $myTour = $_POST['tour'];
    $myLName = $_POST['mylname'];
    $myEmail = $_POST['myemail'];
    // If the if statement is true, save each form field value as a variable. These variable values will be used in the thank you page.

    // And run the try/catch to attempt to insert data in the database. Modify the INSERT statement to write all the form filed values (except the honeypot) to the database.
    try
    {
        $sql = 'INSERT INTO reservations SET
          tour = :tour,
          fname = :fname,
          lname = :lname,
          email = :email';
        $s = $pdo->prepare($sql);
        $s->bindValue(':tour', $myTour);
        $s->bindValue(':myfname', $myFName);
        $s->bindValue(':mylname', $myLName);
        $s->bindValue(':myemail', $myEmail);
        $s->execute();
    }
    catch (PDOException $e)
    {
        $error = 'Error adding submitted joke: ' . $e->getMessage();
        include '../includes/error.html.php';
        exit();
    }
    // load the thank you page after the INSERT runs
    include 'success.html.php';
    // Add an else to load the initial page if the initial (line 19) if statement is false
} else {
    include 'reservations.html.php'; //Modify this to include the initial file for this folder
}
</code>```

答:
The syntax for your insert statement is off, and appears to be hybrid between an insert and an update.  Try this version:

```<code>$sql = "INSERT INTO reservations (tour, fname, lname, email) ";
$sql .= "VALUES (:tour, :fname, :lname, :email)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':tour', $myTour, PDO::PARAM_STR);
$stmt->bindParam(':fname', $myFName, PDO::PARAM_STR);
$stmt->bindParam(':lname', $myLName, PDO::PARAM_STR);
$stmt->bindParam(':email', $myEmail, PDO::PARAM_STR);
$stmt->execute();
$stmt->close();
</code>```

To be clear here, a SQL insert statement takes the following things:

The INSERT INTO keywords, followed by a list of columns

Then a VALUES clause, followed by a tuple containing the values to be inserted

There is also an INSERT INTO ... SELECT, which uses a select statement to provide the values, but you are not using this form.

Body:
So I'm getting SQLSTATE[HY093]: Invalid parameter number: parameter was not defined, when I try to submit my form.  I have a reservations folder with a index.php file that has an include file as reservations.html.php which has the forms in html.

So my forms in the reservations.html.php when filled out and has a value in first name will then try to post all the values in the form into the reservations table I have created in mysql.  Below are my code in the index.php

<?php

// Edit or Replace this try/catch statement to work with the current PHT configuration
include '../includes/db.inc.php';

// Modify the If statement so the try only runs if the First Name field has been submitted AND the honeypot field is empty ''
if (isset($_POST['myfname'])) {
    $myFName = $_POST['myfname'];
    $myTour = $_POST['tour'];
    $myLName = $_POST['mylname'];
    $myEmail = $_POST['myemail'];
    // If the if statement is true, save each form field value as a variable. These variable values will be used in the thank you page.

    // And run the try/catch to attempt to insert data in the database. Modify the INSERT statement to write all the form filed values (except the honeypot) to the database.
    try
    {
        $sql = 'INSERT INTO reservations SET
          tour = :tour,
          fname = :fname,
          lname = :lname,
          email = :email';
        $s = $pdo->prepare($sql);
        $s->bindValue(':tour', $myTour);
        $s->bindValue(':myfname', $myFName);
        $s->bindValue(':mylname', $myLName);
        $s->bindValue(':myemail', $myEmail);
        $s->execute();
    }
    catch (PDOException $e)
    {
        $error = 'Error adding submitted joke: ' . $e->getMessage();
        include '../includes/error.html.php';
        exit();
    }
    // load the thank you page after the INSERT runs
    include 'success.html.php';
    // Add an else to load the initial page if the initial (line 19) if statement is false
} else {
    include 'reservations.html.php'; //Modify this to include the initial file for this folder
}

Body:
The syntax for your insert statement is off, and appears to be hybrid between an insert and an update.  Try this version:

$sql = "INSERT INTO reservations (tour, fname, lname, email) ";
$sql .= "VALUES (:tour, :fname, :lname, :email)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':tour', $myTour, PDO::PARAM_STR);
$stmt->bindParam(':fname', $myFName, PDO::PARAM_STR);
$stmt->bindParam(':lname', $myLName, PDO::PARAM_STR);
$stmt->bindParam(':email', $myEmail, PDO::PARAM_STR);
$stmt->execute();
$stmt->close();

To be clear here, a SQL insert statement takes the following things:

The INSERT INTO keywords, followed by a list of columns

Then a VALUES clause, followed by a tuple containing the values to be inserted

There is also an INSERT INTO ... SELECT, which uses a select statement to provide the values, but you are not using this form.


问:
Cant clear the value of TextInput in react-native
enter image description herethis problem show in ios,when i use TextInput of react-native,but it  can't type Chinese when using soft keyboard，so i modify the code like picture1,but  a new problem has arisen,when i enter the key to send ,the value of the TextInput cant clear.
what can i do?enter image desenter code herecription here

 <TextareaItem clear={true}  type="text" ref="text" value={this.state.meg}
 editable={true} disabled={false} onChange={(value) => {
                                    if (Platform.OS =='ios'){
                                        this.meg = value
                                    } else {
                                        this.setState({
                                            meg:value
                                        })}}} />

    sendMeg = () => {
        let message = ''
        if (this.meg !== '')
        messahe = this.meg
        }else{message = this.state.meg}
      this.meg = ''
      this.setState({  meg:''})
}```

solve with this answer https://github.com/CHANOMA/react-native/pull/3/files#diff-8eb50d68d87e28556c034717cd58a86e

答:
Set this.state.text to initially be an empty string ‘’

Add an actual placeholder to your component and set the value to the string ‘Enter text…’

Add the method submitAndClear to your class and set the component’s onPress prop to this.submitAndClear

Add the prop clearButtonMode='always’ to the <TextInput /> component — this will give you an option to clear the text at any time

The following can be used to clear the text

```<code>submitAndClear = () => {
  this.props.writeText(this.state.text)

  this.setState({
    text: ''
  })
}
</code>```

You're good to go!!

Body:
enter image description herethis problem show in ios,when i use TextInput of react-native,but it  can't type Chinese when using soft keyboard，so i modify the code like picture1,but  a new problem has arisen,when i enter the key to send ,the value of the TextInput cant clear.
what can i do?enter image desenter code herecription here

 <TextareaItem clear={true}  type="text" ref="text" value={this.state.meg}
 editable={true} disabled={false} onChange={(value) => {
                                    if (Platform.OS =='ios'){
                                        this.meg = value
                                    } else {
                                        this.setState({
                                            meg:value
                                        })}}} />

    sendMeg = () => {
        let message = ''
        if (this.meg !== '')
        messahe = this.meg
        }else{message = this.state.meg}
      this.meg = ''
      this.setState({  meg:''})
}

solve with this answer https://github.com/CHANOMA/react-native/pull/3/files#diff-8eb50d68d87e28556c034717cd58a86e

Body:
Set this.state.text to initially be an empty string ‘’

Add an actual placeholder to your component and set the value to the string ‘Enter text…’

Add the method submitAndClear to your class and set the component’s onPress prop to this.submitAndClear

Add the prop clearButtonMode='always’ to the <TextInput /> component — this will give you an option to clear the text at any time

The following can be used to clear the text

submitAndClear = () => {
  this.props.writeText(this.state.text)

  this.setState({
    text: ''
  })
}

You're good to go!!


问:
How to Convince management to upgrade to .Net 4.0
We developed an application using .net 2.0.
We license our software which means whenever we release a new version, we have to push out the change to all our existing clients.

No one in my group has the slightest motivation to upgrade to a newer version of .net. They simple see it as more work for our support team to deploy and argue that clients will be resistant to any change.

Can anyone point me in the direction of some argument i could present to Non programmers that might sway them.

If noting else, some argument that it is safe, and will not cause our clients any harm who already have the .net 2.0 framework on their machines?

I figure it's hopeless. I'm gonna be stuck using the .net 2.0 framework until for another 4 or 5 years i bet... perhaps longer :( help!

I really want to be able to use WCF, LINQ, WPF (possible), and the option to use the Entity Framework 4.0.!

thanks

jonathan

答:
Quick Fix : Just list the bugs and lack of features in Entity Framework 1.0 and the almost crappy edmx editor.
Long Term Fix: Adhere to Hollywood principle and management will call u when they are ready for .net 4 </p>

ContentLicense: CC BY-SA 3.0


问:
ClassNotFoundException: Didn't find class "androidx.work.Worker" on path: DexPathList
I have been trying to make an android library, whenin I'm making use of WorkManager's PeriodicWorkRequest. It works flawlessly as a module in the host development app. However, once I export it as an aar file and use it in another app, I get the following error,

```<code>java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/work/Worker;
.
.
.
Caused by: java.lang.ClassNotFoundException: Didn't find class "androidx.work.Worker" on path: DexPathList[[zip file "/data/app/com.example.testapp-0WusKIYjC1qsHRMASLjm1Q==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.testapp-0WusKIYjC1qsHRMASLjm1Q==/lib/arm64, /system/lib64, /vendor/lib64]]
</code>```

Any idea how I can fix this?

答: you have a dependency error , the app your are trying to use your library use androidx support library , try to change WorkManager's  dependency to androidx dependency

Body:
I have been trying to make an android library, whenin I'm making use of WorkManager's PeriodicWorkRequest. It works flawlessly as a module in the host development app. However, once I export it as an aar file and use it in another app, I get the following error,

java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/work/Worker;
.
.
.
Caused by: java.lang.ClassNotFoundException: Didn't find class "androidx.work.Worker" on path: DexPathList[[zip file "/data/app/com.example.testapp-0WusKIYjC1qsHRMASLjm1Q==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.testapp-0WusKIYjC1qsHRMASLjm1Q==/lib/arm64, /system/lib64, /vendor/lib64]]

Any idea how I can fix this?


问:
Pass array by reference to Laravel Event Listener
I have an array in Laravel applications that I would like to modify in Laravel listener. PHP by default passes an array by value however, the way Laravel events and its listeners work I am unable to modify the original variable. Is there a better way than what I am doing below?

The Model where the event is fired from.

Model: Event.php

```<code>namespace Vendor\Package\Models

use Vendor\Package\Events\PageNodeArrayAfter;
use Event;

class Page
{
   public function toArray()
   {
      $data = [];

      // do something with the data.

      Event::fire(new PageNodeToArrayAfter($data))

      // The data should be modified by a listener when I use it here.
   }
}
</code>```

Event: PageNodeToArrayAfter.php

```<code>namespace Vendor\Package\Events;

class PageNodeToArrayAfter
{
    /**
     * Props to be sent to the view
     * @var array $data
     */
    protected $data = [];

    /**
     * @param array $data
     *
     */
    public function __construct(array &$data)
    {
        $this->data = $data;
    }

    public function getData()
    {
        return $this->data;
    }
}
</code>```

Listener: FlashMessagesListner.php

```<code>namespace Vendor\Package\Listeners;

class FlashMessagesListner
{
    protected $data = [];

    public function handle(PageNodeToArrayAfter $event)
    {
       $this->data = $event->getData();
       // The problem here is the $data is no logner a reference here.
    }
}
</code>```

答:
I appreciate all the responses, feedback on the question and suggestions to look for a better way of doing it.

Now instead of using Listeners, I tried Laravel Pipeline which is a great way of passing the data through different pipes and in my case filtering it. This article has been very helpful in understanding it https://jeffochoa.me/understanding-laravel-pipelines

Here is the final version of my code and how am I using Laravel Pipeline:

Node: Page.php

<?php declare(strict_types=1);

namespace Vendor\Package\Nodes;

class Page extends ReactPage
{
    public function toArray() : array
    {
        $data = parent::toArray();

        $pipes = [
           AppendFlashMessage::class,
           RemoveEmptyLayoutNode::class
        ];

        // Filter data through the pipelines.
        $data = app(Pipeline::class)
            ->send($data)
            ->through($pipes)
            ->via('filter')
            ->then(function($data) {
                return $data;
        });

        return $data;
    }
}
```

<p>Pipe: <strong>AppendFlashMessage.php</strong></p>

<pre class="lang-php prettyprint-override"><code><?php declare(strict_types=1);

namespace Vendor\Package\Pipeline;

use Closure;

class AppendFlashMessage
{

    public function filter(array $data, Closure $next) : array
    {

        // step 1: pull the errors from session.
        $errors = [
            'type' => 'error',
            'message' => 'Invalid User Name'
        ];

        $data['messages'] = $errors;
        return $next($data);
    }
}

</code>```

Body:
I have an array in Laravel applications that I would like to modify in Laravel listener. PHP by default passes an array by value however, the way Laravel events and its listeners work I am unable to modify the original variable. Is there a better way than what I am doing below?

The Model where the event is fired from.

Model: Event.php

namespace Vendor\Package\Models

use Vendor\Package\Events\PageNodeArrayAfter;
use Event;

class Page
{
   public function toArray()
   {
      $data = [];

      // do something with the data.

      Event::fire(new PageNodeToArrayAfter($data))

      // The data should be modified by a listener when I use it here.
   }
}

Event: PageNodeToArrayAfter.php

namespace Vendor\Package\Events;

class PageNodeToArrayAfter
{
    /**
     * Props to be sent to the view
     * @var array $data
     */
    protected $data = [];

    /**
     * @param array $data
     *
     */
    public function __construct(array &$data)
    {
        $this->data = $data;
    }

    public function getData()
    {
        return $this->data;
    }
}

Listener: FlashMessagesListner.php

namespace Vendor\Package\Listeners;

class FlashMessagesListner
{
    protected $data = [];

    public function handle(PageNodeToArrayAfter $event)
    {
       $this->data = $event->getData();
       // The problem here is the $data is no logner a reference here.
    }
}

Body:
I appreciate all the responses, feedback on the question and suggestions to look for a better way of doing it.

Now instead of using Listeners, I tried Laravel Pipeline which is a great way of passing the data through different pipes and in my case filtering it. This article has been very helpful in understanding it https://jeffochoa.me/understanding-laravel-pipelines

Here is the final version of my code and how am I using Laravel Pipeline:

Node: Page.php

<?php declare(strict_types=1);

namespace Vendor\Package\Nodes;

class Page extends ReactPage
{
    public function toArray() : array
    {
        $data = parent::toArray();

        $pipes = [
           AppendFlashMessage::class,
           RemoveEmptyLayoutNode::class
        ];

        // Filter data through the pipelines.
        $data = app(Pipeline::class)
            ->send($data)
            ->through($pipes)
            ->via('filter')
            ->then(function($data) {
                return $data;
        });

        return $data;
    }
}

Pipe: AppendFlashMessage.php

<?php declare(strict_types=1);

namespace Vendor\Package\Pipeline;

use Closure;

class AppendFlashMessage
{

    public function filter(array $data, Closure $next) : array
    {

        // step 1: pull the errors from session.
        $errors = [
            'type' => 'error',
            'message' => 'Invalid User Name'
        ];

        $data['messages'] = $errors;
        return $next($data);
    }
}


问:
Java Timer & KeyEvents problem
I have been making Tetris game and it's almost complete. I have a problem with KeyEvents and a Timer.

My Timer calls actionPerformed every 400ms which drops down tetris block. Problem is that if I press something from the keyboard (down, left, right etc), those commands are noted also every 400 milliseconds. How can I make the timer call actionPerformed every 400ms but so that I can press whenever and how many times I want something from the keyboard and it's instantly recognized/responded to?

EDIT: Here's some of code like people asked

```<code>public class Game extends JPanel implements ActionListener {

public static final HashMap<Character, Color> colors = new HashMap<Character,Color>();
Timer timer;
Block kpl;
Grid gameBoard;
char[][] grid;
boolean paused = false;

public Game() {

    colors.put('P', Color.blue); colors.put('S', Color.green);
    colors.put('D', Color.pink); colors.put('L', Color.red);
    colors.put('Z', Color.orange); colors.put('A', Color.cyan);
    colors.put('T', Color.magenta);
    kpl = new Block();
    gameBoard = new Grid(21,10); // 21x10 sized gameboard
    grid = gameBoard.getGrid();
    addKeyListener(new KeyListening());
    setDoubleBuffered(true);
    setFocusable(true);
    timer = new Timer(100, this);
    timer.start();

}

@Override
public void paint(Graphics g) { // draws the current game situation
    super.paint(g);

        int height = getHeight()/grid.length;
        int width = getWidth()/grid[0].length/2;

        for (int row = 0; row < grid.length; ++row) {
            for (int column = 0; column < grid[row].length; ++column) {

                if (grid[row][column] == '.') { // if empty, paint white
                    g.setColor(Color.white);
                    g.fillRect(column*width, row*height , width, height);
                    g.setColor(Color.LIGHT_GRAY);
                    g.drawRect(column*width, row*height , width, height);
                }
                else if (grid[row][column] != '.') { // if not empty, paint with the color of the block
                    g.setColor(colors.get(grid[row][column]));
                    g.fillRect(column*width, row*height , width, height);
                    g.setColor(Color.BLACK);
                    g.drawRect(column*width, row*height , width, height);
                }
            }
        }

    Toolkit.getDefaultToolkit().sync();
    g.dispose();
}

public void actionPerformed(ActionEvent e) {
    if (!gameBoard.isFallingBlock())
        gameBoard.drop(kpl); // if not any falling blocks, drops a new block

    gameBoard.updateView(); // moves the block down
    repaint();
}

    private class KeyListening extends KeyAdapter {

    @Override
    public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();

        switch (key) {
            case KeyEvent.VK_LEFT:
                gameBoard.move("v"); // moves block left
                break;
            case KeyEvent.VK_RIGHT:
                gameBoard.move("o"); // moves block right
                break;
            case KeyEvent.VK_DOWN:
                gameBoard.updateView(); // moves block down
                break;
            case KeyEvent.VK_SPACE:
                gameBoard.move("p"); // drops the block to the bottom
                break;
            case KeyEvent.VK_UP: // rotates block
                gameBoard.move("k");
                break;
            case KeyEvent.VK_P: // makes the game pause
                if (paused) {
                    timer.start();
                    paused = false;
                    return;
                }

                timer.stop();
                paused = true;
                break;

        }

    }

}
</code>```

}

Had to translate the variables a little since I have been naming them with my own language. GUI is also pretty simple since I made first a text version of my Tetris so it basically runs the text version of it in the background and just paints the situation of the game.

Text version itself is char typed matrix where I move the blocks, for example:

```<code>..P..
..ppp
.....
.....
</code>```

SOLVED:

Problem solved! In public void keyPressed() after every command coming from keyboard I just called repaint()-method again like

```<code>        public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();
        switch (key) {
            case KeyEvent.VK_LEFT:
                gameBoard.move("v");
                repaint();
                break;
</code>```

Originally my game responded to my keyboard commands instantly but drew the current state of game every 400ms in actionPerformed() where the repaint() was called. Now my blocks can be moved whenever I want without any "delay" and they're still dropping steady every 400ms :)

答: I'd try decreasing the timer interval to make keypresses more responsive and use a counter to drop down the block once every so many intervals.</p>

Title: Java Timer & KeyEvents problem

Body:
I have been making Tetris game and it's almost complete. I have a problem with KeyEvents and a Timer.

My Timer calls actionPerformed every 400ms which drops down tetris block. Problem is that if I press something from the keyboard (down, left, right etc), those commands are noted also every 400 milliseconds. How can I make the timer call actionPerformed every 400ms but so that I can press whenever and how many times I want something from the keyboard and it's instantly recognized/responded to?

EDIT: Here's some of code like people asked

public class Game extends JPanel implements ActionListener {

public static final HashMap<Character, Color> colors = new HashMap<Character,Color>();
Timer timer;
Block kpl;
Grid gameBoard;
char[][] grid;
boolean paused = false;

public Game() {

    colors.put('P', Color.blue); colors.put('S', Color.green);
    colors.put('D', Color.pink); colors.put('L', Color.red);
    colors.put('Z', Color.orange); colors.put('A', Color.cyan);
    colors.put('T', Color.magenta);
    kpl = new Block();
    gameBoard = new Grid(21,10); // 21x10 sized gameboard
    grid = gameBoard.getGrid();
    addKeyListener(new KeyListening());
    setDoubleBuffered(true);
    setFocusable(true);
    timer = new Timer(100, this);
    timer.start();

}

@Override
public void paint(Graphics g) { // draws the current game situation
    super.paint(g);

        int height = getHeight()/grid.length;
        int width = getWidth()/grid[0].length/2;

        for (int row = 0; row < grid.length; ++row) {
            for (int column = 0; column < grid[row].length; ++column) {

                if (grid[row][column] == '.') { // if empty, paint white
                    g.setColor(Color.white);
                    g.fillRect(column*width, row*height , width, height);
                    g.setColor(Color.LIGHT_GRAY);
                    g.drawRect(column*width, row*height , width, height);
                }
                else if (grid[row][column] != '.') { // if not empty, paint with the color of the block
                    g.setColor(colors.get(grid[row][column]));
                    g.fillRect(column*width, row*height , width, height);
                    g.setColor(Color.BLACK);
                    g.drawRect(column*width, row*height , width, height);
                }
            }
        }

    Toolkit.getDefaultToolkit().sync();
    g.dispose();
}

public void actionPerformed(ActionEvent e) {
    if (!gameBoard.isFallingBlock())
        gameBoard.drop(kpl); // if not any falling blocks, drops a new block

    gameBoard.updateView(); // moves the block down
    repaint();
}

    private class KeyListening extends KeyAdapter {

    @Override
    public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();

        switch (key) {
            case KeyEvent.VK_LEFT:
                gameBoard.move("v"); // moves block left
                break;
            case KeyEvent.VK_RIGHT:
                gameBoard.move("o"); // moves block right
                break;
            case KeyEvent.VK_DOWN:
                gameBoard.updateView(); // moves block down
                break;
            case KeyEvent.VK_SPACE:
                gameBoard.move("p"); // drops the block to the bottom
                break;
            case KeyEvent.VK_UP: // rotates block
                gameBoard.move("k");
                break;
            case KeyEvent.VK_P: // makes the game pause
                if (paused) {
                    timer.start();
                    paused = false;
                    return;
                }

                timer.stop();
                paused = true;
                break;

        }

    }

}

}

Had to translate the variables a little since I have been naming them with my own language. GUI is also pretty simple since I made first a text version of my Tetris so it basically runs the text version of it in the background and just paints the situation of the game.

Text version itself is char typed matrix where I move the blocks, for example:

..P..
..ppp
.....
.....

SOLVED:

Problem solved! In public void keyPressed() after every command coming from keyboard I just called repaint()-method again like

        public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();
        switch (key) {
            case KeyEvent.VK_LEFT:
                gameBoard.move("v");
                repaint();
                break;

Originally my game responded to my keyboard commands instantly but drew the current state of game every 400ms in actionPerformed() where the repaint() was called. Now my blocks can be moved whenever I want without any "delay" and they're still dropping steady every 400ms :)


问:
Is it possible to include a Vue.js component from a URL?
We are designing a plugin architecture and are curious if there is a way to allow including 3rd party plug-ins as Vue components through a URL.

How can I import a vue file from a remote url? For example, I am attempting to follow Alex Jover Morales's approach to importing an async componentAsync vue.js components. In this approach, when a user clicks an "import plugin" button, a vue component should appear that is imported from a url. I published the vue component that I'd like to import on a github page.

The app cannot resolve the url. Why not? What must I do to fix this?
Import error

This is the code for my vue component that is doing the importing...

```<code>  <div v-if="showPlugin">
    <MassEmailerPlugin>
    </MassEmailerPlugin>
    <button @click.prevent="addPlugin">Add Plugin</button>
  </div>
</template>

<style>
</style>

<script>
export default {
  name: "Plugins",
  components: {
    MassEmailerPlugin: () => import('https://github.com/gideongrossmanHome/test-vuejs-plugin/blob/master/index.html')
  },

  data() {
    return {
      showPlugin: false
    }

  },

  methods: {
    addPlugin() {
      this.showPlugin = true;
      console.log("showing plugin");
    }
  }
};
</script>

</code>```

Here is the component that I am trying to import...

```<code><template>
    <div>
        Plugin from url
    </div>
</template>

<script>
export default {
    name: "MassEmailerPlugin"
}
</script>
</code>```

答:
I agree with the previous comment. I think the main thing is that the code you are importing may need to be compiled to plain ol' JavaScript before you can import it (and you also need to import the actual source, not the GitHub page).

Another recommendation I would make is to simply copy the component you are trying to import into your project somewhere (maybe like /src/vendor/Component.vue for third party things) and then you can dynamically import it into your project like any other component. This approach has the benefit of not requiring you to compile the third party component since it will become part of your source code.

And if copying the code into your repo is not an option, perhaps this third party plugin is available via npm install? If it's on NPM, you could install it from there, and if it's just on GitHub, you might still be able to install it. Then still go for dynamic import.

Hope that helps.

Body:
We are designing a plugin architecture and are curious if there is a way to allow including 3rd party plug-ins as Vue components through a URL.

How can I import a vue file from a remote url? For example, I am attempting to follow Alex Jover Morales's approach to importing an async componentAsync vue.js components. In this approach, when a user clicks an "import plugin" button, a vue component should appear that is imported from a url. I published the vue component that I'd like to import on a github page.

The app cannot resolve the url. Why not? What must I do to fix this?
Import error

This is the code for my vue component that is doing the importing...

    <MassEmailerPlugin>
    </MassEmailerPlugin>
    <button @click.prevent="addPlugin">Add Plugin</button>

</template>

Here is the component that I am trying to import...

<template>

        Plugin from url

</template>


问:
Can't find Application entry file './main.js' in electron build
I have an electron app and I got this error when run electron-builder build.

```<code>Error: Application entry file "main.js" in the "/project/dist/release/mac/demo.app/Contents/Resources/app.asar" does not exist. Seems like a wrong configuration.
</code>```

This is package.json. I have set the main to dist/electron.js but I don't understand why it keep saying main.js doesn't exist.

```<code>...
"main": "dist/electron.js",
"build": {
    "productName": "demo",
    "appId": "com.auspost.pos",
    "files": [
      "dist/",
      "node_modules/**/*",
      "package.json",
      "dist/electron.js"
    ],
    "directories": {
      "output": "dist/release"
    },
    "dmg": {
      "contents": [
        {
          "x": 130,
          "y": 220
        },
        {
          "x": 410,
          "y": 220,
          "type": "link",
          "path": "/Applications"
        }
      ]
    },
    "win": {
      "target": [
        "nsis",
        "msi"
      ],
      "icon": "./electron/assets/icons/win/app.ico"
    },
    "publish": {
      "provider": "github"
    }
  },
...
"devDepencencies": {
    "electron": "^5.0.2",
    "electron-builder": "^20.41.0",
    "electron-webpack": "^2.6.2",
}
</code>```

答:
Finally figure out that because the project has electron-webpack dependency which works as a base template for electron build configuration. There are some fields are defined there which get extended.

The fix for that is either remove electron-webpack from your project dependencies or use electron-webpack convention to manage your project.

Body:
I have an electron app and I got this error when run electron-builder build.

Error: Application entry file "main.js" in the "/project/dist/release/mac/demo.app/Contents/Resources/app.asar" does not exist. Seems like a wrong configuration.

This is package.json. I have set the main to dist/electron.js but I don't understand why it keep saying main.js doesn't exist.

...
"main": "dist/electron.js",
"build": {
    "productName": "demo",
    "appId": "com.auspost.pos",
    "files": [
      "dist/",
      "node_modules/**/*",
      "package.json",
      "dist/electron.js"
    ],
    "directories": {
      "output": "dist/release"
    },
    "dmg": {
      "contents": [
        {
          "x": 130,
          "y": 220
        },
        {
          "x": 410,
          "y": 220,
          "type": "link",
          "path": "/Applications"
        }
      ]
    },
    "win": {
      "target": [
        "nsis",
        "msi"
      ],
      "icon": "./electron/assets/icons/win/app.ico"
    },
    "publish": {
      "provider": "github"
    }
  },
...
"devDepencencies": {
    "electron": "^5.0.2",
    "electron-builder": "^20.41.0",
    "electron-webpack": "^2.6.2",
}


问:
Relationship between stream and buffer?
I'm a newbie programmer, can you help me imagine what a stream is, is it a fixed array of bytes that transfer data from i.e: a file to Y? And what is Y here, a buffer or something else?
In what way is the buffer related to stream?</p>

答:
Difference between a buffer and a stream is

A Stream is a sequence of bytes of data that transfers information from or to a specified source.

A sequence of bytes flowing into a program is called input stream. A sequence of bytes flowing out of the program is called output stream
Use of Stream makes I/O machine independent.

A Buffer is a sequence of bytes that are stored in memory.

In C, I/O operations are asynchronous: you don’t know when you have data nor how much of it. So a buffer is usually used to collect data from the stream (file, socket, device). When the buffer is full, consumers of that stream are notified and can consume data from the buffer until is depleted. Then wait for the buffer to be filled again before using that data. It is a place to store something temporarily, in order to mitigate differences between the input speed and output speed. While the producer is being faster than the consumer, the producer can continue to store the output in the buffer. When the consumer speeds up, it can read from the buffer. The buffer is there in the middle to bridge the gap.

Y in your question can be a file, socket or a device(I/O).

Hope this solves your Query :)

Title: Relationship between stream and buffer?


问:
"Fastest" hash function implemented in Java, comparing part of file
I need to compare two different files of the instance "File" in Java and want to do this with a fast hash function.

Idea:
- Hashing the 20 first lines in File 1
- Hashing the 20 first lines in File 2
- Compare the two hashes and return true if those are equal.

I want to use the "fastest" hash function ever been implemented in Java. Which one would you choose?

答:
If you want speed, do not hash! Especially not a cryptographic hash like MD5. These hashes are designed to be impossible to reverse, not fast to calculate. What you should use is a Checksum - see java.util.zip.Checksum and its two concrete implementations. Adler32 is extremely fast to compute.

Any method based on checksums or hashes is vulnerable to collisions, but you can minimise the risk by using two different methods in the way RSYNC does.

The algorithm is basically:

Check file sizes are equal

Break the files into chunks of size N bytes

Compute checksum on each pair of matching blocks and compare. Any differences prove files are not the same.

This allows for early detection of a difference. You can improve it by computing two checksums at once with different algorithms, or different block sizes.

More bits in the result mean less chance of a collision, but as soon as you go over 64 bits you are outside what Java (and the computer's CPU) can handle natively and hence get slow, so FNV-1024 is less likely to give you a false negative but is much slower.

If it is all about speed, just use Adler32 and accept that very rarely a difference will not be detected. It really is rare. Checksums like these are used to ensure the internet can spot transmission errors, and how often do you get the wrong data turning up?

It it is all about accuracy really, you will have to compare every byte. Nothing else will work.

If you can compromise between speed and accuracy, there is a wealth of options out there.


问:
IE Handling in Excel macros
I am new to Excel macros and I am trying to auto-fill the text box and select the option from Dropdown and click on Submit.

Using macros I have navigated to a page and from the page, I need to enter the text in the text box, and based on the Suggestion, I need to select the option.

Once the option is selected I need to click on continue using macros.

Here is the current code (I tried with the commented line but it's not working).

```<code>Sub Create_Change()
    Dim i As Long
    Dim URL As String
    Dim IE As Object
    Dim objElement As Object
    Dim objCollection As Object
    Dim HWNDSrc As Long
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = True
    URL = "URL to Navigate"
    IE.Navigate URL
    Application.StatusBar = URL & " is loading. Please wait..."
    Do While IE.ReadyState = 4: DoEvents: Loop
    Do Until IE.ReadyState = 4: DoEvents: Loop
    Application.StatusBar = URL & " Loaded"
    ' IE.Document.All("Search for a template").Value = "text to search"
    Set IE = Nothing
    Set objElement = Nothing
    Set objCollection = Nothing
End Sub
</code>```

HTML CODE:

<input title="Search for a template"
       class="change-template__search-input ng-pristine ng-untouched ng-valid"
       role="combobox"
       aria-expanded="false"
       aria-owns="typeahead-258-8737"
       aria-autocomplete="list"
       type="text"
       placeholder="Search for a template"
       ng-enter="getRecommendedTemplates(template.search)"
       ng-model="template.search"
       typeahead="template as template for template in getTemplateList($viewValue)"
       typeahead-focus-first="false"
       typeahead-on-select="getRecommendedTemplates($item)"
       typeahead-min-length="3">
```

答:
welcome to SO. If you need to get an element, as drHodge said, using an iterator and some sort of ID attribute is usually enough. I tried this with Google a minute ago:

```<code>Dim Item As Object
For Each Item In IE.Document.all()
If Item.getAttribute("title") = "Buscar" Then
Item.Value = "Test"
End If
Next Item
</code>```

I also made it press space, down arrow and enter, for the sake of doing something with the suggestion and searching part:

```<code>SendKeys ("{ }")
Application.Wait Now + TimeSerial(0, 0, 1)
SendKeys ("{DOWN}"), True
Application.Wait Now + TimeSerial(0, 0, 1)
SendKeys ("{ENTER}"), True
</code>```

(I do not recommend using SendKeys on any script, tho; it's quite unreliable.)

Title: IE Handling in Excel macros

Body:
I am new to Excel macros and I am trying to auto-fill the text box and select the option from Dropdown and click on Submit.

Using macros I have navigated to a page and from the page, I need to enter the text in the text box, and based on the Suggestion, I need to select the option.

Once the option is selected I need to click on continue using macros.

Here is the current code (I tried with the commented line but it's not working).

Sub Create_Change()
    Dim i As Long
    Dim URL As String
    Dim IE As Object
    Dim objElement As Object
    Dim objCollection As Object
    Dim HWNDSrc As Long
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = True
    URL = "URL to Navigate"
    IE.Navigate URL
    Application.StatusBar = URL & " is loading. Please wait..."
    Do While IE.ReadyState = 4: DoEvents: Loop
    Do Until IE.ReadyState = 4: DoEvents: Loop
    Application.StatusBar = URL & " Loaded"
    ' IE.Document.All("Search for a template").Value = "text to search"
    Set IE = Nothing
    Set objElement = Nothing
    Set objCollection = Nothing
End Sub

HTML CODE:

<input title="Search for a template"
       class="change-template__search-input ng-pristine ng-untouched ng-valid"
       role="combobox"
       aria-expanded="false"
       aria-owns="typeahead-258-8737"
       aria-autocomplete="list"
       type="text"
       placeholder="Search for a template"
       ng-enter="getRecommendedTemplates(template.search)"
       ng-model="template.search"
       typeahead="template as template for template in getTemplateList($viewValue)"
       typeahead-focus-first="false"
       typeahead-on-select="getRecommendedTemplates($item)"
       typeahead-min-length="3">

Body:
welcome to SO. If you need to get an element, as drHodge said, using an iterator and some sort of ID attribute is usually enough. I tried this with Google a minute ago:

Dim Item As Object
For Each Item In IE.Document.all()
If Item.getAttribute("title") = "Buscar" Then
Item.Value = "Test"
End If
Next Item

I also made it press space, down arrow and enter, for the sake of doing something with the suggestion and searching part:

SendKeys ("{ }")
Application.Wait Now + TimeSerial(0, 0, 1)
SendKeys ("{DOWN}"), True
Application.Wait Now + TimeSerial(0, 0, 1)
SendKeys ("{ENTER}"), True

(I do not recommend using SendKeys on any script, tho; it's quite unreliable.)


问:
ORA-01843: not a valid month ORA-06512: at line 5 and ORA-01861: literal does not match format string ORA-06512: at line 5
procedure created accurately but execution time getting error mentioned in title.</p>

```<code>DECLARE
     var NUMBER;
     var1 NUMBER;
BEGIN
     sale_procedure(outletid => 809,itemcod => 128169,start_date => '2018-1-1',end_date => '2019-1-1'
     ,amount => var,quantity => var1);

     dbms_output.enable;
     dbms_output.put_line(var);
End;
/
</code>```

答:
Seems like the dates passed as an input parameter (START_Date, END_DATE) need to be "Date" datatype or use the string format according to your NLS_DATE_FORMAT setting.
The string can be directly used in place of dates if they are according to NLS setting.

Better to use to_date function or date ''.

example: to_date('01-01-2019','dd-mm-rrrr')

Body:
procedure created accurately but execution time getting error mentioned in title.

DECLARE
     var NUMBER;
     var1 NUMBER;
BEGIN
     sale_procedure(outletid => 809,itemcod => 128169,start_date => '2018-1-1',end_date => '2019-1-1'
     ,amount => var,quantity => var1);

     dbms_output.enable;
     dbms_output.put_line(var);
End;
/


问:
Sending Gmail through Mandrill - Emails are delayed

Checked many solutions over the web including this :
Emails very delayed getting from mandrill to gmail

In mandrillapp.com > Settings > Domains > Sending domains, verify these 3 points:

DKIM is valid,
SPF is valid,
domain is verified.

We have noticed that those delay usually occurs after let's say a day / few hours of email sending inactivity (meaning : We are not sending any emails through mandrill during that time).

As We need massive Emails in very HIGH volume We have a real problem here.

We like very much the mandrill interface, Thus, If solution / workaround (not ugly like sending dummy email through a scheduled task /job or something) exits, We prefer it, rather than moving to another paid service.

Any suggestions are welcomed.

答: Check if the Google SMTP servers are causing the delay, this was my experience. In gmail, open the email that was delayed and in the top right select More > Show Original) and copy and paste the email header into the google Message header analyzer. This will show you the path your email took and how long it was delayed at each server. My research as to why gmail caused delay has turned up nil, even though many people are experiencing the problem. I suspect it's because the emails are being put on the grey list queue in gmail.</p>


问:
Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?
The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.?

function myJsFunc() {
    alert("myJsFunc");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Run JavaScript Code</code>```

or

function myJsFunc() {
    alert("myJsFunc");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> Run JavaScript Code</code>```

答:
You can use javascript:void(0) here instead of using # to stop anchor tag redirect to header section.</p>

```<code>function helloFunction() {
    alert("hello world");
}
<a href="javascript:void(0)" onclick="helloFunction();">Call Hello Function</a>
</code>```

Body:
The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.?

function myJsFunc() {
    alert("myJsFunc");
}

Run JavaScript Code

or

function myJsFunc() {
    alert("myJsFunc");
}

 Run JavaScript Code

Body:
You can use javascript:void(0) here instead of using # to stop anchor tag redirect to header section.

function helloFunction() {
    alert("hello world");
}
<a href="javascript:void(0)" onclick="helloFunction();">Call Hello Function</a>


问:
Why git is hanging on git commit with directory of ~1000 files
I have a large nested directory with < 1000 files throughout. They are on an external hard drive exthd.

```<code>$ cd /Volumes/exthd/project
$ tree 10/44/
├── 0
│   └── record.yaml
├── 00
│   ├── 11
│   │   └── record.yaml
│   ├── 18
│   │   └── record.yaml
│   ├── 37
│   │   └── record.yaml
│   ├── 41
│   │   └── record.yaml
│   ├── 43
│   │   └── record.yaml
│   ├── 47
│   │   └── record.yaml
│   ├── 77
│   │   └── record.yaml
│   └── 83
│       └── record.yaml
├── 01
│   ├── 02
│   │   └── record.yaml
│   ├── 07
│   │   └── record.yaml
│   ├── 27
│   │   └── record.yaml
│   ├── 61
│   │   └── record.yaml
│   ├── 63
│   │   └── record.yaml
│   ├── 67
│   │   └── record.yaml
│   ├── 68
│   │   └── record.yaml
│   ├── 73
│   │   └── record.yaml
│   └── record.yaml
├── 02
│   ├── 17
│   │   └── record.yaml
│   ├── 33
│   │   └── record.yaml
│   ├── 38
│   │   └── record.yaml
│   ├── 47
│   │   └── record.yaml
│   ├── 58
│   │   └── record.yaml
│   ├── 63
│   │   └── record.yaml
│   ├── 77
│   │   └── record.yaml
│   └── 88
│       └── record.yaml
├── 02
│   ├── 01
│   │   └── record.yaml
│   ├── 41
│   │   └── record.yaml
│   ├── 48
│   │   └── record.yaml
│   ├── 73
│   │   └── record.yaml
│   ├── 83
│   │   └── record.yaml
│   └── record.yaml
├── 04
│   ├── 27
│   │   └── record.yaml
│   ├── 33
│   │   └── record.yaml
│   ├── 48
│   │   └── record.yaml
│   ├── 61
│   │   └── record.yaml
│   ├── 67
│   │   └── record.yaml
│   ├── 73
│   │   └── record.yaml
│   └── record.yaml
├── 05
│   ├── 08
│   │   └── record.yaml
│   ├── 11
│   │   └── record.yaml
│   ├── 17
│   │   └── record.yaml
│   ├── 38
│   │   └── record.yaml
│   ├── 41
│   │   └── record.yaml
│   ├── 53
│   │   └── record.yaml
│   ├── 58
│   │   └── record.yaml
│   ├── 71
│   │   └── record.yaml
│   └── 87
│       └── record.yaml
├── 06
│   ├── 07
│   │   └── record.yaml
│   ├── 11
│   │   └── record.yaml
│   ├── 31
│   │   └── record.yaml
│   └── 41
│       └── record.yaml
├── 07
│   ├── 43
│   │   └── record.yaml
│   ├── 67
│   │   └── record.yaml
│   ├── 78
│   │   └── record.yaml
│   ├── 88
│   │   └── record.yaml
│   └── record.yaml
├── 08
│   ├── 08
│   │   └── record.yaml
│   ├── 51
│   │   └── record.yaml
│   ├── 53
│   │   └── record.yaml
│   ├── 63
│   │   └── record.yaml
│   ├── 68
│   │   └── record.yaml
│   └── record.yaml
├── 08
│   ├── 01
│   │   └── record.yaml
│   ├── 67
│   │   └── record.yaml
│   ├── 73
│   │   └── record.yaml
│   ├── 77
│   │   └── record.yaml
│   └── 78
│       └── record.yaml
├── 1
│   └── record.yaml
├── 10
│   ├── 27
│   │   └── record.yaml
│   ├── 37
│   │   └── record.yaml
│   ├── 48
│   │   └── record.yaml
│   └── 88
│       └── record.yaml
├── 11
│   ├── 21
│   │   └── record.yaml
│   ├── 33
│   │   └── record.yaml
│   └── 47
│       └── record.yaml
├── 12
│   ├── 31
│   │   └── record.yaml
│   ├── 37
│   │   └── record.yaml
│   ├── 53
│   │   └── record.yaml
│   ├── 58
│   │   └── record.yaml
│   ├── 67
│   │   └── record.yaml
│   ├── 73
│   │   └── record.yaml
│   ├── 83
│   │   └── record.yaml
│   └── 87
│       └── record.yaml
├── 13
│   ├── 37
│   │   └── record.yaml
│   ├── 38
│   │   └── record.yaml
│   ├── 57
│   │   └── record.yaml
│   ├── 68
│   │   └── record.yaml
│   ├── 73
│   │   └── record.yaml
│   └── 88
│       └── record.yaml
├── 14
│   ├── 11
│   │   └── record.yaml
│   ├── 23
│   │   └── record.yaml
│   ├── 27
│   │   └── record.yaml
│   ├── 33
│   │   └── record.yaml
│   ├── 38
│   │   └── record.yaml
│   ├── 47
│   │   └── record.yaml
│   ├── 63
│   │   └── record.yaml
│   └── 88
│       └── record.yaml
├── 15
│   ├── 23
│   │   └── record.yaml
│   ├── 31
│   │   └── record.yaml
│   ├── 47
│   │   └── record.yaml
│   ├── 48
│   │   └── record.yaml
│   ├── 78
│   │   └── record.yaml
│   ├── 88
│   │   └── record.yaml
│   └── 87
│       └── record.yaml
├── 16
│   ├── 01
│   │   └── record.yaml
│   ├── 18
│   │   └── record.yaml
│   ├── 31
│   │   └── record.yaml
│   ├── 33
│   │   └── record.yaml
│   ├── 87
│   │   └── record.yaml
│   └── record.yaml
├── 17
│   ├── 27
│   │   └── record.yaml
│   ├── 87
│   │   └── record.yaml
│   ├── 88
│   │   └── record.yaml
│   └── record.yaml
├── 18
│   ├── 43
│   │   └── record.yaml
│   ├── 53
│   │   └── record.yaml
│   ├── 61
│   │   └── record.yaml
│   ├── 67
│   │   └── record.yaml
│   ├── 81
│   │   └── record.yaml
│   └── 87
│       └── record.yaml
├── 18
│   ├── 02
│   │   └── record.yaml
│   ├── 08
│   │   └── record.yaml
│   ├── 38
│   │   └── record.yaml
│   ├── 57
│   │   └── record.yaml
│   ├── 67
│   │   └── record.yaml
│   ├── 78
│   │   └── record.yaml
│   ├── 87
│   │   └── record.yaml
│   └── 88
│       └── record.yaml
├── 2
│   └── record.yaml
├── 20
│   ├── 27
│   │   └── record.yaml
│   ├── 53
│   │   └── record.yaml
│   └── 83
│       └── record.yaml
├── 21
│   ├── 18
│   │   └── record.yaml
│   └── 87
│       └── record.yaml
├── 22
│   ├── 02
│   │   └── record.yaml
│   ├── 08
│   │   └── record.yaml
│   ├── 13
│   │   └── record.yaml
│   ├── 31
│   │   └── record.yaml
│   ├── 38
│   │   └── record.yaml
│   ├── 61
│   │   └── record.yaml
│   ├── 73
│   │   └── record.yaml
│   ├── 87
│   │   └── record.yaml
│   └── 83
│       └── record.yaml
├── 23
│   ├── 02
│   │   └── record.yaml
│   ├── 17
│   │   └── record.yaml
│   ├── 47
│   │   └── record.yaml
│   ├── 58
│   │   └── record.yaml
│   └── 63
│       └── record.yaml
...~1000 or so files
</code>```

I am trying to commit them to a large git repo:

```<code>$ git commit -v 10/44/ -m 'Autocommit'
</code>```

But the spinner thing goes away in the terminal after about 3 seconds, and it just sits there for > 10 minutes (before I cancelled the process). No verbose output was seen either, even with specifying -v. Wondering how to get git to commit these files other than committing them one-by-one. Wondering why it is hanging without doing any processing, or if something is happening in the background. 1000 files should take at most 5 minutes in my experience, but this goes significantly longer. If I shorten the directory, same thing.

答:
The first things to check is your Git version:

Git 2.20 added optimization in tree traversal which could impact your commit.

the commit graph introduced in GIt 2.18 can speed up the retrieval on latest commits to build upon the next one

the diff --historigram has been optimized in Git 2.19

Git pack-object size is smaller with Git 2.21

etc...

Body:
I have a large nested directory with < 1000 files throughout. They are on an external hard drive exthd.

$ cd /Volumes/exthd/project
$ tree 10/44/
├── 0
│   └── record.yaml
├── 00
│   ├── 11
│   │   └── record.yaml
│   ├── 18
│   │   └── record.yaml
│   ├── 37
│   │   └── record.yaml
│   ├── 41
│   │   └── record.yaml
│   ├── 43
│   │   └── record.yaml
│   ├── 47
│   │   └── record.yaml
│   ├── 77
│   │   └── record.yaml
│   └── 83
│       └── record.yaml
├── 01
│   ├── 02
│   │   └── record.yaml
│   ├── 07
│   │   └── record.yaml
│   ├── 27
│   │   └── record.yaml
│   ├── 61
│   │   └── record.yaml
│   ├── 63
│   │   └── record.yaml
│   ├── 67
│   │   └── record.yaml
│   ├── 68
│   │   └── record.yaml
│   ├── 73
│   │   └── record.yaml
│   └── record.yaml
├── 02
│   ├── 17
│   │   └── record.yaml
│   ├── 33
│   │   └── record.yaml
│   ├── 38
│   │   └── record.yaml
│   ├── 47
│   │   └── record.yaml
│   ├── 58
│   │   └── record.yaml
│   ├── 63
│   │   └── record.yaml
│   ├── 77
│   │   └── record.yaml
│   └── 88
│       └── record.yaml
├── 02
│   ├── 01
│   │   └── record.yaml
│   ├── 41
│   │   └── record.yaml
│   ├── 48
│   │   └── record.yaml
│   ├── 73
│   │   └── record.yaml
│   ├── 83
│   │   └── record.yaml
│   └── record.yaml
├── 04
│   ├── 27
│   │   └── record.yaml
│   ├── 33
│   │   └── record.yaml
│   ├── 48
│   │   └── record.yaml
│   ├── 61
│   │   └── record.yaml
│   ├── 67
│   │   └── record.yaml
│   ├── 73
│   │   └── record.yaml
│   └── record.yaml
├── 05
│   ├── 08
│   │   └── record.yaml
│   ├── 11
│   │   └── record.yaml
│   ├── 17
│   │   └── record.yaml
│   ├── 38
│   │   └── record.yaml
│   ├── 41
│   │   └── record.yaml
│   ├── 53
│   │   └── record.yaml
│   ├── 58
│   │   └── record.yaml
│   ├── 71
│   │   └── record.yaml
│   └── 87
│       └── record.yaml
├── 06
│   ├── 07
│   │   └── record.yaml
│   ├── 11
│   │   └── record.yaml
│   ├── 31
│   │   └── record.yaml
│   └── 41
│       └── record.yaml
├── 07
│   ├── 43
│   │   └── record.yaml
│   ├── 67
│   │   └── record.yaml
│   ├── 78
│   │   └── record.yaml
│   ├── 88
│   │   └── record.yaml
│   └── record.yaml
├── 08
│   ├── 08
│   │   └── record.yaml
│   ├── 51
│   │   └── record.yaml
│   ├── 53
│   │   └── record.yaml
│   ├── 63
│   │   └── record.yaml
│   ├── 68
│   │   └── record.yaml
│   └── record.yaml
├── 08
│   ├── 01
│   │   └── record.yaml
│   ├── 67
│   │   └── record.yaml
│   ├── 73
│   │   └── record.yaml
│   ├── 77
│   │   └── record.yaml
│   └── 78
│       └── record.yaml
├── 1
│   └── record.yaml
├── 10
│   ├── 27
│   │   └── record.yaml
│   ├── 37
│   │   └── record.yaml
│   ├── 48
│   │   └── record.yaml
│   └── 88
│       └── record.yaml
├── 11
│   ├── 21
│   │   └── record.yaml
│   ├── 33
│   │   └── record.yaml
│   └── 47
│       └── record.yaml
├── 12
│   ├── 31
│   │   └── record.yaml
│   ├── 37
│   │   └── record.yaml
│   ├── 53
│   │   └── record.yaml
│   ├── 58
│   │   └── record.yaml
│   ├── 67
│   │   └── record.yaml
│   ├── 73
│   │   └── record.yaml
│   ├── 83
│   │   └── record.yaml
│   └── 87
│       └── record.yaml
├── 13
│   ├── 37
│   │   └── record.yaml
│   ├── 38
│   │   └── record.yaml
│   ├── 57
│   │   └── record.yaml
│   ├── 68
│   │   └── record.yaml
│   ├── 73
│   │   └── record.yaml
│   └── 88
│       └── record.yaml
├── 14
│   ├── 11
│   │   └── record.yaml
│   ├── 23
│   │   └── record.yaml
│   ├── 27
│   │   └── record.yaml
│   ├── 33
│   │   └── record.yaml
│   ├── 38
│   │   └── record.yaml
│   ├── 47
│   │   └── record.yaml
│   ├── 63
│   │   └── record.yaml
│   └── 88
│       └── record.yaml
├── 15
│   ├── 23
│   │   └── record.yaml
│   ├── 31
│   │   └── record.yaml
│   ├── 47
│   │   └── record.yaml
│   ├── 48
│   │   └── record.yaml
│   ├── 78
│   │   └── record.yaml
│   ├── 88
│   │   └── record.yaml
│   └── 87
│       └── record.yaml
├── 16
│   ├── 01
│   │   └── record.yaml
│   ├── 18
│   │   └── record.yaml
│   ├── 31
│   │   └── record.yaml
│   ├── 33
│   │   └── record.yaml
│   ├── 87
│   │   └── record.yaml
│   └── record.yaml
├── 17
│   ├── 27
│   │   └── record.yaml
│   ├── 87
│   │   └── record.yaml
│   ├── 88
│   │   └── record.yaml
│   └── record.yaml
├── 18
│   ├── 43
│   │   └── record.yaml
│   ├── 53
│   │   └── record.yaml
│   ├── 61
│   │   └── record.yaml
│   ├── 67
│   │   └── record.yaml
│   ├── 81
│   │   └── record.yaml
│   └── 87
│       └── record.yaml
├── 18
│   ├── 02
│   │   └── record.yaml
│   ├── 08
│   │   └── record.yaml
│   ├── 38
│   │   └── record.yaml
│   ├── 57
│   │   └── record.yaml
│   ├── 67
│   │   └── record.yaml
│   ├── 78
│   │   └── record.yaml
│   ├── 87
│   │   └── record.yaml
│   └── 88
│       └── record.yaml
├── 2
│   └── record.yaml
├── 20
│   ├── 27
│   │   └── record.yaml
│   ├── 53
│   │   └── record.yaml
│   └── 83
│       └── record.yaml
├── 21
│   ├── 18
│   │   └── record.yaml
│   └── 87
│       └── record.yaml
├── 22
│   ├── 02
│   │   └── record.yaml
│   ├── 08
│   │   └── record.yaml
│   ├── 13
│   │   └── record.yaml
│   ├── 31
│   │   └── record.yaml
│   ├── 38
│   │   └── record.yaml
│   ├── 61
│   │   └── record.yaml
│   ├── 73
│   │   └── record.yaml
│   ├── 87
│   │   └── record.yaml
│   └── 83
│       └── record.yaml
├── 23
│   ├── 02
│   │   └── record.yaml
│   ├── 17
│   │   └── record.yaml
│   ├── 47
│   │   └── record.yaml
│   ├── 58
│   │   └── record.yaml
│   └── 63
│       └── record.yaml
...~1000 or so files

I am trying to commit them to a large git repo:

$ git commit -v 10/44/ -m 'Autocommit'

But the spinner thing goes away in the terminal after about 3 seconds, and it just sits there for > 10 minutes (before I cancelled the process). No verbose output was seen either, even with specifying -v. Wondering how to get git to commit these files other than committing them one-by-one. Wondering why it is hanging without doing any processing, or if something is happening in the background. 1000 files should take at most 5 minutes in my experience, but this goes significantly longer. If I shorten the directory, same thing.


问:
Rails default error page doesn't show on development
I built an error handler that, when there's an error in any controller method in production, reroutes the user to an error page and sends me, the developer, a notification email. This works, but I want the normal error screen to appear when I'm in development. I assumed the code to produce this was just raise e, but instead in development I'm now getting the default production error page (the one that says "We're sorry, but something went wrong".), instead of the detailed error message and trace that used to appear.

```<code>class ApplicationController < ActionController::Base
  rescue_from StandardError, with: :handle_error

  #error handler
  def handle_error(e)
    if Rails.env.production?
      #code to send email and redirect to error page
    else
      raise e
    end
  end
end
</code>```

I also tried the following:

```<code>raise
raise StandardError.new e
raise e, e.message
raise e.message
</code>```

and if I run any of those in a binding.pry console, they produce the error message I'm looking for, but the error page still just says "We're sorry, but something went wrong."

Anyone know how I can just show the default development error page?

UPDATE

This is insane...so the code to display an error normally should definitely work, but something somewhere is preventing that. If I change config.consider_all_requests_local = true on production, the errors show up on production, but then even if I copy and paste my config/environments/production.rb file into my config/environments/development.rb, the errors still don't show on development. If I enter a pry console, request.local? returns "0", signifying true, and Rails.env returns "development". I have no idea what is going on.

UPDATE 2

Apparently I'm not supposed to be rescuing exceptions on development, but even if I delete every bit of custom error handling code so my Application Controller is just empty, my errors still don't show on development. Further, I have a different app with the same exact error handling code, and for that the errors do show.

答:
create ErrorsController like below</p>

```<code>class ErrorsController < ApplicationController
   skip_before_action :login

   def not_found
     respond_to do |format|
       format.html { render status: 404 }
       format.json { render json: { error: "Not found" }, status: 404 }
     end
   end
end
</code>```

Body:
I built an error handler that, when there's an error in any controller method in production, reroutes the user to an error page and sends me, the developer, a notification email. This works, but I want the normal error screen to appear when I'm in development. I assumed the code to produce this was just raise e, but instead in development I'm now getting the default production error page (the one that says "We're sorry, but something went wrong".), instead of the detailed error message and trace that used to appear.

class ApplicationController < ActionController::Base
  rescue_from StandardError, with: :handle_error

  #error handler
  def handle_error(e)
    if Rails.env.production?
      #code to send email and redirect to error page
    else
      raise e
    end
  end
end

I also tried the following:

raise
raise StandardError.new e
raise e, e.message
raise e.message

and if I run any of those in a binding.pry console, they produce the error message I'm looking for, but the error page still just says "We're sorry, but something went wrong."

Anyone know how I can just show the default development error page?

UPDATE

This is insane...so the code to display an error normally should definitely work, but something somewhere is preventing that. If I change config.consider_all_requests_local = true on production, the errors show up on production, but then even if I copy and paste my config/environments/production.rb file into my config/environments/development.rb, the errors still don't show on development. If I enter a pry console, request.local? returns "0", signifying true, and Rails.env returns "development". I have no idea what is going on.

UPDATE 2

Apparently I'm not supposed to be rescuing exceptions on development, but even if I delete every bit of custom error handling code so my Application Controller is just empty, my errors still don't show on development. Further, I have a different app with the same exact error handling code, and for that the errors do show.

Body:
create ErrorsController like below

class ErrorsController < ApplicationController
   skip_before_action :login

   def not_found
     respond_to do |format|
       format.html { render status: 404 }
       format.json { render json: { error: "Not found" }, status: 404 }
     end
   end
end


答:
An AAR by itself does not embed or otherwise encode anything about the transitive dependencies (such as your AAR's dependency on WorkManager), so it is expected that if you're just using an AAR as a local binary dependency that you'd need to redeclare all of the transitive dependencies.

As per the Gradle Declaring Dependencies documentation, a proper dependency is in the form of a maven repository (either local or remote). A maven repository, besides hosting the AAR itself, also includes a POM file that declares the transitive dependencies your library depends on. This ensures that there's only one version of each library included in your build (as it can deduplicate transitive dependencies across multiple libraries).

You don't see this same issue when locally using a project since those transitive dependencies are included as part of the build process.

Title: ClassNotFoundException: Didn't find class "androidx.work.Worker" on path: DexPathList


问:
Rails command not available after installing with gemfile
I installed rails via a Gemfile and bundle install:

Gemfile

```<code>source "https://rubygems.org"

gem "rails",  "5.0.6"
</code>```

the gem appears to have successfully installed according to success message. However it is still not available from the command line even after a restart.

```<code>$ rails
The program 'rails' is currently not installed. You can install it by typing:
sudo apt install ruby-railties
You will have to enable the component called 'universe'
</code>```

I am using rbenv (required) and have a number of utilities in /.rbenv/shims/ (gem, rake, bundle, etc.) but not rails... so I don't know where it got installed.

gem env returns:

```<code>GEM PATHS:
 - /home/user/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0
 - /home/user/.gem/ruby/2.5.0
</code>```

but I don't see those packages there. I'm guessing it needs to be on the path, but I don't know where it is. The solution needs to work while installing with a bash script.

答: So, I was running rbenv rehash and setting the environment variable. However, the new env variables were not available until after a restart. Using the full path to /.rbenv/shims/rake solved the problem.

Body:
I installed rails via a Gemfile and bundle install:

Gemfile

source "https://rubygems.org"

gem "rails",  "5.0.6"

the gem appears to have successfully installed according to success message. However it is still not available from the command line even after a restart.

$ rails
The program 'rails' is currently not installed. You can install it by typing:
sudo apt install ruby-railties
You will have to enable the component called 'universe'

I am using rbenv (required) and have a number of utilities in /.rbenv/shims/ (gem, rake, bundle, etc.) but not rails... so I don't know where it got installed.

gem env returns:

GEM PATHS:
 - /home/user/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0
 - /home/user/.gem/ruby/2.5.0

but I don't see those packages there. I'm guessing it needs to be on the path, but I don't know where it is. The solution needs to work while installing with a bash script.


问:
A Widget that retrieves data from a Database
I'm trying to make a simple widget that displays texts taken from a database. I have created the database + a button that redirects to the MainActitivy when pressed. However, I can't seem to set the text on the button using my method.

This is a method from my DataBase class to retrieve the first "First name" and "Last name":

```<code> public String getData(int i) {
    StringBuffer buffer = new StringBuffer();
    db = this.getReadableDatabase();
    Cursor res = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + COLUMN_ID + " = "+ i, null);
    while (res.moveToNext()) {
        String firstname = res.getString(1);
        String lastname = res.getString(2);
        buffer.append(firstname);
        buffer.append(" ");
        buffer.append(lastname);
    }

    return buffer.toString();
}
</code>```

It returns a String and I later use it for setting Text on the button with the setCharSequence() method:

```<code>public class WidgetProvider extends AppWidgetProvider {

DatabaseHandler myDb;

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    String result = myDb.getData(1);

    for (int appWidgetId : appWidgetIds) {
        Intent intent = new Intent(context, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
        views.setOnClickPendingIntent(R.id.button, pendingIntent);
        views.setCharSequence(R.id.button,"setText",result);
        appWidgetManager.updateAppWidget(appWidgetId,views);
    }
}

}
</code>```

However, I can't seem to call any method that deals with the class DatabaseHandler in the WidgetProvider class. I have even tried to retrieve the Firstname+Lastname from the MainActivity, then created an instance of the MainActivity class in the WidgetProvider, but it still has errors. Are there any other ways to retrieve data from the database and display it on the Widget button? Thank you very much!

答:
You need to use:

```<code>public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    this.mContext = context;
}
</code>```

and then on your WidgetProvider class you can simply call create the DatabaseHandler instance by passing the context like:

```<code>DatabaseHandler db = new DatabaseHandler(context);
</code>```

and then call your getData() method wherever you need.

Body:
I'm trying to make a simple widget that displays texts taken from a database. I have created the database + a button that redirects to the MainActitivy when pressed. However, I can't seem to set the text on the button using my method.

This is a method from my DataBase class to retrieve the first "First name" and "Last name":

 public String getData(int i) {
    StringBuffer buffer = new StringBuffer();
    db = this.getReadableDatabase();
    Cursor res = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + COLUMN_ID + " = "+ i, null);
    while (res.moveToNext()) {
        String firstname = res.getString(1);
        String lastname = res.getString(2);
        buffer.append(firstname);
        buffer.append(" ");
        buffer.append(lastname);
    }

    return buffer.toString();
}

It returns a String and I later use it for setting Text on the button with the setCharSequence() method:

public class WidgetProvider extends AppWidgetProvider {

DatabaseHandler myDb;

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    String result = myDb.getData(1);

    for (int appWidgetId : appWidgetIds) {
        Intent intent = new Intent(context, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
        views.setOnClickPendingIntent(R.id.button, pendingIntent);
        views.setCharSequence(R.id.button,"setText",result);
        appWidgetManager.updateAppWidget(appWidgetId,views);
    }
}

}

However, I can't seem to call any method that deals with the class DatabaseHandler in the WidgetProvider class. I have even tried to retrieve the Firstname+Lastname from the MainActivity, then created an instance of the MainActivity class in the WidgetProvider, but it still has errors. Are there any other ways to retrieve data from the database and display it on the Widget button? Thank you very much!

Body:
You need to use:

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    this.mContext = context;
}

and then on your WidgetProvider class you can simply call create the DatabaseHandler instance by passing the context like:

DatabaseHandler db = new DatabaseHandler(context);

and then call your getData() method wherever you need.