问:
Vue is not a constructor error, using Typescript & webpack
I'm using Typescript & Webpack. My code is below. I'm running it in chrome and it gives the error:

```<code>Uncaught TypeError: vue_1.default is not a constructor
    at Object.defineProperty.value (Index.ts:3)
    at __webpack_require__ (bootstrap f29fbbb047d131556dcf:19)
    at Object.defineProperty.value (bootstrap f29fbbb047d131556dcf:62)
    at bootstrap f29fbbb047d131556dcf:62
</code>```

I have added the import, also did the resolve -> alias -> vue part. And tried a whole bunch of other stuff but it didn't work. I also played around with the tsconfig file but no luck.

How do I solve this?

webpack.config.js

```<code>var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');

module.exports = {
    context: __dirname,//another dir +"/app"
    // devtool: debug ? "inline-sourcemap" : null,

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    entry: "./code/client/scripts/Index.ts",
    output: {
        path: __dirname + "/code/client/views",
        filename: "scripts.min.js"
    },
    plugins: debug ? [] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({mangle: false, sourcemap: false}),
        new webpack.IgnorePlugin(/fs/),
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        })
    ],
    node: {
        fs: 'empty',
        child_process: 'empty',
    },

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        alias: {
            vue: 'vue/dist/vue.js'
        },
        extensions: [".ts", ".tsx", ".js", ".json"]
    },

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            { test: /\.tsx?$/, loader: "awesome-typescript-loader" },

            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
        ]
    },
};
</code>```

tsconfig.js

```<code>{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2015",
    "noImplicitThis": true,
    "sourceMap": true,
    "strictNullChecks": true,
    "removeComments": false,
    "moduleResolution": "node",
    "types": [
      "node",
      "mocha",
      "chai"
    ],
    "typeRoots": [
      "node_modules/@types"
    ]
  },
  "exclude": [
    "node_modules"
  ]
}
</code>```

index.ts

```<code>import Vue from "vue"

var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!',
    }
})
console.log(app)
</code>```

html

```<code><div id="app">
    <p>{{ message }}</p>
    <input v-model="message">
</div>
</code>```

答:
The vue/dist/vue.js file does not have a default export, but Vue also provides an ES module version: vue/dist/vue.esm.js. You want to use this one, since you are using it as an ES module with the import statement.

Your alias should be:

```<code>alias: {
    'vue': 'vue/dist/vue.esm.js'
},
</code>```

Body:
I'm using Typescript & Webpack. My code is below. I'm running it in chrome and it gives the error:

Uncaught TypeError: vue_1.default is not a constructor
    at Object.defineProperty.value (Index.ts:3)
    at __webpack_require__ (bootstrap f29fbbb047d131556dcf:19)
    at Object.defineProperty.value (bootstrap f29fbbb047d131556dcf:62)
    at bootstrap f29fbbb047d131556dcf:62

I have added the import, also did the resolve -> alias -> vue part. And tried a whole bunch of other stuff but it didn't work. I also played around with the tsconfig file but no luck.

How do I solve this?

webpack.config.js

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');

module.exports = {
    context: __dirname,//another dir +"/app"
    // devtool: debug ? "inline-sourcemap" : null,

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    entry: "./code/client/scripts/Index.ts",
    output: {
        path: __dirname + "/code/client/views",
        filename: "scripts.min.js"
    },
    plugins: debug ? [] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({mangle: false, sourcemap: false}),
        new webpack.IgnorePlugin(/fs/),
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        })
    ],
    node: {
        fs: 'empty',
        child_process: 'empty',
    },

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        alias: {
            vue: 'vue/dist/vue.js'
        },
        extensions: [".ts", ".tsx", ".js", ".json"]
    },

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            { test: /\.tsx?$/, loader: "awesome-typescript-loader" },

            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
        ]
    },
};

tsconfig.js

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2015",
    "noImplicitThis": true,
    "sourceMap": true,
    "strictNullChecks": true,
    "removeComments": false,
    "moduleResolution": "node",
    "types": [
      "node",
      "mocha",
      "chai"
    ],
    "typeRoots": [
      "node_modules/@types"
    ]
  },
  "exclude": [
    "node_modules"
  ]
}

index.ts

import Vue from "vue"

var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!',
    }
})
console.log(app)

html

{{ message }}

    <input v-model="message">

Body:
The vue/dist/vue.js file does not have a default export, but Vue also provides an ES module version: vue/dist/vue.esm.js. You want to use this one, since you are using it as an ES module with the import statement.

Your alias should be:

alias: {
    'vue': 'vue/dist/vue.esm.js'
},


来源: stackexchange

问:
under the hood execution of if condition in PHP
Following block of code throws an exception that variable $booking is undefined. can someone explain why?

```<code>if(
     trim($request->id)!=''
     && $booking = Booking::find($request->id)
     && $booking->user_id == auth()->user()->id // undefined variable $booking
       ) {
          return response()->json($booking);
    }
    else {
          return response()->json(['message' => 'not found'],404);
    }
</code>```

However this works without any issue

```<code>if(
    trim($request->id)!=''
    && $booking = Booking::find($request->id)
    ) {
      if($booking->user_id == auth()->user()->id)
                    return response()->json($booking);
}
return response()->json(['message' => 'not found'],404);
</code>```

答:
The two fragments of code you gave, the one that is throwing an exception, and the one that is working, are not equivalent. The first one is missing the boolean expression $booking->user_id != null. Probalby, you should code:

```<code>if(
     trim($request->id)!=''
     && $booking = Booking::find($request->id)
     && $booking->user_id != null               // added stuff here
     && $booking->user_id == auth()->user()->id // $booking no more undefined
       ) {
          return response()->json($booking);
    }
    else {
          return response()->json(['message' => 'not found'],404);
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Following block of code throws an exception that variable $booking is undefined. can someone explain why?

if(
     trim($request->id)!=''
     && $booking = Booking::find($request->id)
     && $booking->user_id == auth()->user()->id // undefined variable $booking
       ) {
          return response()->json($booking);
    }
    else {
          return response()->json(['message' => 'not found'],404);
    }

However this works without any issue

if(
    trim($request->id)!=''
    && $booking = Booking::find($request->id)
    ) {
      if($booking->user_id == auth()->user()->id)
                    return response()->json($booking);
}
return response()->json(['message' => 'not found'],404);

Body:
The two fragments of code you gave, the one that is throwing an exception, and the one that is working, are not equivalent. The first one is missing the boolean expression $booking->user_id != null. Probalby, you should code:

if(
     trim($request->id)!=''
     && $booking = Booking::find($request->id)
     && $booking->user_id != null               // added stuff here
     && $booking->user_id == auth()->user()->id // $booking no more undefined
       ) {
          return response()->json($booking);
    }
    else {
          return response()->json(['message' => 'not found'],404);
    }


问:
JPA Mapping Error -not provided sufficient metadata in your id class
I am trying to do mapping in JPA.

```<code>@Entity
public class Auction {

    @Id
    private Integer auctionId;

    @OneToMany(mappedBy="auctionId")
    @MapKey(name="auctionParamId")
    private Map<AuctionParam, AuctionParamValue> values;

}

@Entity
public class AuctionParam {

    @Id
    private Integer auctionParamId;

    private String description;

}

@Entity
public class AuctionParamValue {

    @EmbeddedId
    private AuctionParamValuePK pk;

    private String value;

}

@Embeddable
public class AuctionParamValuePK {

    @ManyToOne
    @JoinColumn(name="auctionId")
    private Auction auction;

    @ManyToOne
    @JoinColumn(name="auctionParamId")
    private AuctionParam auctionParam;

}
</code>```

Showing an error:-

.Error-Details:-Exception Description:
  Entity [class
  com.eaportal.domain.AuctionParamValue]

  uses [class
  com.eaportal.domain.AuctionParamValuePK]

  as embedded id class

  whose access-type
  has been determined as [FIELD].

  But
  [class
  com.eaportal.domain.AuctionParamValuePK]

  does not define any [FIELD]. It is
  likely that you have not provided

  sufficient metadata in your id class
  [class
  com.eaportal.domain.AuctionParamValuePK].

If you come up with a solution please let me know.

Thanks in Advance
Tushar

答:
You cannot use an EmbeddedId with relationships.  Use an IdClass.</p>

```<code>@Entity
@IdClass(AuctionParamValuePK.class)
public class AuctionParamValue {

    @Id
    @ManyToOne
    @JoinColumn(name="auctionId")
    private Auction auction;

    @Id
    @ManyToOne
    @JoinColumn(name="auctionParamId")
    private AuctionParam auctionParam;

    @Basic
    private String value;

}

public class AuctionParamValuePK {

    private int auction;
    private int auctionParam;

}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to do mapping in JPA.

@Entity
public class Auction {

    @Id
    private Integer auctionId;

    @OneToMany(mappedBy="auctionId")
    @MapKey(name="auctionParamId")
    private Map<AuctionParam, AuctionParamValue> values;

}

@Entity
public class AuctionParam {

    @Id
    private Integer auctionParamId;

    private String description;

}

@Entity
public class AuctionParamValue {

    @EmbeddedId
    private AuctionParamValuePK pk;

    private String value;

}

@Embeddable
public class AuctionParamValuePK {

    @ManyToOne
    @JoinColumn(name="auctionId")
    private Auction auction;

    @ManyToOne
    @JoinColumn(name="auctionParamId")
    private AuctionParam auctionParam;

}

Showing an error:-

.Error-Details:-Exception Description:
  Entity [class
  com.eaportal.domain.AuctionParamValue]

  uses [class
  com.eaportal.domain.AuctionParamValuePK]

  as embedded id class

  whose access-type
  has been determined as [FIELD].

  But
  [class
  com.eaportal.domain.AuctionParamValuePK]

  does not define any [FIELD]. It is
  likely that you have not provided

  sufficient metadata in your id class
  [class
  com.eaportal.domain.AuctionParamValuePK].

If you come up with a solution please let me know.

Thanks in Advance
Tushar

Body:
You cannot use an EmbeddedId with relationships.  Use an IdClass.

@Entity
@IdClass(AuctionParamValuePK.class)
public class AuctionParamValue {

    @Id
    @ManyToOne
    @JoinColumn(name="auctionId")
    private Auction auction;

    @Id
    @ManyToOne
    @JoinColumn(name="auctionParamId")
    private AuctionParam auctionParam;

    @Basic
    private String value;

}

public class AuctionParamValuePK {

    private int auction;
    private int auctionParam;

}


问:
Error Call to a member function fetchAll() on boolean
Hello can you help me with these error i get them idk how i just entered the site and i got this errors.

Fatal error: Call to a member function rowCount() on boolean in
  C:\xampp\htdocs\settings.php on line 6

```<code>if (isset($_COOKIE['hash'])) {
    $sql = $db->query("SELECT * FROM `users` WHERE `hash` = " . $db->quote(filter_var($_COOKIE['hash'], FILTER_SANITIZE_STRING)));
    if ($sql->rowCount() != 0) { //line 6
        $row = $sql->fetch();
        $user = $row;
    }
}
</code>```

Fatal error: Call to a member function fetchAll() on boolean in
  C:\xampp\htdocs\login.php on line 42

```<code>        $hash = md5($steamid . time() . rand(1, 50));
        $sql = $db->query("SELECT * FROM `users` WHERE `steamid` = '" . $steamid . "'");
        $row = $sql->fetchAll(PDO::FETCH_ASSOC); //line 42
        if (count($row) == 0) {

            $name = str_replace("script", "*", $name);
            $name = str_replace("/", "*", $name);
            $name = str_replace("<", "*", $name);
            $name = str_replace(">", "*", $name);
            $name = str_replace("body", "*", $name);
            $name = str_replace("onload", "*", $name);
            $name = str_replace("alert", "*", $name);
            $name = str_replace(")", "*", $name);
            $name = str_replace("(", "*", $name);
            $name = str_replace("'", "*", $name);
</code>```

答:
There's absolutely NO reason to assume your query will always execute successfully. Your sin is to have no error handling, which means lack of checking what query() returned. And by docs it returns:

```<code>PDO::query() returns a PDOStatement object, or FALSE on failure.
</code>```

so, as you get boolean it clearly means it fails on your query.

Body:
Hello can you help me with these error i get them idk how i just entered the site and i got this errors.

Fatal error: Call to a member function rowCount() on boolean in
  C:\xampp\htdocs\settings.php on line 6

if (isset($_COOKIE['hash'])) {
    $sql = $db->query("SELECT * FROM `users` WHERE `hash` = " . $db->quote(filter_var($_COOKIE['hash'], FILTER_SANITIZE_STRING)));
    if ($sql->rowCount() != 0) { //line 6
        $row = $sql->fetch();
        $user = $row;
    }
}

Fatal error: Call to a member function fetchAll() on boolean in
  C:\xampp\htdocs\login.php on line 42

        $hash = md5($steamid . time() . rand(1, 50));
        $sql = $db->query("SELECT * FROM `users` WHERE `steamid` = '" . $steamid . "'");
        $row = $sql->fetchAll(PDO::FETCH_ASSOC); //line 42
        if (count($row) == 0) {

            $name = str_replace("script", "*", $name);
            $name = str_replace("/", "*", $name);
            $name = str_replace("<", "*", $name);
            $name = str_replace(">", "*", $name);
            $name = str_replace("body", "*", $name);
            $name = str_replace("onload", "*", $name);
            $name = str_replace("alert", "*", $name);
            $name = str_replace(")", "*", $name);
            $name = str_replace("(", "*", $name);
            $name = str_replace("'", "*", $name);

Body:
There's absolutely NO reason to assume your query will always execute successfully. Your sin is to have no error handling, which means lack of checking what query() returned. And by docs it returns:

PDO::query() returns a PDOStatement object, or FALSE on failure.

so, as you get boolean it clearly means it fails on your query.


问:
dplyr check values between first and last permanent change
I have data structured like this

```<code>set.seed(2)
require(tidyverse)

data <- data.frame("TIME" = c(sample(seq(1:20), 20, replace = F), seq(21:30)),
                   "ID" = c(rep("A", 10), rep("B", 10), rep("C", 10)),
                   "LOC" = c(sample(c("X", "Y"), 20, replace = T), c("X", rep("Y", 9))))
</code>```

and I'm trying to use dplyr to create a variable to indicate whether or not a given ID has a change in time that is permanent (PERMANENT =1) or not (PERMANENT=0). I can't use first() or last() because that ignores the in between values. If for instance they go from X to Y and back to X again like in the case of A and B, the indicator should be 0 for every instance of A and B in the data. However C starts at X and stays at Y in all other instances.

I tried to use indexing in a mutate function, but something isn't working.

```<code>data %>%
  arrange(ID, TIME) %>%
  group_by(ID)%>%
  mutate(LOC = as.character(LOC),
         PERMANENT = ifelse(last(LOC) != "X" & any(LOC[2:length(ID) -1]) != "X"), 1, 0)
</code>```

Like I said the output should indicate C moved permanently, while A and B bounced around in the data set.

the expected output is what happens if you run the following code:

```<code>data$PERMANENT<-ifelse(data$ID%in%c("A","B"),0,1)
</code>```

答:
Here's a go at it with dpylr.  I am assuming an ID is permanent if it hasn't changed since it's second observed time period.

```<code>  set.seed(2)
  data<-data.frame("TIME" = c(sample(seq(1:20),20,replace = F),seq(21:30)),"ID" =c(rep("A",10),rep("B",10),rep("C",10)),"LOC" = c(sample(c("X","Y"),20,replace = T),c("X",rep("Y",9))) )

     data %>% arrange(ID, TIME) %>%
       group_by(ID) %>%
       mutate(timeObs = row_number(), SecondLoc = LOC[timeObs == 2], Change = LOC != SecondLoc) %>%
       filter(timeObs > 1) %>%
       summarize(Permanent = sum(Change) == 0 ) %>%
       right_join(data, by = 'ID')
</code>```

Body:
I have data structured like this

set.seed(2)
require(tidyverse)

data <- data.frame("TIME" = c(sample(seq(1:20), 20, replace = F), seq(21:30)),
                   "ID" = c(rep("A", 10), rep("B", 10), rep("C", 10)),
                   "LOC" = c(sample(c("X", "Y"), 20, replace = T), c("X", rep("Y", 9))))

and I'm trying to use dplyr to create a variable to indicate whether or not a given ID has a change in time that is permanent (PERMANENT =1) or not (PERMANENT=0). I can't use first() or last() because that ignores the in between values. If for instance they go from X to Y and back to X again like in the case of A and B, the indicator should be 0 for every instance of A and B in the data. However C starts at X and stays at Y in all other instances.

I tried to use indexing in a mutate function, but something isn't working.

data %>%
  arrange(ID, TIME) %>%
  group_by(ID)%>%
  mutate(LOC = as.character(LOC),
         PERMANENT = ifelse(last(LOC) != "X" & any(LOC[2:length(ID) -1]) != "X"), 1, 0)

Like I said the output should indicate C moved permanently, while A and B bounced around in the data set.

the expected output is what happens if you run the following code:

data$PERMANENT<-ifelse(data$ID%in%c("A","B"),0,1)

Body:
Here's a go at it with dpylr.  I am assuming an ID is permanent if it hasn't changed since it's second observed time period.

  set.seed(2)
  data<-data.frame("TIME" = c(sample(seq(1:20),20,replace = F),seq(21:30)),"ID" =c(rep("A",10),rep("B",10),rep("C",10)),"LOC" = c(sample(c("X","Y"),20,replace = T),c("X",rep("Y",9))) )

     data %>% arrange(ID, TIME) %>%
       group_by(ID) %>%
       mutate(timeObs = row_number(), SecondLoc = LOC[timeObs == 2], Change = LOC != SecondLoc) %>%
       filter(timeObs > 1) %>%
       summarize(Permanent = sum(Change) == 0 ) %>%
       right_join(data, by = 'ID')


问:
Android how to install apk stored in internal storage
I've successfully downloaded my apk file to internal storage.

However when running it I get an "No activity found to handle intent" error.

Here is my code to run the apk file.

```<code>// Old version
if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.N)
{
File apkFile = new File(this.pathToFile);
     if(apkFile.exists())
     {
          Uri apkURI = Uri.fromFile(apkFile);
          Intent intent = new Intent(Intent.ACTION_VIEW);
          intent.setData(apkURI);
          intent.setType("application/vnd.android.package-archive");
          intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, false);
          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          context.startActivity(intent);
    }
}
</code>```

答:
The apk cannot be installed using a content scheme.

You have to offer Android a file path to the apk file.

So do away with the FileProvider.

Further you should download to getExternalStorageDirectory() or getFilesDir() instead.

Body:
I've successfully downloaded my apk file to internal storage.

However when running it I get an "No activity found to handle intent" error.

Here is my code to run the apk file.

// Old version
if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.N)
{
File apkFile = new File(this.pathToFile);
     if(apkFile.exists())
     {
          Uri apkURI = Uri.fromFile(apkFile);
          Intent intent = new Intent(Intent.ACTION_VIEW);
          intent.setData(apkURI);
          intent.setType("application/vnd.android.package-archive");
          intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, false);
          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          context.startActivity(intent);
    }
}


问:
Testing the availability of std::byte
I'd like to use C++17's std::byte type if it's available, and fall back to using unsigned char if not, i.e. something along the lines of

```<code>#include <cstddef>

namespace my {
#if SOMETHING
using byte = std::byte;
#else
using byte = unsigned char;
#endif
}
</code>```

Unfortunately it seems that std::byte didn't come come with the usual feature test macro, so it's not obvious what SOMETHING above should be. (AFAIK the value of __cplusplus for '17 hasn't been set yet, so I can't test for that either.)

So, does anybody know of a way to detect whether std::byte is available on the big three compilers?

答:
For C++17, the value of __cplusplus is 201703L. But that's not super useful.

Instead, you should look at SD-6. This document contains all the feature test macros for all features adopted into C++, and the vendors all agree to follow them. It's possible that an implementation provides a feature but not the macro (e.g. gcc 7.2 supports std::byte but does not provide the macro) and more obviously that an implementation provides a feature and a macro but the feature is buggy, but you should rely on the macro. That's what it's there for.

Note that using unsigned char gives you almost the exact same behavior as std::byte - the only difference being that unsigned char supports extra arithmetic operations. So having an inexact check for std::byte support is okay - as long as you test on some compiler that supports std::byte to verify that you're not doing anything untoward, you're fine.

Title: Testing the availability of std::byte

Body:
I'd like to use C++17's std::byte type if it's available, and fall back to using unsigned char if not, i.e. something along the lines of

#include <cstddef>

namespace my {
#if SOMETHING
using byte = std::byte;
#else
using byte = unsigned char;
#endif
}

Unfortunately it seems that std::byte didn't come come with the usual feature test macro, so it's not obvious what SOMETHING above should be. (AFAIK the value of __cplusplus for '17 hasn't been set yet, so I can't test for that either.)

So, does anybody know of a way to detect whether std::byte is available on the big three compilers?

ContentLicense: CC BY-SA 4.0


问:
Remove default nonexistent footer links
I have a problem with my MediaWiki installation on a local network. I'm using MediaWiki in German. There are several footer links in my wiki, that throw a 404 error. For example in the footer there's a link Impressum (in English: Disclaimer). It points to *NameOfMyWiki*:Impressum which does not exist.

When I go to MediaWiki:Disclaimers, then a Disclaimer shows up, it's the page that should be behind *wgSitename*:Impressum. I don't think it's intended that I have to point the disclaimer link to MediaWiki:Disclaimers.

Another behaviour that probably is based on the same problem is, that a user gets a 404 on his own user page, when the user page is still empty/not already created (clicking on the link on the top right next to settings). When another user edits the user page of the first user, the first user then can access and edit it, too. But not when it's still empty/not defined.

How can I fix that?

答:
The link mentioned by Ilmari Karonen above:

Alternatively, since MediaWiki 1.17, you can also modify the footer by
  defining a hook in your LocalSettings.php.

...shows how to add links to the built-in list of footer links.  What it does NOT show is how to remove the existing built-in footer links, which is what the original question was.

Turns out it is a simple addition to the referenced hook solution.  You just need to discard the existing footer links in the template array.

Most folks will not only want to remove the built-in footer links but also add their own.  In the spirit of StackOverflow, here is a complete example solution that does both (this is from an existing Wiki...)

This works in mediawiki-1.29.2 but it will probably work in many older versions too.  Put this code in your LocalSettings.php file (I put it at the bottom) to remove the existing footer links and add your own:

```<code># Remove all existing footer links and add my own
$wgHooks['SkinTemplateOutputPageBeforeExec'][] = function( $sk, &$tpl ) {

        # IMPORTANT:  this is the secret sauce - remove all existing footer links
        $tpl->data['footerlinks']['places'] = array();

        # To add new footer links to local wiki pages:
        #
        # 1) You MUST create your new pages in your (Main) namespace first, for example:
        #
        #       http://<your-site>/wiki/index.php/About_Us
        #       http://<your-site>/wiki/index.php/Contact_Us
        #       http://<your-site>/wiki/index.php/Disclaimer
        #       http://<your-site>/wiki/index.php/Download
        #       http://<your-site>/wiki/index.php/Privacy_Policy
        #
        # 2) You MUST then create each of these pages in your MediaWiki namespace:
        #
        #       http://<your-site>/wiki/index.php/MediaWiki:Aboutpage
        #               - Insert 1 line, with "About Us" (no quotes)
        #       http://<your-site>/wiki/index.php/MediaWiki:Contactpage
        #               - Insert 1 line, with "Contact Us" (no quotes)
        #       http://<your-site>/wiki/index.php/MediaWiki:Disclaimerpage
        #               - Insert 1 line, with "Disclaimer" (no quotes)
        #       http://<your-site>/wiki/index.php/MediaWiki:Downloadpage
        #               - Insert 1 line, with "Download" (no quotes)
        #       http://<your-site>/wiki/index.php/MediaWiki:Privacypage
        #               - Insert 1 line, with "Privacy Policy" (no quotes)
        #
        # 3) Add new footer links like this:

        $tpl->set( 'aboutpage', $sk->footerLink( 'aboutpage', 'aboutpage' ) );
        $tpl->data['footerlinks']['places'][] = 'aboutpage';
        $tpl->set( 'contactpage', $sk->footerLink( 'contactpage', 'contactpage' ) );
        $tpl->data['footerlinks']['places'][] = 'contactpage';
        $tpl->set( 'disclaimerpage', $sk->footerLink( 'disclaimerpage', 'disclaimerpage' ) );
        $tpl->data['footerlinks']['places'][] = 'disclaimerpage';
        $tpl->set( 'downloadpage', $sk->footerLink( 'downloadpage', 'downloadpage' ) );
        $tpl->data['footerlinks']['places'][] = 'downloadpage';
        $tpl->set( 'privacypage', $sk->footerLink( 'privacypage', 'privacypage' ) );
        $tpl->data['footerlinks']['places'][] = 'privacypage';

        return true;
};
</code>```

IMPORTANT: Don't forget to follow the instructions and create your own pages and the corresponding MediaWiki redirects, or your links may not show or they may be broken.

Title: Remove default nonexistent footer links

Body:
The link mentioned by Ilmari Karonen above:

Alternatively, since MediaWiki 1.17, you can also modify the footer by
  defining a hook in your LocalSettings.php.

...shows how to add links to the built-in list of footer links.  What it does NOT show is how to remove the existing built-in footer links, which is what the original question was.

Turns out it is a simple addition to the referenced hook solution.  You just need to discard the existing footer links in the template array.

Most folks will not only want to remove the built-in footer links but also add their own.  In the spirit of StackOverflow, here is a complete example solution that does both (this is from an existing Wiki...)

This works in mediawiki-1.29.2 but it will probably work in many older versions too.  Put this code in your LocalSettings.php file (I put it at the bottom) to remove the existing footer links and add your own:

# Remove all existing footer links and add my own
$wgHooks['SkinTemplateOutputPageBeforeExec'][] = function( $sk, &$tpl ) {

        # IMPORTANT:  this is the secret sauce - remove all existing footer links
        $tpl->data['footerlinks']['places'] = array();

        # To add new footer links to local wiki pages:
        #
        # 1) You MUST create your new pages in your (Main) namespace first, for example:
        #
        #       http://<your-site>/wiki/index.php/About_Us
        #       http://<your-site>/wiki/index.php/Contact_Us
        #       http://<your-site>/wiki/index.php/Disclaimer
        #       http://<your-site>/wiki/index.php/Download
        #       http://<your-site>/wiki/index.php/Privacy_Policy
        #
        # 2) You MUST then create each of these pages in your MediaWiki namespace:
        #
        #       http://<your-site>/wiki/index.php/MediaWiki:Aboutpage
        #               - Insert 1 line, with "About Us" (no quotes)
        #       http://<your-site>/wiki/index.php/MediaWiki:Contactpage
        #               - Insert 1 line, with "Contact Us" (no quotes)
        #       http://<your-site>/wiki/index.php/MediaWiki:Disclaimerpage
        #               - Insert 1 line, with "Disclaimer" (no quotes)
        #       http://<your-site>/wiki/index.php/MediaWiki:Downloadpage
        #               - Insert 1 line, with "Download" (no quotes)
        #       http://<your-site>/wiki/index.php/MediaWiki:Privacypage
        #               - Insert 1 line, with "Privacy Policy" (no quotes)
        #
        # 3) Add new footer links like this:

        $tpl->set( 'aboutpage', $sk->footerLink( 'aboutpage', 'aboutpage' ) );
        $tpl->data['footerlinks']['places'][] = 'aboutpage';
        $tpl->set( 'contactpage', $sk->footerLink( 'contactpage', 'contactpage' ) );
        $tpl->data['footerlinks']['places'][] = 'contactpage';
        $tpl->set( 'disclaimerpage', $sk->footerLink( 'disclaimerpage', 'disclaimerpage' ) );
        $tpl->data['footerlinks']['places'][] = 'disclaimerpage';
        $tpl->set( 'downloadpage', $sk->footerLink( 'downloadpage', 'downloadpage' ) );
        $tpl->data['footerlinks']['places'][] = 'downloadpage';
        $tpl->set( 'privacypage', $sk->footerLink( 'privacypage', 'privacypage' ) );
        $tpl->data['footerlinks']['places'][] = 'privacypage';

        return true;
};

IMPORTANT: Don't forget to follow the instructions and create your own pages and the corresponding MediaWiki redirects, or your links may not show or they may be broken.


问:
difference between java and azure stream analytics
Sorry for the question but is there any difference between Java Streams and Microsoft Azure Stream Analytics?

I do see what are the benefits that azure stream analytics bring about but is there any difference? For example, Something that Azure Stream Analytics can do but not Java Streams.

I do also understand that Azure Stream Analytics can be used with Java..

答:
You are comparing apples to oranges. Java Streams is used for processing data in process much like .Net Linq. See this blogpost for a comparison.

Azure Stream Analytics is a cloud service that lets you analyse a vast amount of incoming real-time data (like thousands of events from different IoT sensors) and apply transformations to that data while outputting it to a destination like a file or a reporting tool and much more.

You see any similarities? No? Well that's because you cannot compare them like that.

About Azure Stream Analytics being able to leverage Java: I don't know. It uses a language on its own to write a stream processing job. See the docs.

The apache counterpart that supports Java would be Apache Storm or Spark (I am not that familiar with those products), see also Azure Storm vs Azure Stream Analytics


问:
ASP.NET Error About "Inherits" attribute, even though it's correct?
Having a really strange issue at the moment with an ASP.NET site I'm currently building.

At the moment, I'm writting the HTML and CSS for a page called Dashboard.aspx. But when I go to view the page in a browser, half the time it throws up this error:

ASPNET: Make sure that the class
  defined in this code file matches the
  'inherits' attribute, and that it
  extends the correct base class (e.g.
  Page or UserControl).

I've checked the Inherits attribute on the .aspx page, and it matches the Partial Class held in the VB code of Dashboard.aspx.vb file.

When I refresh, it will always come up with this error. Then after a minute or two, it will load fine with no problems. I had a quick look on Google and I couldn't find an answer to this issue.

I have also changed the name of the partial class (and the content placeholder on the .aspx file, thinking that may have caused a conflict) and nothing I do seems to fix it.

Could anyone shed any light on what's going on?

Thanks,
Michael

答:
Make sure the inherits property in the
  aspx page matches the class definition
  in the .cs file. […] the inherits
  property and the class must have the
  same namespace and classname

(From: Inherit problem in asp.net)

Additionally, make sure no other pages (accidentally) try to inherit a class from the same code behind file.


问:
Matching Outlook Calendar Dates to CSV Dates and Appending Match to List
Disclaimer: I'm relatively new to Python. I am attempting to write a script that will go through a CSV, check if certain columns match Outlook calendar items (by subject, organizer, and date match), and then have the script note that there was a successful match in a new column (I stole heavily from this question). Below is my whole script.

```<code>import win32com.client, datetime, re, os, csv, shutil

# set cwd, create copy of original CSV, and access outlook API
os.chdir('C:\\')
shutil.copy('masterCheck.csv', 'inspectCheck.csv')
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

inspectors = {'ASMITH': 'Smith, Aaron', 'JDOE': 'Doe, Jane', 'KZEEBOP': 'Zeebop, Kim'}

#access csv and put it into a list
with open('inspectCheck.csv', 'r', newline = '', encoding='utf-8') as csvAppointments:
    reader = csv.reader(csvAppointments)
    masterList = list(reader)
    del masterList[-1] # delete blank nested list
    del masterList[1] #delete header
    for i in masterList: # switch out names so they can match Outlook descriptors later
        for key, value in inspectors.items():
            if i[3] in key:
                i[3] = value

# create another list for appending later in the script
finalList = []
finalList += masterList

# access the inspectors' calendars
x = 0
try:
    for inspector in inspectors.values():
        recipient = outlook.createRecipient(inspector)
        resolved = recipient.Resolve()
        sharedCalendar = outlook.GetSharedDefaultFolder(recipient, 9)
        codeAppointments = sharedCalendar.Items

        #restrict to items in the next year
        begin = datetime.date.today()
        end = begin + datetime.timedelta(days = 365);
        restriction = "[Start] >= '" + begin.strftime("%m/%d/%Y") + "' AND [End] <= '" +end.strftime("%m/%d/%Y") + "'"
        restrictedItems = codeAppointments.Restrict(restriction)

        # loop through inspectors' appointments and match
        for appointmentItem in restrictedItems:
            for i in masterList:
                addressSearch = i[1]
                if re.search(r'%s' % addressSearch, appointmentItem.Subject, re.IGNORECASE)\
                   and i[3] in appointmentItem.Organizer\
                   and i[4] in appointmentItem.Start:
                    finalList[x].append(appointmentItem.Subject)
                    x += 1
except IndexError:
    pass

# update spreadsheet
with open('inspectCheckFinal.csv', 'w', newline = '') as csvAppointments:
    appointmentsWriter = csv.writer(csvAppointments)
    appointmentsWriter.writerows(finalList)
</code>```

I have had success matching columns from my CSV to Outlook items. For example, I can get this to match.

```<code>if re.search(r'%s' % addressSearch, appointmentItem.Subject, re.IGNORECASE)
</code>```

However, as soon as I try to match it to my date column (i[4]), it throws the error: TypeError: argument of type 'pywintypes.datetime' is not iterable. The dates in my CSV look like 2/11/2018 but the dates (when printed) in Outlook look like 2017-11-16 11:00:00+00:00. I'm at a loss on how to match these two.

Moreover, I am having trouble marking the CSV with successful matches. While the script will append a value to the end of each nested list (and then write it to a CSV), it will not append the value to the matched row of the CSV. For example, my output looks like:

```<code>Inspector     |Address     |Date     |Success?(print Address)
ASMITH        |212 Clark St|11/21/18 |Yes. 33 Blart Ave
ASMITH        |33 Blart Ave|11/20/18 |Yes. 212 Clark St
</code>```

My guess is that my script finds a match in Outlook, and then appends that value to the end of a nested list. What I would like it to do is to match it in the row/nested list where it was actually matched. Apologies for the long post and thank you to those who read it.

答:
Nevermind, I solved the TypeError by converting

```<code>and i[4] in appointmentItem.Start:
# to
and i[4] in str(appointmentItem.Start):
</code>```

Moreover, I reformatted my CSV beforehand so it will now match Outlook's format. As for my matches being appended in the wrong rows, I think I will solve that by appending matches to a separate CSV/dataframe, and then joining that dataframe to the original CSV/dataframe.

Body:
Disclaimer: I'm relatively new to Python. I am attempting to write a script that will go through a CSV, check if certain columns match Outlook calendar items (by subject, organizer, and date match), and then have the script note that there was a successful match in a new column (I stole heavily from this question). Below is my whole script.

import win32com.client, datetime, re, os, csv, shutil

# set cwd, create copy of original CSV, and access outlook API
os.chdir('C:\\')
shutil.copy('masterCheck.csv', 'inspectCheck.csv')
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

inspectors = {'ASMITH': 'Smith, Aaron', 'JDOE': 'Doe, Jane', 'KZEEBOP': 'Zeebop, Kim'}

#access csv and put it into a list
with open('inspectCheck.csv', 'r', newline = '', encoding='utf-8') as csvAppointments:
    reader = csv.reader(csvAppointments)
    masterList = list(reader)
    del masterList[-1] # delete blank nested list
    del masterList[1] #delete header
    for i in masterList: # switch out names so they can match Outlook descriptors later
        for key, value in inspectors.items():
            if i[3] in key:
                i[3] = value

# create another list for appending later in the script
finalList = []
finalList += masterList

# access the inspectors' calendars
x = 0
try:
    for inspector in inspectors.values():
        recipient = outlook.createRecipient(inspector)
        resolved = recipient.Resolve()
        sharedCalendar = outlook.GetSharedDefaultFolder(recipient, 9)
        codeAppointments = sharedCalendar.Items

        #restrict to items in the next year
        begin = datetime.date.today()
        end = begin + datetime.timedelta(days = 365);
        restriction = "[Start] >= '" + begin.strftime("%m/%d/%Y") + "' AND [End] <= '" +end.strftime("%m/%d/%Y") + "'"
        restrictedItems = codeAppointments.Restrict(restriction)

        # loop through inspectors' appointments and match
        for appointmentItem in restrictedItems:
            for i in masterList:
                addressSearch = i[1]
                if re.search(r'%s' % addressSearch, appointmentItem.Subject, re.IGNORECASE)\
                   and i[3] in appointmentItem.Organizer\
                   and i[4] in appointmentItem.Start:
                    finalList[x].append(appointmentItem.Subject)
                    x += 1
except IndexError:
    pass

# update spreadsheet
with open('inspectCheckFinal.csv', 'w', newline = '') as csvAppointments:
    appointmentsWriter = csv.writer(csvAppointments)
    appointmentsWriter.writerows(finalList)

I have had success matching columns from my CSV to Outlook items. For example, I can get this to match.

if re.search(r'%s' % addressSearch, appointmentItem.Subject, re.IGNORECASE)

However, as soon as I try to match it to my date column (i[4]), it throws the error: TypeError: argument of type 'pywintypes.datetime' is not iterable. The dates in my CSV look like 2/11/2018 but the dates (when printed) in Outlook look like 2017-11-16 11:00:00+00:00. I'm at a loss on how to match these two.

Moreover, I am having trouble marking the CSV with successful matches. While the script will append a value to the end of each nested list (and then write it to a CSV), it will not append the value to the matched row of the CSV. For example, my output looks like:

Inspector     |Address     |Date     |Success?(print Address)
ASMITH        |212 Clark St|11/21/18 |Yes. 33 Blart Ave
ASMITH        |33 Blart Ave|11/20/18 |Yes. 212 Clark St

My guess is that my script finds a match in Outlook, and then appends that value to the end of a nested list. What I would like it to do is to match it in the row/nested list where it was actually matched. Apologies for the long post and thank you to those who read it.

Body:
Nevermind, I solved the TypeError by converting

and i[4] in appointmentItem.Start:
# to
and i[4] in str(appointmentItem.Start):

Moreover, I reformatted my CSV beforehand so it will now match Outlook's format. As for my matches being appended in the wrong rows, I think I will solve that by appending matches to a separate CSV/dataframe, and then joining that dataframe to the original CSV/dataframe.


问:
Fatal Error :1:1: Content is not allowed in prolog. org.xml.sax.SAXParseException
I am trying to read an XML file in Java and then compare it against its XML Schema but I can't get past this error :

[Fatal Error] :1:1: Content is not allowed in prolog.
      org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.

This is the start of the file reading

```<code>try {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(new InputSource(new StringReader("myfile.xml"))); // ERROR OCCURS HERE
</code>```

I scanned my XML through HEX Editors but I did not find any weird characters inside, so I dont know where the problem is

myfile.xml

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>

<Schedule xmlns ="schedule"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="schedule.xsd">
    <Lesson>
        <Title>Artificial Intelligence</Title>
        <Lecture Classroom="BA">
            <Day>Wednesday</Day>
            <Time>09-11</Time>
        </Lecture>
        <Professor>Hatzilygeroudis</Professor>
    </Lesson>
    <Lesson>
        <Title>Constraint Satisfaction Problems</Title>
        <Lecture Classroom="B3">
            <Day>Monday</Day>
            <Time>19-21</Time>
        </Lecture>
    </Lesson>
    <Lesson>
        <Title>Knowledge Representation in Web</Title>
        <Lecture Classroom="P200">
            <Day>Friday</Day>
            <Time>15-17</Time>
        </Lecture>
        <Professor>Hatzilygeroudis</Professor>
    </Lesson>
    <Lesson>
        <Title>Artificial Intelligence</Title>
        <Lecture>
            <Day>Monday</Day>
            <Time>19-21</Time>
        </Lecture>
    </Lesson>
    <Lesson>
        <Title>AI Programming</Title>
        <Lecture Classroom="B3">
            <Day>Monday</Day>
            <Time>11-13</Time>
        </Lecture>
    </Lesson>
    <Lesson>
        <Title>Introduction to Procedural Programming</Title>
        <Lecture Classroom="P200">
            <Day>Wednesday</Day>
            <Time>15-17</Time>
        </Lecture>
        <Professor>Papadopoulos</Professor>
    </Lesson>
</Schedule>
</code>```

答:
StringReader("myfile.xml") takes a string argument that must be XML, not a filename.  The parser is reading the string literal, myfile.xml, (not the file contents of myfile.xml) and failing immediately because an XML document may not begin with an m character.

Change

```<code>Document doc = dBuilder.parse(new InputSource(new StringReader("myfile.xml")));
</code>```

to

```<code>Document doc = dBuilder.parse(new InputSource("myfile.xml"));
</code>```

Body:
I am trying to read an XML file in Java and then compare it against its XML Schema but I can't get past this error :

[Fatal Error] :1:1: Content is not allowed in prolog.
      org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.

This is the start of the file reading

try {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(new InputSource(new StringReader("myfile.xml"))); // ERROR OCCURS HERE

I scanned my XML through HEX Editors but I did not find any weird characters inside, so I dont know where the problem is

myfile.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<Schedule xmlns ="schedule"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="schedule.xsd">
    <Lesson>
        <Title>Artificial Intelligence</Title>
        <Lecture Classroom="BA">
            <Day>Wednesday</Day>
            <Time>09-11</Time>
        </Lecture>
        <Professor>Hatzilygeroudis</Professor>
    </Lesson>
    <Lesson>
        <Title>Constraint Satisfaction Problems</Title>
        <Lecture Classroom="B3">
            <Day>Monday</Day>
            <Time>19-21</Time>
        </Lecture>
    </Lesson>
    <Lesson>
        <Title>Knowledge Representation in Web</Title>
        <Lecture Classroom="P200">
            <Day>Friday</Day>
            <Time>15-17</Time>
        </Lecture>
        <Professor>Hatzilygeroudis</Professor>
    </Lesson>
    <Lesson>
        <Title>Artificial Intelligence</Title>
        <Lecture>
            <Day>Monday</Day>
            <Time>19-21</Time>
        </Lecture>
    </Lesson>
    <Lesson>
        <Title>AI Programming</Title>
        <Lecture Classroom="B3">
            <Day>Monday</Day>
            <Time>11-13</Time>
        </Lecture>
    </Lesson>
    <Lesson>
        <Title>Introduction to Procedural Programming</Title>
        <Lecture Classroom="P200">
            <Day>Wednesday</Day>
            <Time>15-17</Time>
        </Lecture>
        <Professor>Papadopoulos</Professor>
    </Lesson>
</Schedule>

Body:
StringReader("myfile.xml") takes a string argument that must be XML, not a filename.  The parser is reading the string literal, myfile.xml, (not the file contents of myfile.xml) and failing immediately because an XML document may not begin with an m character.

Change

Document doc = dBuilder.parse(new InputSource(new StringReader("myfile.xml")));

to

Document doc = dBuilder.parse(new InputSource("myfile.xml"));


问:
Azure / U-SQL - Regex substitution
I have some data containing spaces () and hyphens (-) that I'd like to convert to underscore characters (_).  In other languages (ie R) I can write something like this:

```<code>var1 <- gsub(var1, "s+|\\-", "_")
</code>```

which will look for multiple characters and convert them all to some other character.

Is there a way to do this in U-SQL?

EDIT:

I tried this and it ran without error but did not change the data:

```<code>@t2 = SELECT var1,
           var2,
           var3.Replace("s+|\\'|\\-","_") AS var3
    FROM @t1;
</code>```

答:
```<code>@someData =
SELECT * FROM
    ( VALUES
    ("tic tac-toe")
    ) AS T(col1);

DECLARE  @pattern string = "\\s|-";

@result =
SELECT  col1 AS original,
        Regex.Replace(col1,  "\\s",    "_") AS regex_replaceSpace,
        Regex.Replace(col1,  "-",    "_") AS regex_replaceHypen,
        Regex.Replace(col1,  "\\055",    "_") AS regex_replaceHypenDecimal,
        Regex.Replace(col1,  "\\s|-",    "_") AS regex_replaceBoth,
        Regex.Replace(col1,  @"\s|-",    "_") AS regex_replaceBoth_verbatim,
        Regex.Replace(col1,  @pattern,    "_") AS regex_replaceBoth_pattern,

        col1.Replace(" ", "_") AS string_replaceSpace,
        col1.Replace("-", "_") AS string_replaceHypen,
        col1.Replace("-", "_").Replace(" ", "_") AS string_replaceBoth
FROM @someData;

OUTPUT @result
TO "/Replace.csv"
USING Outputters.Csv(outputHeader: true);
</code>```

Title: Azure / U-SQL - Regex substitution

Body:
I have some data containing spaces () and hyphens (-) that I'd like to convert to underscore characters (_).  In other languages (ie R) I can write something like this:

var1 <- gsub(var1, "s+|\\-", "_")

which will look for multiple characters and convert them all to some other character.

Is there a way to do this in U-SQL?

EDIT:

I tried this and it ran without error but did not change the data:

@t2 = SELECT var1,
           var2,
           var3.Replace("s+|\\'|\\-","_") AS var3
    FROM @t1;


问:
I want to resize certain images on my site ONLY on mobile
On the website I have I can only input code into the body and the footer.

The website is bothellhomes.com. The homepage shows three round images. On a mobile device, I want to resize the images so they show horizontally. Right now, since the images are so large, they go vertically.

Body code:

```<code><section class="three-widgets">
<ul class="small-block-grid-1 medium-block-grid-3 text-center">
<li><a title="Advanced Search" href="/search/advanced_search/"><img src="https://u.realgeeks.media/lookinwa/advancedsearch.png" alt="Advanced Search" width="300" height="300" /></a></li>
<li><a title="Interactive Map Search" href="/map_search/results/9k/1/#/?city=Kenmore&city=Bothell&city=Kirkland&city=Woodinville&city=Bellevue&city=Lynnwood&city=Mill%20Creek&city=Redmond&page=1&list_price_max=800000&per_page=100&type=res&type=con&list_price_min=250000"><img src="https://u.realgeeks.media/lookinwa/mapsearch.png" alt="Interactive Map Search" width="300" height="300" /></a></li>
<li><a title="What's My Home Worth?" href="/cma/property-valuation/"><img src="https://u.realgeeks.media/lookinwa/homevaluation.png" alt="Home Value" width="300" height="300" /></a></li>
</ul>
</section>
</code>```

Footer code:

```<code><script>// <![CDATA[
document.write("<style>.three-widgets {margin-top: -60px;}.three-widgets img {background: #fff;border: 1px solid #ddd;border-radius: 100%;padding: 5px;}.three-widgets p {color: #000}.three-widgets li img {     opacity: .9;-webkit-transition: all 0.3s ease-out;     -moz-transition: all 0.3s ease-out;     -o-transition: all 0.3s ease-out;transition: all 0.3s ease-out;}.three-widgets li:hover img {border: 1px solid #444444;opacity: 1; -webkit-transform: scale(1.1);-moz-transform: scale(1.1);-ms-transform: scale(1.1);transform: scale(1.1);}@media (max-width:767px) {.three-widgets {     margin-top: 0}}h1{ line-height:38px!important}</style>");
// ]]></script>
</code>```

答:
You should think mobile first. Apply styles to the images for the mobile version, and then override them using media queries for the desktop viewing.

You will likely want to add an ID or class to target strictly the desired images. In this case I added an id called round-images. Remove the classes "small-block-grid-1" and "medium-block-grid-3".

Body Code:

```<code><section class="three-widgets" id="round-images">
<ul class="text-center">
<li><a title="Advanced Search" href="/search/advanced_search/"><img src="https://u.realgeeks.media/lookinwa/advancedsearch.png" alt="Advanced Search" width="300" height="300" /></a></li>
<li><a title="Interactive Map Search" href="/map_search/results/9k/1/#/?city=Kenmore&city=Bothell&city=Kirkland&city=Woodinville&city=Bellevue&city=Lynnwood&city=Mill%20Creek&city=Redmond&page=1&list_price_max=800000&per_page=100&type=res&type=con&list_price_min=250000"><img src="https://u.realgeeks.media/lookinwa/mapsearch.png" alt="Interactive Map Search" width="300" height="300" /></a></li>
<li><a title="What's My Home Worth?" href="/cma/property-valuation/"><img src="https://u.realgeeks.media/lookinwa/homevaluation.png" alt="Home Value" width="300" height="300" /></a></li>
</ul>
</section>
</code>```

Next, style the images as you want for mobile using CSS. Since you don't have access to the header, you can get around that limitation through inline CSS or as I show below with embedded CSS. Lastly, add a media query to reset the styles how you had them before. Here is the idea:

```<code><style>
/* the following controls image size */
#round-images img{
    max-width:100px;
    max-height:100px;
};
@media (min-width: 768px) {
    #round-images img{
        max-width:300px;
        max-height:300px;
    };
}
/* the following will remove the vertical stacking */
#round-images ul li{
    float:left;
    width:33%;
};
</style>
</code>```

I got this working without your classes "small-block-grid-1 medium-block-grid-3".

Body:
On the website I have I can only input code into the body and the footer.

The website is bothellhomes.com. The homepage shows three round images. On a mobile device, I want to resize the images so they show horizontally. Right now, since the images are so large, they go vertically.

Body code:

Footer code:

Body:
You should think mobile first. Apply styles to the images for the mobile version, and then override them using media queries for the desktop viewing.

You will likely want to add an ID or class to target strictly the desired images. In this case I added an id called round-images. Remove the classes "small-block-grid-1" and "medium-block-grid-3".

Body Code:

<section class="three-widgets" id="round-images">
<ul class="text-center">
<li><a title="Advanced Search" href="/search/advanced_search/"><img src="https://u.realgeeks.media/lookinwa/advancedsearch.png" alt="Advanced Search" width="300" height="300" /></a></li>
<li><a title="Interactive Map Search" href="/map_search/results/9k/1/#/?city=Kenmore&city=Bothell&city=Kirkland&city=Woodinville&city=Bellevue&city=Lynnwood&city=Mill%20Creek&city=Redmond&page=1&list_price_max=800000&per_page=100&type=res&type=con&list_price_min=250000"><img src="https://u.realgeeks.media/lookinwa/mapsearch.png" alt="Interactive Map Search" width="300" height="300" /></a></li>
<li><a title="What's My Home Worth?" href="/cma/property-valuation/"><img src="https://u.realgeeks.media/lookinwa/homevaluation.png" alt="Home Value" width="300" height="300" /></a></li>
</ul>
</section>

Next, style the images as you want for mobile using CSS. Since you don't have access to the header, you can get around that limitation through inline CSS or as I show below with embedded CSS. Lastly, add a media query to reset the styles how you had them before. Here is the idea:

<style>
/* the following controls image size */
#round-images img{
    max-width:100px;
    max-height:100px;
};
@media (min-width: 768px) {
    #round-images img{
        max-width:300px;
        max-height:300px;
    };
}
/* the following will remove the vertical stacking */
#round-images ul li{
    float:left;
    width:33%;
};
</style>

I got this working without your classes "small-block-grid-1 medium-block-grid-3".


问:
Swift - Mapping of Nested Objects (Objectmapper)
I am developing an application with Swift 4. Where I make a call to the APIRest with Alamofire and I want to map the JSON response with Objectmapper. Well, the JSON that calls me back is the following:

The code to the APIRest is:

```<code>    func retrievePostListData() {
        Alamofire
            .request("http://www.speedrun.com/api/v1/games", method: .get)
            .validate()
            .responseArray(completionHandler: { (response:
            DataResponse<[PostModelSpeedRunModel]>) in
                switch response.result {
                case .success(let posts):

                 self.remoteRequestHandler?.onPostsRetrievedData(posts)
                    case .failure( _):
                        self.remoteRequestHandler?.onError()
                }
            })
    }
</code>```

The problem is that I do not know how to access each of the values (func mapping). Because there are some nested values. In addition to that some of the annunciations are objects and others are array. My erroneous code is the following:

```<code>import Foundation
import ObjectMapper

struct PostModelSpeedRunModel {
    var id              = ""
    var international   = ""
    var abbreviation    = ""
    var links           = [Links]??? // I need to get "rel" and "uri" of "runs"
    var uri             = ""
}

extension PostModelSpeedRunModel: Mappable {

    init?(map: Map) {
    }

    mutating func mapping(map: Map) {
        id              <- map["data.id"]
        international   <- map["data.international"]
        abbreviation    <- map["data.abbreviation"]
        link              <- map["data.Links"]
        uri             <- map["data.logo"]
    }

}
</code>```

Can you help me do / understand doing the function mapping? Thanks

答:
I'm assuming you are getting no values at all, because I tried your code and got nothing. If you only need the contents of the data array from the json and, as you have it now, ObjectMapper is expecting a json with just an array of PostModelSpeedRunModels. Therefore, you need to add a keyPath to tell AlamofireObjectMapper it's starting point:

```<code>    Alamofire.request("http://www.speedrun.com/api/v1/games", method: .get)
        .responseArray(keyPath: "data") { (response: DataResponse<[PostModelSpeedRunModel]>) in
            ...
    }
</code>```

If you also need the info from the pagination node, then you'll need to create a new object that has a data and pagination properties, and change responseArray(keyPath: ...) to simply responseObject using the new root object in DataResponse.

Then I believe you only want runs's uri, so I recommend just having a String in your model for storing it, instead of an array of Links. Assuming that the array of links is unsorted and may change order in the future (if not you can access directly like map["links.1.uri"] and you are done), all links need to be parsed and then filtered. It can be done as follows:

```<code>struct PostModelSpeedRunModel {
    var id              = ""
    var international   = ""
    var abbreviation    = ""
    var runsLink        = ""
    var uri             = ""
}

extension PostModelSpeedRunModel: Mappable {

    init?(map: Map) {
    }

    mutating func mapping(map: Map) {
        id              <- map["id"]
        international   <- map["international"]
        abbreviation    <- map["abbreviation"]
        uri             <- map["logo"]

        var links: [Link]?
        links <- map["links"]

        if let uri = links?.first(where: {$0.rel == "runs"})?.uri {
            runsLink = uri
        }
    }
}

struct Link {
    var rel = ""
    var uri = ""
}

extension Link: Mappable {
    init?(map: Map) {
    }

    mutating func mapping(map: Map) {
        rel <- map["rel"]
        uri <- map["uri"]
    }
}
</code>```

Body:
I am developing an application with Swift 4. Where I make a call to the APIRest with Alamofire and I want to map the JSON response with Objectmapper. Well, the JSON that calls me back is the following:

The code to the APIRest is:

    func retrievePostListData() {
        Alamofire
            .request("http://www.speedrun.com/api/v1/games", method: .get)
            .validate()
            .responseArray(completionHandler: { (response:
            DataResponse<[PostModelSpeedRunModel]>) in
                switch response.result {
                case .success(let posts):

                 self.remoteRequestHandler?.onPostsRetrievedData(posts)
                    case .failure( _):
                        self.remoteRequestHandler?.onError()
                }
            })
    }

The problem is that I do not know how to access each of the values (func mapping). Because there are some nested values. In addition to that some of the annunciations are objects and others are array. My erroneous code is the following:

import Foundation
import ObjectMapper

struct PostModelSpeedRunModel {
    var id              = ""
    var international   = ""
    var abbreviation    = ""
    var links           = [Links]??? // I need to get "rel" and "uri" of "runs"
    var uri             = ""
}

extension PostModelSpeedRunModel: Mappable {

    init?(map: Map) {
    }

    mutating func mapping(map: Map) {
        id              <- map["data.id"]
        international   <- map["data.international"]
        abbreviation    <- map["data.abbreviation"]
        link              <- map["data.Links"]
        uri             <- map["data.logo"]
    }

}

Can you help me do / understand doing the function mapping? Thanks

Body:
I'm assuming you are getting no values at all, because I tried your code and got nothing. If you only need the contents of the data array from the json and, as you have it now, ObjectMapper is expecting a json with just an array of PostModelSpeedRunModels. Therefore, you need to add a keyPath to tell AlamofireObjectMapper it's starting point:

    Alamofire.request("http://www.speedrun.com/api/v1/games", method: .get)
        .responseArray(keyPath: "data") { (response: DataResponse<[PostModelSpeedRunModel]>) in
            ...
    }

If you also need the info from the pagination node, then you'll need to create a new object that has a data and pagination properties, and change responseArray(keyPath: ...) to simply responseObject using the new root object in DataResponse.

Then I believe you only want runs's uri, so I recommend just having a String in your model for storing it, instead of an array of Links. Assuming that the array of links is unsorted and may change order in the future (if not you can access directly like map["links.1.uri"] and you are done), all links need to be parsed and then filtered. It can be done as follows:

struct PostModelSpeedRunModel {
    var id              = ""
    var international   = ""
    var abbreviation    = ""
    var runsLink        = ""
    var uri             = ""
}

extension PostModelSpeedRunModel: Mappable {

    init?(map: Map) {
    }

    mutating func mapping(map: Map) {
        id              <- map["id"]
        international   <- map["international"]
        abbreviation    <- map["abbreviation"]
        uri             <- map["logo"]

        var links: [Link]?
        links <- map["links"]

        if let uri = links?.first(where: {$0.rel == "runs"})?.uri {
            runsLink = uri
        }
    }
}

struct Link {
    var rel = ""
    var uri = ""
}

extension Link: Mappable {
    init?(map: Map) {
    }

    mutating func mapping(map: Map) {
        rel <- map["rel"]
        uri <- map["uri"]
    }
}


问:
Training using mxnet in ipython console of Spyder not working
I'm running the mnist example of mxnet in Spyder IDE. The training does not progress, just as if the learning rate were 0 (see output below).

If I run the same file on the console using either python or ipython, it works as expected (seeing improvements in the second epoch).

If I run the file using the normal Python console of Spyder, it also works.
But if I run the file using the ipython console, I get the output shown below.

I'm new to Python. Any ideas?

Source code

```<code>#!/usr/bin/env python2
# -*- coding: utf-8 -*-

#%%
import mxnet as mx

#%% load mnist

mnist = mx.test_utils.get_mnist()

#%% define data iterators

batch_size = 100
train_iter = mx.io.NDArrayIter(mnist['train_data'], mnist['train_label'], batch_size, shuffle=True)
val_iter = mx.io.NDArrayIter(mnist['test_data'], mnist['test_label'], batch_size)

#%% create input variable

data = mx.sym.var('data')
# Flatten the data from 4-D shape into 2-D (batch_size, num_channel*width*height)
data = mx.sym.flatten(data=data)

#%% Multilayer Perceptron with softmax

# The first fully-connected layer and the corresponding activation function
fc1  = mx.sym.FullyConnected(data=data, num_hidden=128)
act1 = mx.sym.Activation(data=fc1, act_type="relu")

# The second fully-connected layer and the corresponding activation function
fc2  = mx.sym.FullyConnected(data=act1, num_hidden = 64)
act2 = mx.sym.Activation(data=fc2, act_type="relu")

# MNIST has 10 classes
fc3  = mx.sym.FullyConnected(data=act2, num_hidden=10)
# Softmax with cross entropy loss
mlp  = mx.sym.SoftmaxOutput(data=fc3, name='softmax')

#%% Training
import logging
logging.getLogger().setLevel(logging.DEBUG)  # logging to stdout
# create a trainable module on CPU
mlp_model = mx.mod.Module(symbol=mlp, context=mx.cpu())
mlp_model.fit(train_iter,  # train data
              eval_data=val_iter,  # validation data
              optimizer='sgd',  # use SGD to train
              optimizer_params={'learning_rate':0.1},  # use fixed learning rate
              eval_metric='acc',  # report accuracy during training
              batch_end_callback = mx.callback.Speedometer(batch_size, 100), # output progress for each 100 data batches
              num_epoch=10)  # train for at most 10 dataset passes
</code>```

Output of ipython console in Spyder

```<code>runfile('/home/thomas/workspace/clover-python/mnist.py', wdir='/home/thomas/workspace/clover-python')
INFO:root:train-labels-idx1-ubyte.gz exists, skipping download
INFO:root:train-images-idx3-ubyte.gz exists, skipping download
INFO:root:t10k-labels-idx1-ubyte.gz exists, skipping download
INFO:root:t10k-images-idx3-ubyte.gz exists, skipping download
INFO:root:Epoch[0] Batch [100]  Speed: 1304.05 samples/sec      accuracy=0.097921
INFO:root:Epoch[0] Batch [200]  Speed: 1059.19 samples/sec      accuracy=0.098200
INFO:root:Epoch[0] Batch [300]  Speed: 1178.64 samples/sec      accuracy=0.099600
INFO:root:Epoch[0] Batch [400]  Speed: 1292.71 samples/sec      accuracy=0.098900
INFO:root:Epoch[0] Batch [500]  Speed: 1394.21 samples/sec      accuracy=0.096500
INFO:root:Epoch[0] Train-accuracy=0.101212
INFO:root:Epoch[0] Time cost=47.798
INFO:root:Epoch[0] Validation-accuracy=0.098000
INFO:root:Epoch[1] Batch [100]  Speed: 1247.47 samples/sec      accuracy=0.097921
INFO:root:Epoch[1] Batch [200]  Speed: 1673.79 samples/sec      accuracy=0.098200
INFO:root:Epoch[1] Batch [300]  Speed: 1283.91 samples/sec      accuracy=0.099600
INFO:root:Epoch[1] Batch [400]  Speed: 1247.79 samples/sec      accuracy=0.098900
INFO:root:Epoch[1] Batch [500]  Speed: 1371.93 samples/sec      accuracy=0.096500
INFO:root:Epoch[1] Train-accuracy=0.101212
INFO:root:Epoch[1] Time cost=44.201
INFO:root:Epoch[1] Validation-accuracy=0.098000
INFO:root:Epoch[2] Batch [100]  Speed: 1387.72 samples/sec      accuracy=0.097921
INFO:root:Epoch[2] Batch [200]  Speed: 1196.37 samples/sec      accuracy=0.098200
INFO:root:Epoch[2] Batch [300]  Speed: 1220.44 samples/sec      accuracy=0.099600
INFO:root:Epoch[2] Batch [400]  Speed: 1387.75 samples/sec      accuracy=0.098900
INFO:root:Epoch[2] Batch [500]  Speed: 1279.58 samples/sec      accuracy=0.096500
INFO:root:Epoch[2] Train-accuracy=0.101212
INFO:root:Epoch[2] Time cost=46.929
INFO:root:Epoch[2] Validation-accuracy=0.098000
INFO:root:Epoch[3] Batch [100]  Speed: 1266.24 samples/sec      accuracy=0.097921

and so on…
</code>```

答: Do you have multiple versions of MXNet installed? One thing I can think of is to verify if ipython console and python console is using the same version of python and MXNet. In ipython, you can type import mxnet; mxnet? to see what version of MXNet you're using.

Body:
I'm running the mnist example of mxnet in Spyder IDE. The training does not progress, just as if the learning rate were 0 (see output below).

If I run the same file on the console using either python or ipython, it works as expected (seeing improvements in the second epoch).

If I run the file using the normal Python console of Spyder, it also works.
But if I run the file using the ipython console, I get the output shown below.

I'm new to Python. Any ideas?

Source code

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

#%%
import mxnet as mx

#%% load mnist

mnist = mx.test_utils.get_mnist()

#%% define data iterators

batch_size = 100
train_iter = mx.io.NDArrayIter(mnist['train_data'], mnist['train_label'], batch_size, shuffle=True)
val_iter = mx.io.NDArrayIter(mnist['test_data'], mnist['test_label'], batch_size)

#%% create input variable

data = mx.sym.var('data')
# Flatten the data from 4-D shape into 2-D (batch_size, num_channel*width*height)
data = mx.sym.flatten(data=data)

#%% Multilayer Perceptron with softmax

# The first fully-connected layer and the corresponding activation function
fc1  = mx.sym.FullyConnected(data=data, num_hidden=128)
act1 = mx.sym.Activation(data=fc1, act_type="relu")

# The second fully-connected layer and the corresponding activation function
fc2  = mx.sym.FullyConnected(data=act1, num_hidden = 64)
act2 = mx.sym.Activation(data=fc2, act_type="relu")

# MNIST has 10 classes
fc3  = mx.sym.FullyConnected(data=act2, num_hidden=10)
# Softmax with cross entropy loss
mlp  = mx.sym.SoftmaxOutput(data=fc3, name='softmax')

#%% Training
import logging
logging.getLogger().setLevel(logging.DEBUG)  # logging to stdout
# create a trainable module on CPU
mlp_model = mx.mod.Module(symbol=mlp, context=mx.cpu())
mlp_model.fit(train_iter,  # train data
              eval_data=val_iter,  # validation data
              optimizer='sgd',  # use SGD to train
              optimizer_params={'learning_rate':0.1},  # use fixed learning rate
              eval_metric='acc',  # report accuracy during training
              batch_end_callback = mx.callback.Speedometer(batch_size, 100), # output progress for each 100 data batches
              num_epoch=10)  # train for at most 10 dataset passes

Output of ipython console in Spyder

runfile('/home/thomas/workspace/clover-python/mnist.py', wdir='/home/thomas/workspace/clover-python')
INFO:root:train-labels-idx1-ubyte.gz exists, skipping download
INFO:root:train-images-idx3-ubyte.gz exists, skipping download
INFO:root:t10k-labels-idx1-ubyte.gz exists, skipping download
INFO:root:t10k-images-idx3-ubyte.gz exists, skipping download
INFO:root:Epoch[0] Batch [100]  Speed: 1304.05 samples/sec      accuracy=0.097921
INFO:root:Epoch[0] Batch [200]  Speed: 1059.19 samples/sec      accuracy=0.098200
INFO:root:Epoch[0] Batch [300]  Speed: 1178.64 samples/sec      accuracy=0.099600
INFO:root:Epoch[0] Batch [400]  Speed: 1292.71 samples/sec      accuracy=0.098900
INFO:root:Epoch[0] Batch [500]  Speed: 1394.21 samples/sec      accuracy=0.096500
INFO:root:Epoch[0] Train-accuracy=0.101212
INFO:root:Epoch[0] Time cost=47.798
INFO:root:Epoch[0] Validation-accuracy=0.098000
INFO:root:Epoch[1] Batch [100]  Speed: 1247.47 samples/sec      accuracy=0.097921
INFO:root:Epoch[1] Batch [200]  Speed: 1673.79 samples/sec      accuracy=0.098200
INFO:root:Epoch[1] Batch [300]  Speed: 1283.91 samples/sec      accuracy=0.099600
INFO:root:Epoch[1] Batch [400]  Speed: 1247.79 samples/sec      accuracy=0.098900
INFO:root:Epoch[1] Batch [500]  Speed: 1371.93 samples/sec      accuracy=0.096500
INFO:root:Epoch[1] Train-accuracy=0.101212
INFO:root:Epoch[1] Time cost=44.201
INFO:root:Epoch[1] Validation-accuracy=0.098000
INFO:root:Epoch[2] Batch [100]  Speed: 1387.72 samples/sec      accuracy=0.097921
INFO:root:Epoch[2] Batch [200]  Speed: 1196.37 samples/sec      accuracy=0.098200
INFO:root:Epoch[2] Batch [300]  Speed: 1220.44 samples/sec      accuracy=0.099600
INFO:root:Epoch[2] Batch [400]  Speed: 1387.75 samples/sec      accuracy=0.098900
INFO:root:Epoch[2] Batch [500]  Speed: 1279.58 samples/sec      accuracy=0.096500
INFO:root:Epoch[2] Train-accuracy=0.101212
INFO:root:Epoch[2] Time cost=46.929
INFO:root:Epoch[2] Validation-accuracy=0.098000
INFO:root:Epoch[3] Batch [100]  Speed: 1266.24 samples/sec      accuracy=0.097921

and so on…


问:
SQL Convert from Type time to Minutes
in my database I have the running time of a movie as type: time.

How do I select the values in minutes as an integer?

Thank you!

答:
```<code>SELECT f.Titel, ROUND(TIME_TO_SEC(Laufzeit)/60)
FROM film f
WHERE f.Erscheinungsjahr >= 1980 ORDER BY f.Titel ASC
</code>```

Title: SQL Convert from Type time to Minutes


问:
Is there a simple way to get a object by _id in Kotlin?
I'm a beginner of Kotlin, I hope to get a object by _id in the following data structure, so I write the fun getMDetailByID(aMDetailsList:MDetailsList, _id:Long)... which is a traditional method.

But I think the fun is too complex, is there a simple way do that? such as use Lambda expression.

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

    data class BluetoothDef(val Status:Boolean=false)
    data class WiFiDef(val Name:String, val Status:Boolean=false)

    data class MDetail (
            val _id: Long,
            val bluetooth: BluetoothDef,
            val wiFi:WiFiDef
    )

    data class MDetailsList(val mListMetail: MutableList<MDetail>)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_main)

        var mBluetoothDef1=BluetoothDef()
        var mWiFiDef1=WiFiDef("MyConnect 1",true)
        var aMDetail1= MDetail(5L,mBluetoothDef1,mWiFiDef1)

        var mBluetoothDef2=BluetoothDef(true)
        var mWiFiDef2=WiFiDef("MyConnect 2")
        var aMDetail2= MDetail(6L,mBluetoothDef2,mWiFiDef2)

        val mListMetail:MutableList<MDetail> = mutableListOf(aMDetail1,aMDetail2)

        var aMDetailsList=MDetailsList(mListMetail)

        var c=getMDetailByID(aMDetailsList,5L)

    }

    fun getMDetailByID(aMDetailsList:MDetailsList, _id:Long):MDetail?{
        var aMDetail: MDetail?=null

        var a=aMDetailsList.mListMetail

        for (b in a){
            if (b._id==_id){
                aMDetail=b
            }
        }

        return aMDetail

    }

}
</code>```

答:
A faster and simpler alternative to current answers (it's also better than your original code, since it doesn't always need to  traverse the entire list):

```<code>fun getMDetailByID(aMDetailsList: MDetailsList, _id: Long) =
    aMDetailsList.mListMetail.findLast { it._id == _id }
</code>```

Also, consider whether you actually benefit from defining MDetailsList as a class instead of directly using (Mutable)List<MDetail> or making it a typealias. There are cases in which you do need such a type, but they aren't that common.

Body:
I'm a beginner of Kotlin, I hope to get a object by _id in the following data structure, so I write the fun getMDetailByID(aMDetailsList:MDetailsList, _id:Long)... which is a traditional method.

But I think the fun is too complex, is there a simple way do that? such as use Lambda expression.

class UIMain : AppCompatActivity() {

    data class BluetoothDef(val Status:Boolean=false)
    data class WiFiDef(val Name:String, val Status:Boolean=false)

    data class MDetail (
            val _id: Long,
            val bluetooth: BluetoothDef,
            val wiFi:WiFiDef
    )

    data class MDetailsList(val mListMetail: MutableList<MDetail>)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_main)

        var mBluetoothDef1=BluetoothDef()
        var mWiFiDef1=WiFiDef("MyConnect 1",true)
        var aMDetail1= MDetail(5L,mBluetoothDef1,mWiFiDef1)

        var mBluetoothDef2=BluetoothDef(true)
        var mWiFiDef2=WiFiDef("MyConnect 2")
        var aMDetail2= MDetail(6L,mBluetoothDef2,mWiFiDef2)

        val mListMetail:MutableList<MDetail> = mutableListOf(aMDetail1,aMDetail2)

        var aMDetailsList=MDetailsList(mListMetail)

        var c=getMDetailByID(aMDetailsList,5L)

    }

    fun getMDetailByID(aMDetailsList:MDetailsList, _id:Long):MDetail?{
        var aMDetail: MDetail?=null

        var a=aMDetailsList.mListMetail

        for (b in a){
            if (b._id==_id){
                aMDetail=b
            }
        }

        return aMDetail

    }

}

Body:
A faster and simpler alternative to current answers (it's also better than your original code, since it doesn't always need to  traverse the entire list):

fun getMDetailByID(aMDetailsList: MDetailsList, _id: Long) =
    aMDetailsList.mListMetail.findLast { it._id == _id }

Also, consider whether you actually benefit from defining MDetailsList as a class instead of directly using (Mutable)List<MDetail> or making it a typealias. There are cases in which you do need such a type, but they aren't that common.


问:
Cancel Route Resolve
I am looking for a way to terminate an async route resolve.

The scenario is the user clicks a link that fetches data necessary for a component, and while that is resolving the user hits back, or clicks on another link.  I would then want to cancel the current resolve and begin the new routing.

I can't intercept the routing by listening for these changes as no route event subscription fires while the existing route (still in the resolve phase) is processing.

For example my router may look like:

```<code>const appRoutes: Routes = [
{
    path: 'resolvableRoute',
    component: ResolvableRouteComponent,
    resolve: {
      data: RouteResolver
    }
}];
</code>```

And the resolver:

```<code>@Injectable()
export class RouteResolver implements Resolve<any> {

    constructor(private http: HttpClient) {}

    public resolve(router: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
        return this.http.get('api/path/for/data');
    }
}
</code>```

Until that http call returns in any way, the router is more or less stuck.

I have a nice loader that starts up while the route is transitioning, and I don't want to display the new component until I have the data necessary for that component, but I need to be able to terminate the request.

For example if I did not use the resolver, the user can navigate away from a component while that component is fetching data (on init for example) as I can then just destruct the component and terminate the http request.  The downside to doing the component this way is I either have to show a blank page, or an incomplete page while I am in the processing of fetching data.

答:
I am going to post my solution for now as an answer as this work around does what I need it to and maybe it will also help someone else.

The downside to this solution is I need wrappers for the router which I would prefer to not need.

Ideally I could have just created a subscription to the router navigation queue but all those methods/variables are private in the angular router so I had no way to access them.

Instead I created a RouterService that lets me trigger an event when a new navigation event fires:

```<code>@Injectable()
export class RouterService {

    protected navigateListener = new EventEmitter<any>();

    constructor(private router: Router) {}

    public subscribe(generatorOrNext?: any, error?: any, complete?: any) {
        return this.navigateListener.subscribe(generatorOrNext, error, complete);
    }

    public navigate(commands: any[], extras?: NavigationExtras): Promise<boolean> {
        this.navigateListener.next();
        return this.router.navigate(commands, extras);
    }

    public navigateByUrl(url: string | UrlTree, extras?: NavigationExtras): Promise<boolean> {
        this.navigateListener.next();
        return this.router.navigateByUrl(url, extras);
    }

}
</code>```

Then inside of my Resolve I created an observable (that normally wants to return the http request), but is also listening for an event change on the RouterService.  If the route navigation is emitted, then I terminate the http request, and let the promise know it can finish...

```<code>public resolve(router: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<any> {
        return new Promise((resolve: any, reject: any) => {
                const subscription = this.http.get('/path/to/some/url').subscribe((data) => {
                    resolve(data)
                }, (error) => {
                    reject({
                        ngNavigationCancelingError: true
                    });
                });

                this.router.subscribe(change => {
                    subscription.unsubscribe();
                    reject({
                        ngNavigationCancelingError: true
                    });
                });
        });
    }
</code>```

Title: Cancel Route Resolve

Body:
I am looking for a way to terminate an async route resolve.

The scenario is the user clicks a link that fetches data necessary for a component, and while that is resolving the user hits back, or clicks on another link.  I would then want to cancel the current resolve and begin the new routing.

I can't intercept the routing by listening for these changes as no route event subscription fires while the existing route (still in the resolve phase) is processing.

For example my router may look like:

const appRoutes: Routes = [
{
    path: 'resolvableRoute',
    component: ResolvableRouteComponent,
    resolve: {
      data: RouteResolver
    }
}];

And the resolver:

@Injectable()
export class RouteResolver implements Resolve<any> {

    constructor(private http: HttpClient) {}

    public resolve(router: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
        return this.http.get('api/path/for/data');
    }
}

Until that http call returns in any way, the router is more or less stuck.

I have a nice loader that starts up while the route is transitioning, and I don't want to display the new component until I have the data necessary for that component, but I need to be able to terminate the request.

For example if I did not use the resolver, the user can navigate away from a component while that component is fetching data (on init for example) as I can then just destruct the component and terminate the http request.  The downside to doing the component this way is I either have to show a blank page, or an incomplete page while I am in the processing of fetching data.

Body:
I am going to post my solution for now as an answer as this work around does what I need it to and maybe it will also help someone else.

The downside to this solution is I need wrappers for the router which I would prefer to not need.

Ideally I could have just created a subscription to the router navigation queue but all those methods/variables are private in the angular router so I had no way to access them.

Instead I created a RouterService that lets me trigger an event when a new navigation event fires:

@Injectable()
export class RouterService {

    protected navigateListener = new EventEmitter<any>();

    constructor(private router: Router) {}

    public subscribe(generatorOrNext?: any, error?: any, complete?: any) {
        return this.navigateListener.subscribe(generatorOrNext, error, complete);
    }

    public navigate(commands: any[], extras?: NavigationExtras): Promise<boolean> {
        this.navigateListener.next();
        return this.router.navigate(commands, extras);
    }

    public navigateByUrl(url: string | UrlTree, extras?: NavigationExtras): Promise<boolean> {
        this.navigateListener.next();
        return this.router.navigateByUrl(url, extras);
    }

}

Then inside of my Resolve I created an observable (that normally wants to return the http request), but is also listening for an event change on the RouterService.  If the route navigation is emitted, then I terminate the http request, and let the promise know it can finish...

public resolve(router: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<any> {
        return new Promise((resolve: any, reject: any) => {
                const subscription = this.http.get('/path/to/some/url').subscribe((data) => {
                    resolve(data)
                }, (error) => {
                    reject({
                        ngNavigationCancelingError: true
                    });
                });

                this.router.subscribe(change => {
                    subscription.unsubscribe();
                    reject({
                        ngNavigationCancelingError: true
                    });
                });
        });
    }


问:
how to display state inside input tag
I'm building the following react component and trying to add hidden to my input box.

```<code>class FontChooser extends React.Component {

constructor(props) {
super(props);
this.state={display:'hidden'};
}

render() {

return(
       <div>
          <input type="checkbox" id="boldCheckbox" this.state.display />
       </div>
);
}
}
</code>```

I also tried {this.state.display} but I get unexpected token

答:
Either , replace display by visibility , or replace hidden by none.

Either you have {display: 'none'} or {visibility: 'hidden'} .

Then answer of @Linas will be valid . I mean :

```<code><input type="text" style={this.state} />
</code>```

or

```<code><input type="text" style={{...this.state}} />
</code>```

Both render the same.

Title: how to display state inside input tag

Body:
I'm building the following react component and trying to add hidden to my input box.

class FontChooser extends React.Component {

constructor(props) {
super(props);
this.state={display:'hidden'};
}

render() {

return(

          <input type="checkbox" id="boldCheckbox" this.state.display />

);
}
}

I also tried {this.state.display} but I get unexpected token

Body:
Either , replace display by visibility , or replace hidden by none.

Either you have {display: 'none'} or {visibility: 'hidden'} .

Then answer of @Linas will be valid . I mean :

<input type="text" style={this.state} />

or

<input type="text" style={{...this.state}} />

Both render the same.


问:
How to get X largest values from array
I have array:
[2 , 4 , 5, 1 , 4 , 20]

How to get X highest values from this array?

Like this:

```<code>getHighest(2): 25, 5
getHighest(3): 25, 5, 4
</code>```

答:
The basic idea is to create a priority queue (max heap) of the first X items. Then, for each remaining item in the array, if it's smaller than the first item on the heap, remove the first item from the heap and add the new item. Something like this:

```<code>heap = new maxHeap();
for (i = 0; i < X; i++)
{
    heap.Add(a[i]);
}
for (; i < a.Length; ++i)
{
    if (a[i] < heap.peek())
    {
        heap.removeFirst();
        heap.Add(a[i]);
    }
}
// at this point, the smallest X items are on the heap.
// Remove them:
while (!heap.IsEmpty())
{
    print(heap.removeFirst());
}
</code>```

Note that what I describe above is how to get the X smallest items from the array. If you want the X largest, create a min heap and change the comparison from < to >.

Title: How to get X largest values from array

Body:
I have array:
[2 , 4 , 5, 1 , 4 , 20]

How to get X highest values from this array?

Like this:

getHighest(2): 25, 5
getHighest(3): 25, 5, 4

Body:
The basic idea is to create a priority queue (max heap) of the first X items. Then, for each remaining item in the array, if it's smaller than the first item on the heap, remove the first item from the heap and add the new item. Something like this:

heap = new maxHeap();
for (i = 0; i < X; i++)
{
    heap.Add(a[i]);
}
for (; i < a.Length; ++i)
{
    if (a[i] < heap.peek())
    {
        heap.removeFirst();
        heap.Add(a[i]);
    }
}
// at this point, the smallest X items are on the heap.
// Remove them:
while (!heap.IsEmpty())
{
    print(heap.removeFirst());
}

Note that what I describe above is how to get the X smallest items from the array. If you want the X largest, create a min heap and change the comparison from < to >.


问:
NoHostAvailableException in Cassandra
I need to make a presentation+ connection to cassandra for classes. After quite a big hussle I left behind other kinds of errors, but I'm getting stuck here, where it seems not to get the address of the Keyspace.

```<code>import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.exceptions.NoHostAvailableException;

public class conectaradb {

public static void main(String[] args) {
 try {
    Cluster cluster;
     Session sesion;

     cluster = Cluster.builder().addContactPoint("127.0.0.1").withPort(9042).build();

     sesion= cluster.connect("ejemplodb");

     ResultSet resultado= sesion.execute("select * from empleados");
     String nombreemp,fecha,cargo;
     double comision,salario;
     int empno;

     for (Row row:resultado) {
         empno=row.getInt("empno");
         cargo=row.getString("cargo");
         comision=row.getDouble("comision");
         fecha=row.getString("fechaing");
         nombreemp=row.getString("nombreempno");
         salario=row.getDouble("salario");
         System.out.println(empno+" "+cargo+" "+comision+" "+fecha+" "+nombreemp+" "+salario);
     }
     cluster.close();

 }catch(NoHostAvailableException e) {
 System.out.println(e.getErrors());
}

}

}
</code>```

I'd be glad if someone can Identify where is the error, I think I have the yaml file right. I get the error when the code reaches the localhost on addcontactpoint: "All hosts tried for query failed".
After a .getError I get a "TransportException". I don't know how to proceed further.

答:
Update rpc_broadcast_address in cassandra.yaml to a valid IP; since rpc_address is 0.0.0.0. Then try and connect via Java with that IP after restarting Cassandra.

https://docs.datastax.com/en/developer/java-driver/3.3/manual/address_resolution/

Title: NoHostAvailableException in Cassandra

Body:
I need to make a presentation+ connection to cassandra for classes. After quite a big hussle I left behind other kinds of errors, but I'm getting stuck here, where it seems not to get the address of the Keyspace.

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.exceptions.NoHostAvailableException;

public class conectaradb {

public static void main(String[] args) {
 try {
    Cluster cluster;
     Session sesion;

     cluster = Cluster.builder().addContactPoint("127.0.0.1").withPort(9042).build();

     sesion= cluster.connect("ejemplodb");

     ResultSet resultado= sesion.execute("select * from empleados");
     String nombreemp,fecha,cargo;
     double comision,salario;
     int empno;

     for (Row row:resultado) {
         empno=row.getInt("empno");
         cargo=row.getString("cargo");
         comision=row.getDouble("comision");
         fecha=row.getString("fechaing");
         nombreemp=row.getString("nombreempno");
         salario=row.getDouble("salario");
         System.out.println(empno+" "+cargo+" "+comision+" "+fecha+" "+nombreemp+" "+salario);
     }
     cluster.close();

 }catch(NoHostAvailableException e) {
 System.out.println(e.getErrors());
}

}

}

I'd be glad if someone can Identify where is the error, I think I have the yaml file right. I get the error when the code reaches the localhost on addcontactpoint: "All hosts tried for query failed".
After a .getError I get a "TransportException". I don't know how to proceed further.


问:
Google APP SCRIPT -> Force submit a google form after a given duration
I'm trying to create a script that could stop and submit the entire form after a given duration.
The duration have to be set in the script settings when creating the form.
I will use this functionality in order to evaluate students.

I did not understood anything in the google documentation, so I don't know how to stop the form and how to wait the duration (like the setTimeOut function in javascript).

Can you help me please ?

Waykizz

答:
This cannot currently be done using native Google forms.

You could use HTMLService to create your own form and could add the time controls to it using client-side javascript. This SO answer covers the creation of the form. Be warned that this is much more complex than using Google forms. As for the timer/autosubmit part of it see this SO answer.


问:
How to convert a year to the Japanese calendar?
I have this code that converts the CURRENT Gregorian year to the Japanese era year.

```<code>var date = new Date().toLocaleDateString("ja-JP-u-ca-japanese");
var year = date.substring(0, date.indexOf("/"));
</code>```

However, I want to input the year myself instead of getting the present year.
I tried like this:

```<code>var myyear = 2018;
var date = myyear.toLocaleDateString("ja-JP-u-ca-japanese");
var year = date.substring(0, date.indexOf("/"));
</code>```

It didn't work though. How should I do it?

答:
You can always do that with the following.
DateTime val = new DateTime(your_year_variable, month, year, new GregorianCalendar());

Remember to add System.Globalization namespace at top.

Body:
I have this code that converts the CURRENT Gregorian year to the Japanese era year.

var date = new Date().toLocaleDateString("ja-JP-u-ca-japanese");
var year = date.substring(0, date.indexOf("/"));

However, I want to input the year myself instead of getting the present year.
I tried like this:

var myyear = 2018;
var date = myyear.toLocaleDateString("ja-JP-u-ca-japanese");
var year = date.substring(0, date.indexOf("/"));

It didn't work though. How should I do it?


问:
Android wear emulator crashes on startup
I'm trying to develop an Android wear application, using Android studio.  Everything was going fine until I was requested to make an update a few days ago (unfortunately I do not remember what the exact update was, but I think it actually had to do with Android studio, but I might be wrong about that)

Anyway:  After the update, my application does not start properly in the emulator.  The emulator fires up as it should, but then shows a screen where it says that my app has stopped and shows a reload button.  When I press the reload button the app starts as it should.

Does anybody know why I can't get my app to start right away?

I found an error message in logical that says:

       android.view.InflateException: Binary XML file line #23: Binary XML file line #2: Error inflating class com.google.android.clockwork.home2.module.watchfacepicker.AllFacesView

Also, I have tried to limit my activity xml to just the bare layout at the top level, but I still get the same behavior...

答:
Not sure why this was downvoted.  I'm getting the same error in almost all my emulators, except mine is showing Android Wear crashing not my app.  I'm able to bring up my app if I run it, then hit he back button on the emulator.

Something to do with the the Watch Face picker.


问:
Is there a way to distribute windows phone 7 applications without using the windows phone 7 marketplace?
I may need to port a private application from android to windows phone 7.</p>

答: There's no "official" way to do it, at least not for now. But Microsoft is in touch with developers who unlocked their phones to run home brew applications, to figure out how to make it available for developers, without prejudice the app market ecossystem.</p>


答:
You could try to convert it this way:

```<code>select (datediff(second,0,[timeValue])/60) as [TimeinMinutes]
</code>```

This is a SQL Server statement.

Below is an example to try out for SQL Server:

```<code>create table #tbl1 (
    [RunningTime] time
);

insert into #tbl1 ([RunningTime])
values
    ('10:53')
;

select
    [RunningTime]
    ,datediff(second,0,[RunningTime]) as [RunningTimeInSeconds]
    ,(datediff(second,0,[RunningTime])/60) as [RunningTimeInMinutes]
from #tbl1
;

drop table #tbl1;
</code>```

Title: SQL Convert from Type time to Minutes

Body:
in my database I have the running time of a movie as type: time.

How do I select the values in minutes as an integer?

Thank you!

Body:
You could try to convert it this way:

select (datediff(second,0,[timeValue])/60) as [TimeinMinutes]

This is a SQL Server statement.

Below is an example to try out for SQL Server:

create table #tbl1 (
    [RunningTime] time
);

insert into #tbl1 ([RunningTime])
values
    ('10:53')
;

select
    [RunningTime]
    ,datediff(second,0,[RunningTime]) as [RunningTimeInSeconds]
    ,(datediff(second,0,[RunningTime])/60) as [RunningTimeInMinutes]
from #tbl1
;

drop table #tbl1;