问:
Typescript error "Cannot write file ... because it would overwrite input file."
In my Typescript 2.2.1 project in Visual Studio 2015 Update 3, I am getting hundreds of errors in the error list like:

Cannot write file 'C:/{{my-project}}/node_modules/buffer-shims/index.js' because it would overwrite input file.

It looks like this all the time.  It doesn't actually prevent building, and everything works just fine, but the error list is distracting and difficult to locate "real" errors when they occur.

Here is my tsconfig.json file

```<code>{
  "compileOnSave": true,
  "compilerOptions": {
    "baseUrl": ".",
    "module": "commonjs",
    "noImplicitAny": true,
    "removeComments": true,
    "sourceMap": true,
    "target": "ES5",
    "forceConsistentCasingInFileNames": true,
    "strictNullChecks": true,
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,

    "typeRoots": [],
    "types": [] //Explicitly specify an empty array so that the TS2 @types modules are not acquired since we aren't ready for them yet.
  },
  "exclude": ["node_modules"]
}
</code>```

How can I get rid of all these errors?

答:
this config works for me</p>

```<code>"allowJs": true
</code>```

Body:
In my Typescript 2.2.1 project in Visual Studio 2015 Update 3, I am getting hundreds of errors in the error list like:

Cannot write file 'C:/{{my-project}}/node_modules/buffer-shims/index.js' because it would overwrite input file.

It looks like this all the time.  It doesn't actually prevent building, and everything works just fine, but the error list is distracting and difficult to locate "real" errors when they occur.

Here is my tsconfig.json file

{
  "compileOnSave": true,
  "compilerOptions": {
    "baseUrl": ".",
    "module": "commonjs",
    "noImplicitAny": true,
    "removeComments": true,
    "sourceMap": true,
    "target": "ES5",
    "forceConsistentCasingInFileNames": true,
    "strictNullChecks": true,
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,

    "typeRoots": [],
    "types": [] //Explicitly specify an empty array so that the TS2 @types modules are not acquired since we aren't ready for them yet.
  },
  "exclude": ["node_modules"]
}

How can I get rid of all these errors?

Body:
this config works for me

"allowJs": true


来源: stackexchange

问:
Cannot connect to Eclipse Mosquitto broker using Node.js mqtt library
I am running Eclipse Mosquitto on a local docker container on 172.17.0.2:1883

I am able to publish/subscribe using MQTT.fx client but now trying to connect to the broker from node and haven't been able to.

The topic is "sensors"

```<code>CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                            NAMES
e747c86b6ec1        eclipse-mosquitto   "/docker-entrypoint.…"   5 hours ago         Up 5 hours          0.0.0.0:1883->1883/tcp, 0.0.0.0:9001->9001/tcp   adoring_varahamihira
</code>```

When I inspect the IP address

```<code>docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' e747c86b6ec1
172.17.0.2
</code>```

I am trying to use the following node server to connect to my MQTT broker but the 'connect' event never seems to happen.

```<code>// Note: I have an express server running but didn't include
const mqtt = require("mqtt")

var MQTT_TOPIC = "sensors";
var MQTT_ADDR = "mqtt://172.17.0.2";
var MQTT_PORT = 1883;

var client = mqtt.connect(MQTT_ADDR, {
  port: MQTT_PORT,
  clientId: 'bgtestnodejs232323',
  protocolId: 'MQIsdp',
  protocolVersion: 3,
  connectTimeout: 1000,
  debug: true
});

client.on('connect', function () {
  console.log("connected!")
});

client.on('error', function (err) {
  console.log(err)``
  client.end()
})
</code>```

When I run:

```<code>console.log(util.inspect(client))
</code>```

The output is:

```<code>MqttClient {
  options:
   { protocol: 'mqtt',
     slashes: true,
     auth: null,
     host: '172.17.0.2',
     port: 1883,
     hostname: '172.17.0.2',
     hash: null,
     search: null,
     query: [Object: null prototype] {},
     pathname: null,
     path: null,
     href: 'mqtt://172.17.0.2',
     clientId: 'bgtestnodejs232323',
     protocolId: 'MQIsdp',
     protocolVersion: 3,
     connectTimeout: 1000,
     debug: true,
     defaultProtocol: 'mqtt',
     keepalive: 60,
     reschedulePings: true,
     reconnectPeriod: 1000,
     clean: true,
     resubscribe: true,
     customHandleAcks: [Function] },
  streamBuilder: [Function: wrapper],
  outgoingStore: Store { options: { clean: true }, _inflights: Map {} },
  incomingStore: Store { options: { clean: true }, _inflights: Map {} },
  queueQoSZero: true,
  _resubscribeTopics: {},
  messageIdToTopic: {},
  pingTimer: null,
  connected: false,
  disconnecting: false,
  queue: [],
  connackTimer:
   Timeout {
     _called: false,
     _idleTimeout: 1000,
     _idlePrev: [TimersList],
     _idleNext: [TimersList],
     _idleStart: 478,
     _onTimeout: [Function],
     _timerArgs: undefined,
     _repeat: null,
     _destroyed: false,
     [Symbol(unrefed)]: false,
     [Symbol(asyncId)]: 9,
     [Symbol(triggerId)]: 1 },
  reconnectTimer: null,
  _storeProcessing: false,
  _packetIdsDuringStoreProcessing: {},
  nextId: 26898,
  outgoing: {},
  _firstConnection: true,
  _events:
   [Object: null prototype] {
     close: [ [Function], [Function], [Function] ],
     connect: [Function] },
  _eventsCount: 2,
  _maxListeners: undefined,
  stream:
   Socket {
     connecting: true,
     _hadError: false,
     _handle:
      TCP {
        reading: false,
        onread: [Function: onStreamRead],
        onconnection: null,
        [Symbol(owner)]: [Circular] },
     _parent: null,
     _host: null,
     _readableState:
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: BufferList { head: null, tail: null, length: 0 },
        length: 0,
        pipes: [Writable],
        pipesCount: 1,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: false,
        sync: true,
        needReadable: false,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: true,
        paused: false,
        emitClose: false,
        destroyed: false,
        defaultEncoding: 'utf8',
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: false,
     _events:
      [Object: null prototype] {
        end: [Array],
        data: [Function: ondata],
        error: [Function: nop],
        close: [Function] },
     _eventsCount: 4,
     _maxListeners: 1000,
     _writableState:
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        destroyed: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 34,
        writing: false,
        corked: 1,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        bufferedRequest: [Object],
        lastBufferedRequest: [Object],
        pendingcb: 9,
        prefinished: false,
        errorEmitted: false,
        emitClose: false,
        bufferedRequestCount: 9,
        corkedRequestsFree: [Object] },
     writable: true,
     allowHalfOpen: false,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server: null,
     _server: null,
     [Symbol(asyncId)]: 5,
     [Symbol(lastWriteQueueSize)]: 0,
     [Symbol(timeout)]: null,
     [Symbol(kBytesRead)]: 0,
     [Symbol(kBytesWritten)]: 0 } }
</code>```

I have been trying the suggestions in this answer: Why is MQTT not connecting with NodeJS?

Thanks for your help!

答:
The IP address range 172.17.0.0/16 that is handed out to Docker containers by the Docker engine are part of the RFC1918 set intended for private use.

In the case of Docker, they are used on the internal "bridge" network and only accessible from other docker containers or the machine hosting the Docker engine.

The 0.0.0.0:1883->1883/tcp, 0.0.0.0:9001->9001/tcp output for the info of your mosquitto container shows that these ports have been exposed and are mapped to the host machines IP address. You should be able to connect if you change 172.17.0.2 for the IP address of the machine hosting the Docker engine.

ContentLicense: CC BY-SA 4.0

Body:
I am running Eclipse Mosquitto on a local docker container on 172.17.0.2:1883

I am able to publish/subscribe using MQTT.fx client but now trying to connect to the broker from node and haven't been able to.

The topic is "sensors"

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                            NAMES
e747c86b6ec1        eclipse-mosquitto   "/docker-entrypoint.…"   5 hours ago         Up 5 hours          0.0.0.0:1883->1883/tcp, 0.0.0.0:9001->9001/tcp   adoring_varahamihira

When I inspect the IP address

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' e747c86b6ec1
172.17.0.2

I am trying to use the following node server to connect to my MQTT broker but the 'connect' event never seems to happen.

// Note: I have an express server running but didn't include
const mqtt = require("mqtt")

var MQTT_TOPIC = "sensors";
var MQTT_ADDR = "mqtt://172.17.0.2";
var MQTT_PORT = 1883;

var client = mqtt.connect(MQTT_ADDR, {
  port: MQTT_PORT,
  clientId: 'bgtestnodejs232323',
  protocolId: 'MQIsdp',
  protocolVersion: 3,
  connectTimeout: 1000,
  debug: true
});

client.on('connect', function () {
  console.log("connected!")
});

client.on('error', function (err) {
  console.log(err)``
  client.end()
})

When I run:

console.log(util.inspect(client))

The output is:

MqttClient {
  options:
   { protocol: 'mqtt',
     slashes: true,
     auth: null,
     host: '172.17.0.2',
     port: 1883,
     hostname: '172.17.0.2',
     hash: null,
     search: null,
     query: [Object: null prototype] {},
     pathname: null,
     path: null,
     href: 'mqtt://172.17.0.2',
     clientId: 'bgtestnodejs232323',
     protocolId: 'MQIsdp',
     protocolVersion: 3,
     connectTimeout: 1000,
     debug: true,
     defaultProtocol: 'mqtt',
     keepalive: 60,
     reschedulePings: true,
     reconnectPeriod: 1000,
     clean: true,
     resubscribe: true,
     customHandleAcks: [Function] },
  streamBuilder: [Function: wrapper],
  outgoingStore: Store { options: { clean: true }, _inflights: Map {} },
  incomingStore: Store { options: { clean: true }, _inflights: Map {} },
  queueQoSZero: true,
  _resubscribeTopics: {},
  messageIdToTopic: {},
  pingTimer: null,
  connected: false,
  disconnecting: false,
  queue: [],
  connackTimer:
   Timeout {
     _called: false,
     _idleTimeout: 1000,
     _idlePrev: [TimersList],
     _idleNext: [TimersList],
     _idleStart: 478,
     _onTimeout: [Function],
     _timerArgs: undefined,
     _repeat: null,
     _destroyed: false,
     [Symbol(unrefed)]: false,
     [Symbol(asyncId)]: 9,
     [Symbol(triggerId)]: 1 },
  reconnectTimer: null,
  _storeProcessing: false,
  _packetIdsDuringStoreProcessing: {},
  nextId: 26898,
  outgoing: {},
  _firstConnection: true,
  _events:
   [Object: null prototype] {
     close: [ [Function], [Function], [Function] ],
     connect: [Function] },
  _eventsCount: 2,
  _maxListeners: undefined,
  stream:
   Socket {
     connecting: true,
     _hadError: false,
     _handle:
      TCP {
        reading: false,
        onread: [Function: onStreamRead],
        onconnection: null,
        [Symbol(owner)]: [Circular] },
     _parent: null,
     _host: null,
     _readableState:
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: BufferList { head: null, tail: null, length: 0 },
        length: 0,
        pipes: [Writable],
        pipesCount: 1,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: false,
        sync: true,
        needReadable: false,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: true,
        paused: false,
        emitClose: false,
        destroyed: false,
        defaultEncoding: 'utf8',
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: false,
     _events:
      [Object: null prototype] {
        end: [Array],
        data: [Function: ondata],
        error: [Function: nop],
        close: [Function] },
     _eventsCount: 4,
     _maxListeners: 1000,
     _writableState:
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        destroyed: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 34,
        writing: false,
        corked: 1,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        bufferedRequest: [Object],
        lastBufferedRequest: [Object],
        pendingcb: 9,
        prefinished: false,
        errorEmitted: false,
        emitClose: false,
        bufferedRequestCount: 9,
        corkedRequestsFree: [Object] },
     writable: true,
     allowHalfOpen: false,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server: null,
     _server: null,
     [Symbol(asyncId)]: 5,
     [Symbol(lastWriteQueueSize)]: 0,
     [Symbol(timeout)]: null,
     [Symbol(kBytesRead)]: 0,
     [Symbol(kBytesWritten)]: 0 } }

I have been trying the suggestions in this answer: Why is MQTT not connecting with NodeJS?

Thanks for your help!


问:
identify circular parent/child records
I am trying to identify (and then prevent in the future) parent/children records in List object(having parent and child ID as integer property of SampleItem class) from pointing back at themselves.

Below is the SampleItem Class and list of SampleItem object:

```<code>public class SampleItem
    {
        public int ChildId{ get; set; }
        public int ParentId { get; set; }
    }

List<SampleItem> items= new List<SampleItem>
{
    new SampleItem{ ParentId=Null, ChildId=1 },
    new SampleItem{ ParentId=1, ChildId=2 },
    new SampleItem{ ParentId=2, ChildId=4 },
    new SampleItem{ ParentId=4, ChildId=1 }
};

</code>```

When I go to expand out the parent/children relationships it looks like this :
    1--> 2 --> 4 --> 1 (again) --> 2 (again) --> 3 (again)...repeating...(1 is root/parent of all)

SampleItems list object is like a tree structure where circular reference is not allowed.

How to identify these circular relationships and how can I prevent them in c# code? I would really appreciate if some one can answer this question.

答:
This is essentially determining if a linked list has a cycle. The normal approach to this is to increment through the list at two different speeds and see if the nodes are ever equal, or if the faster incrementing node has exhausted the list. Using a slight modification to your base class to allow for a null value,

```<code>public class SampleItem
{
    public int ChildId { get; set; }
    public int? ParentId { get; set; }
}
</code>```

The following quick and dirty implementation will determine if your collection has a cycle for a list of SampleItem. This does assume that relationships are one to one and in your example and not one to many, as that would need to cover the case for each potential child.

```<code>void Main()
{
    List<SampleItem> itemsWithCycle = new List<SampleItem>
    {
        new SampleItem{ ParentId=null, ChildId=1 },
        new SampleItem{ ParentId=1, ChildId=2 },
        new SampleItem{ ParentId=2, ChildId=4 },
        new SampleItem{ ParentId=4, ChildId=1 }
    };
    List<SampleItem> itemsWithoutCycle = new List<SampleItem>
    {
        new SampleItem{ ParentId=null, ChildId=1 },
        new SampleItem{ ParentId=1, ChildId=2 },
        new SampleItem{ ParentId=2, ChildId=4 },
        new SampleItem{ ParentId=4, ChildId=5 }
    };

    Console.WriteLine(HasCycle(itemsWithCycle)); // true
    Console.WriteLine(HasCycle(itemsWithoutCycle)); // false

    bool HasCycle(IEnumerable<SampleItem> items) {
        var slow = items.FirstOrDefault(i => i.ParentId == null);
        var fast = slow;

        while(fast != null) {
            fast = Next(Next(fast));
            slow = Next(slow);

            if(fast == slow && fast != null) return true;
        }
        return false;

        SampleItem Next(SampleItem item)
        {
            if(item == null) return null;

            return items.FirstOrDefault(i => i.ParentId == item.ChildId);
        }
    }
}
</code>```

Title: identify circular parent/child records

Body:
I am trying to identify (and then prevent in the future) parent/children records in List object(having parent and child ID as integer property of SampleItem class) from pointing back at themselves.

Below is the SampleItem Class and list of SampleItem object:

public class SampleItem
    {
        public int ChildId{ get; set; }
        public int ParentId { get; set; }
    }

List<SampleItem> items= new List<SampleItem>
{
    new SampleItem{ ParentId=Null, ChildId=1 },
    new SampleItem{ ParentId=1, ChildId=2 },
    new SampleItem{ ParentId=2, ChildId=4 },
    new SampleItem{ ParentId=4, ChildId=1 }
};

When I go to expand out the parent/children relationships it looks like this :
    1--> 2 --> 4 --> 1 (again) --> 2 (again) --> 3 (again)...repeating...(1 is root/parent of all)

SampleItems list object is like a tree structure where circular reference is not allowed.

How to identify these circular relationships and how can I prevent them in c# code? I would really appreciate if some one can answer this question.

Body:
This is essentially determining if a linked list has a cycle. The normal approach to this is to increment through the list at two different speeds and see if the nodes are ever equal, or if the faster incrementing node has exhausted the list. Using a slight modification to your base class to allow for a null value,

public class SampleItem
{
    public int ChildId { get; set; }
    public int? ParentId { get; set; }
}

The following quick and dirty implementation will determine if your collection has a cycle for a list of SampleItem. This does assume that relationships are one to one and in your example and not one to many, as that would need to cover the case for each potential child.

void Main()
{
    List<SampleItem> itemsWithCycle = new List<SampleItem>
    {
        new SampleItem{ ParentId=null, ChildId=1 },
        new SampleItem{ ParentId=1, ChildId=2 },
        new SampleItem{ ParentId=2, ChildId=4 },
        new SampleItem{ ParentId=4, ChildId=1 }
    };
    List<SampleItem> itemsWithoutCycle = new List<SampleItem>
    {
        new SampleItem{ ParentId=null, ChildId=1 },
        new SampleItem{ ParentId=1, ChildId=2 },
        new SampleItem{ ParentId=2, ChildId=4 },
        new SampleItem{ ParentId=4, ChildId=5 }
    };

    Console.WriteLine(HasCycle(itemsWithCycle)); // true
    Console.WriteLine(HasCycle(itemsWithoutCycle)); // false

    bool HasCycle(IEnumerable<SampleItem> items) {
        var slow = items.FirstOrDefault(i => i.ParentId == null);
        var fast = slow;

        while(fast != null) {
            fast = Next(Next(fast));
            slow = Next(slow);

            if(fast == slow && fast != null) return true;
        }
        return false;

        SampleItem Next(SampleItem item)
        {
            if(item == null) return null;

            return items.FirstOrDefault(i => i.ParentId == item.ChildId);
        }
    }
}


问:
Unable to install @tensorflow/tfjs-node with npm
I cannot install '@tensorflow/tfjs-node'

I installed it using 'npm install @tensorflow/tfjs-node' but the installations fails. I tried installing 'node-pre-gyp' globally, with and without root permissions but no success. I run on node v12.9.0.

```<code>
> fsevents@1.2.9 install /Users/username/Documents/Development/AI/Tensorflow/node_modules/fsevents
> node install

node-pre-gyp WARN Using needle for node-pre-gyp https download
[fsevents] Success: "/Users/username/Documents/Development/AI/Tensorflow/node_modules/fsevents/lib/binding/Release/node-v72-darwin-x64/fse.node" is installed via remote

> @tensorflow/tfjs-node@1.2.9 install /Users/username/Documents/Development/AI/Tensorflow/node_modules/@tensorflow/tfjs-node
> node scripts/install.js

CPU-darwin-1.2.9.tar.gz
* Downloading libtensorflow
[==============================] 10422374/bps 100% 0.0s
* Building TensorFlow Node.js bindings
node-pre-gyp install failed with error: Error: Command failed: node-pre-gyp install --fallback-to-build
node-pre-gyp WARN Using needle for node-pre-gyp https download
node-pre-gyp WARN Tried to download(404): https://storage.googleapis.com/tf-builds/pre-built-binary/napi-v4/1.2.9/CPU-darwin-1.2.9.tar.gz
node-pre-gyp WARN Pre-built binaries not found for @tensorflow/tfjs-node@1.2.9 and node@12.9.0 (node-v72 ABI, unknown) (falling back to source compile with node-gyp)
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.

gyp: No Xcode or CLT version detected!
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:344:16)
gyp ERR! stack     at ChildProcess.emit (events.js:209:13)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:272:12)
gyp ERR! System Darwin 19.0.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "configure" "--fallback-to-build" "--module=/Users/username/Documents/Development/AI/Tensorflow/node_modules/@tensorflow/tfjs-node/lib/napi-v4/tfjs_binding.node" "--module_name=tfjs_binding" "--module_path=/Users/username/Documents/Development/AI/Tensorflow/node_modules/@tensorflow/tfjs-node/lib/napi-v4" "--napi_version=4" "--node_abi_napi=napi" "--napi_build_version=4" "--node_napi_label=napi-v4"
gyp ERR! cwd /Users/username/Documents/Development/AI/Tensorflow/node_modules/@tensorflow/tfjs-node
gyp ERR! node -v v12.9.0
gyp ERR! node-gyp -v v5.0.3
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute '/usr/local/bin/node /usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --module=/Users/username/Documents/Development/AI/Tensorflow/node_modules/@tensorflow/tfjs-node/lib/napi-v4/tfjs_binding.node --module_name=tfjs_binding --module_path=/Users/username/Documents/Development/AI/Tensorflow/node_modules/@tensorflow/tfjs-node/lib/napi-v4 --napi_version=4 --node_abi_napi=napi --napi_build_version=4 --node_napi_label=napi-v4' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/Users/username/Documents/Development/AI/Tensorflow/node_modules/node-pre-gyp/lib/util/compile.js:83:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:209:13)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:1021:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)
node-pre-gyp ERR! System Darwin 19.0.0
node-pre-gyp ERR! command "/usr/local/bin/node" "/Users/username/Documents/Development/AI/Tensorflow/node_modules/.bin/node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd /Users/username/Documents/Development/AI/Tensorflow/node_modules/@tensorflow/tfjs-node
node-pre-gyp ERR! node -v v12.9.0
node-pre-gyp ERR! node-pre-gyp -v v0.13.0
node-pre-gyp ERR! not ok

> nodemon@1.19.2 postinstall /Users/username/Documents/Development/AI/Tensorflow/node_modules/nodemon
> node bin/postinstall || exit 0

npm WARN tensorflow@1.0.0 No description
npm WARN tensorflow@1.0.0 No repository field.

added 362 packages from 202 contributors and audited 2419 packages in 11.642s
found 0 vulnerabilities

</code>```

node-pre-gyp failes to install and 'CPU-darwin-1.2.9.tar.gz' no longer seems to exist, so I get an 404 error.

Also this question if probably somewhat of a duplicate to this question:
Cannot import @tensorflow/tfjs-node in nodejs

EDIT: Tried to downgrade to @tensorflow/tfjs-node@1.2.8, but the error is still there:

```<code>CPU-darwin-1.2.8.tar.gz
* Downloading libtensorflow
[==============================] 10642013/bps 100% 0.0s
* Building TensorFlow Node.js bindings
node-pre-gyp install failed with error: Error: Command failed: node-pre-gyp install --fallback-to-build
node-pre-gyp WARN Using needle for node-pre-gyp https download
node-pre-gyp WARN Tried to download(404): https://storage.googleapis.com/tf-builds/pre-built-binary/napi-v4/1.2.8/tfjs_binding-v1.2.8-node-v72-darwin-x64.tar.gz
node-pre-gyp WARN Pre-built binaries not found for @tensorflow/tfjs-node@1.2.8 and node@12.9.0 (node-v72 ABI, unknown) (falling back to source compile with node-gyp)
</code>```

答:
I had the same issue on MacOS 10.15 when installing 1.5.2.

```<code>CPU-darwin-1.5.2.tar.gz
* Downloading libtensorflow
[==============================] 15666967/bps 100% 0.0s
* Building TensorFlow Node.js bindings
node-pre-gyp install failed with error: Error: Command failed: node-pre-gyp install --fallback-to-build
node-pre-gyp WARN Using needle for node-pre-gyp https download
node-pre-gyp WARN Tried to download(404): https://storage.googleapis.com/tf-builds/pre-built-binary/napi-v5/1.5.2/CPU-darwin-1.5.2.tar.gz
node-pre-gyp WARN Pre-built binaries not found for @tensorflow/tfjs-node@1.5.2 and node@12.15.0 (node-v72 ABI, unknown) (falling back to source compile with node-gyp)
</code>```

https://www.npmjs.com/package/@tensorflow/tfjs-node#windows--mac-os-x-requires-python-27

You have to be using python 2.7 when attempting the install. If you aren't you will get a similar error to that you posted, I was in a python3 venv and thus got this error; falling back to 2.7 solved the problem.

Body:
I cannot install '@tensorflow/tfjs-node'

I installed it using 'npm install @tensorflow/tfjs-node' but the installations fails. I tried installing 'node-pre-gyp' globally, with and without root permissions but no success. I run on node v12.9.0.

> fsevents@1.2.9 install /Users/username/Documents/Development/AI/Tensorflow/node_modules/fsevents
> node install

node-pre-gyp WARN Using needle for node-pre-gyp https download
[fsevents] Success: "/Users/username/Documents/Development/AI/Tensorflow/node_modules/fsevents/lib/binding/Release/node-v72-darwin-x64/fse.node" is installed via remote

> @tensorflow/tfjs-node@1.2.9 install /Users/username/Documents/Development/AI/Tensorflow/node_modules/@tensorflow/tfjs-node
> node scripts/install.js

CPU-darwin-1.2.9.tar.gz
* Downloading libtensorflow
[==============================] 10422374/bps 100% 0.0s
* Building TensorFlow Node.js bindings
node-pre-gyp install failed with error: Error: Command failed: node-pre-gyp install --fallback-to-build
node-pre-gyp WARN Using needle for node-pre-gyp https download
node-pre-gyp WARN Tried to download(404): https://storage.googleapis.com/tf-builds/pre-built-binary/napi-v4/1.2.9/CPU-darwin-1.2.9.tar.gz
node-pre-gyp WARN Pre-built binaries not found for @tensorflow/tfjs-node@1.2.9 and node@12.9.0 (node-v72 ABI, unknown) (falling back to source compile with node-gyp)
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.

gyp: No Xcode or CLT version detected!
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:344:16)
gyp ERR! stack     at ChildProcess.emit (events.js:209:13)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:272:12)
gyp ERR! System Darwin 19.0.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "configure" "--fallback-to-build" "--module=/Users/username/Documents/Development/AI/Tensorflow/node_modules/@tensorflow/tfjs-node/lib/napi-v4/tfjs_binding.node" "--module_name=tfjs_binding" "--module_path=/Users/username/Documents/Development/AI/Tensorflow/node_modules/@tensorflow/tfjs-node/lib/napi-v4" "--napi_version=4" "--node_abi_napi=napi" "--napi_build_version=4" "--node_napi_label=napi-v4"
gyp ERR! cwd /Users/username/Documents/Development/AI/Tensorflow/node_modules/@tensorflow/tfjs-node
gyp ERR! node -v v12.9.0
gyp ERR! node-gyp -v v5.0.3
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute '/usr/local/bin/node /usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --module=/Users/username/Documents/Development/AI/Tensorflow/node_modules/@tensorflow/tfjs-node/lib/napi-v4/tfjs_binding.node --module_name=tfjs_binding --module_path=/Users/username/Documents/Development/AI/Tensorflow/node_modules/@tensorflow/tfjs-node/lib/napi-v4 --napi_version=4 --node_abi_napi=napi --napi_build_version=4 --node_napi_label=napi-v4' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/Users/username/Documents/Development/AI/Tensorflow/node_modules/node-pre-gyp/lib/util/compile.js:83:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:209:13)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:1021:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)
node-pre-gyp ERR! System Darwin 19.0.0
node-pre-gyp ERR! command "/usr/local/bin/node" "/Users/username/Documents/Development/AI/Tensorflow/node_modules/.bin/node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd /Users/username/Documents/Development/AI/Tensorflow/node_modules/@tensorflow/tfjs-node
node-pre-gyp ERR! node -v v12.9.0
node-pre-gyp ERR! node-pre-gyp -v v0.13.0
node-pre-gyp ERR! not ok

> nodemon@1.19.2 postinstall /Users/username/Documents/Development/AI/Tensorflow/node_modules/nodemon
> node bin/postinstall || exit 0

npm WARN tensorflow@1.0.0 No description
npm WARN tensorflow@1.0.0 No repository field.

added 362 packages from 202 contributors and audited 2419 packages in 11.642s
found 0 vulnerabilities

node-pre-gyp failes to install and 'CPU-darwin-1.2.9.tar.gz' no longer seems to exist, so I get an 404 error.

Also this question if probably somewhat of a duplicate to this question:
Cannot import @tensorflow/tfjs-node in nodejs

EDIT: Tried to downgrade to @tensorflow/tfjs-node@1.2.8, but the error is still there:

CPU-darwin-1.2.8.tar.gz
* Downloading libtensorflow
[==============================] 10642013/bps 100% 0.0s
* Building TensorFlow Node.js bindings
node-pre-gyp install failed with error: Error: Command failed: node-pre-gyp install --fallback-to-build
node-pre-gyp WARN Using needle for node-pre-gyp https download
node-pre-gyp WARN Tried to download(404): https://storage.googleapis.com/tf-builds/pre-built-binary/napi-v4/1.2.8/tfjs_binding-v1.2.8-node-v72-darwin-x64.tar.gz
node-pre-gyp WARN Pre-built binaries not found for @tensorflow/tfjs-node@1.2.8 and node@12.9.0 (node-v72 ABI, unknown) (falling back to source compile with node-gyp)

Body:
I had the same issue on MacOS 10.15 when installing 1.5.2.

CPU-darwin-1.5.2.tar.gz
* Downloading libtensorflow
[==============================] 15666967/bps 100% 0.0s
* Building TensorFlow Node.js bindings
node-pre-gyp install failed with error: Error: Command failed: node-pre-gyp install --fallback-to-build
node-pre-gyp WARN Using needle for node-pre-gyp https download
node-pre-gyp WARN Tried to download(404): https://storage.googleapis.com/tf-builds/pre-built-binary/napi-v5/1.5.2/CPU-darwin-1.5.2.tar.gz
node-pre-gyp WARN Pre-built binaries not found for @tensorflow/tfjs-node@1.5.2 and node@12.15.0 (node-v72 ABI, unknown) (falling back to source compile with node-gyp)

https://www.npmjs.com/package/@tensorflow/tfjs-node#windows--mac-os-x-requires-python-27

You have to be using python 2.7 when attempting the install. If you aren't you will get a similar error to that you posted, I was in a python3 venv and thus got this error; falling back to 2.7 solved the problem.


问:
c++ std::enable_if .... else?
```<code>#include <stdio.h>
#include <type_traits>

void print()
{
    printf("cheers from print !\n");
}

class A
{
  public:
  void print()
  {
      printf("cheers from A !");
  }
};

template<typename Function>
typename std::enable_if< std::is_function<
                                typename std::remove_pointer<Function>::type >::value,
                                void >::type
run(Function f)
{
    f();
}

template<typename T>
typename std::enable_if< !std::is_function<
                                typename std::remove_pointer<T>::type >::value,
                                void >::type
run(T& t)
{
    t.print();
}

int main()
{
    run(print);

    A a;
    run(a);

    return 0;
}
</code>```

The code above compiles and print as expected:

cheers from print ! cheers from A !

what I would like to express is : "if the template is function then apply this function, else ...". Or in another formulation : having a version of the function for function templates, and a default version for non function templates.

so, this part seems somehow redundant, and could be "replaced" by a "else" condition :

```<code>template<typename T>
typename std::enable_if< !std::is_function<
                                typename std::remove_pointer<T>::type >::value,
                                void >::type
run(T& t)
</code>```

would this exists ?

答:
You can use the tag dispatch mechanism if you are limited to using C++11.

```<code>namespace detail
{
   template<typename Function>
   void run(std::true_type, Function& f)
   {
      f();
   }

   template<typename Object>
   void run(std::false_type, Object& o)
   {
      o.print();
   }

} // namespace detail

template<typename T>
void run(T& t)
{
   constexpr bool t_is_a_function =
      std::is_function<typename std::remove_pointer<T>::type >::value;
   using tag = std::integral_constant<bool, t_is_a_function>;
   detail::run(tag{}, t);
}
</code>```

Working example.

Title: c++ std::enable_if .... else?

Body:
#include <stdio.h>
#include <type_traits>

void print()
{
    printf("cheers from print !\n");
}

class A
{
  public:
  void print()
  {
      printf("cheers from A !");
  }
};

template<typename Function>
typename std::enable_if< std::is_function<
                                typename std::remove_pointer<Function>::type >::value,
                                void >::type
run(Function f)
{
    f();
}

template<typename T>
typename std::enable_if< !std::is_function<
                                typename std::remove_pointer<T>::type >::value,
                                void >::type
run(T& t)
{
    t.print();
}

int main()
{
    run(print);

    A a;
    run(a);

    return 0;
}

The code above compiles and print as expected:

cheers from print ! cheers from A !

what I would like to express is : "if the template is function then apply this function, else ...". Or in another formulation : having a version of the function for function templates, and a default version for non function templates.

so, this part seems somehow redundant, and could be "replaced" by a "else" condition :

template<typename T>
typename std::enable_if< !std::is_function<
                                typename std::remove_pointer<T>::type >::value,
                                void >::type
run(T& t)

would this exists ?

Body:
You can use the tag dispatch mechanism if you are limited to using C++11.

namespace detail
{
   template<typename Function>
   void run(std::true_type, Function& f)
   {
      f();
   }

   template<typename Object>
   void run(std::false_type, Object& o)
   {
      o.print();
   }

} // namespace detail

template<typename T>
void run(T& t)
{
   constexpr bool t_is_a_function =
      std::is_function<typename std::remove_pointer<T>::type >::value;
   using tag = std::integral_constant<bool, t_is_a_function>;
   detail::run(tag{}, t);
}

Working example.


问:
jQuery selector is selecting all input types of submit
I was working with the jquery-3.4.1 when I came across this strange behavior of the jquery  selector.
The html section of the particular submit button is as follows:

```<code><input type="submit" id="submit">
</code>```

Initially, I used the following code to select the only submit button on my page. But, it didn't work.

```<code>$('submit').on('click', function(e){
        e.preventDefault();
        alert('stopped');
    })
</code>```

Then, I tried to be more specific and used the following code to select that submit button on the basis of an id.

```<code>$('#submit').on('click', function(e){
        e.preventDefault();
        alert('stopped');
    })
</code>```

Once again, the results were the same. Then I selected all the submit buttons on the page and the code started working. The code is as follows:

```<code>$(':submit').on('click', function(e){
        e.preventDefault();
        alert('stopped');
    })
</code>```

Now, my question is that why this piece of code worked and the others were not working ? Is there anything wrong with the code ? Or was this because I used the same id as the input type ?

答:
```<code>$('submit').on('click', function(e){
        e.preventDefault();
        alert('stopped');
    })
</code>```

in this one you should use # from id or . for class
but it's best to use class for you select like this

```<code>$('.submit-form').on('click', function(e){
        e.preventDefault();
        alert('stopped');
    })

<input type="submit" class="submit-form" id="submit">
</code>```

and in your code just on tag should have id with name submit
because id name is unique

Body:
I was working with the jquery-3.4.1 when I came across this strange behavior of the jquery  selector.
The html section of the particular submit button is as follows:

<input type="submit" id="submit">

Initially, I used the following code to select the only submit button on my page. But, it didn't work.

$('submit').on('click', function(e){
        e.preventDefault();
        alert('stopped');
    })

Then, I tried to be more specific and used the following code to select that submit button on the basis of an id.

$('#submit').on('click', function(e){
        e.preventDefault();
        alert('stopped');
    })

Once again, the results were the same. Then I selected all the submit buttons on the page and the code started working. The code is as follows:

$(':submit').on('click', function(e){
        e.preventDefault();
        alert('stopped');
    })

Now, my question is that why this piece of code worked and the others were not working ? Is there anything wrong with the code ? Or was this because I used the same id as the input type ?

Body:
$('submit').on('click', function(e){
        e.preventDefault();
        alert('stopped');
    })

in this one you should use # from id or . for class
but it's best to use class for you select like this

$('.submit-form').on('click', function(e){
        e.preventDefault();
        alert('stopped');
    })

<input type="submit" class="submit-form" id="submit">

and in your code just on tag should have id with name submit
because id name is unique


问:
Laravel Slug Duplicate
when i trying to create post with the same slug it create post normally also in update the same problem
in this case i'v duplicate slugs for post

i search a lot about this problem but i didn't get any answers

any idea to solve this problem ?

Model

```<code>protected $fillable = [
    'title', 'slug', 'body',
];
</code>```

Controller

```<code>    public function slug($string, $separator = '-') {
    if (is_null($string)) {
        return "";
    }

    $string = trim($string);

    $string = mb_strtolower($string, "UTF-8");;

    $string = preg_replace("/[^a-z0-9_\sءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]#u/", "", $string);

    $string = preg_replace("/[\s-]+/", " ", $string);

    $string = preg_replace("/[\s_]/", $separator, $string);

    return $string;
}
public function store(Request $request)
{
    $this->validate($request, array(
        'title'         => 'required|max:255',
        'slug'          => 'required|min:3|max:255|unique:posts',
        'body'          => 'required',
    ));
    $post = new Post;
    $post->title = $request->input('title');
    $post->slug = $this->slug($request->slug);
    $post->body = $request->input('body');
    $post->save();

    return redirect('admin/posts')->with('success', 'post is successfully saved');
}
    public function update(Request $request, $id)
{
    if ($request->isMethod('get'))
        return view('content.admin.post.index', ['url' => Post::find($id)]);
    else {
        $rules = [
            'title'         => 'required|max:255',
            'slug'          => 'required|min:3|max:255|unique:posts,slug,{$post->slug},slug',
            'body'          => 'required',
            ];
        $this->validate($request, $rules);
        $post = Post::find($id);

        $post->title = $request->title;
        $post->slug = $this->slug($request->slug);
        $post->body = $request->body;

        $post->save();

        return redirect('/admin/posts');
    }
}
</code>```

答:
Preform your transformations on the slug field before passing it to the validator.

```<code>public function store(Request $request)
{
    $request->slug = $this->slug($request->slug);
    $this->validate($request, array(
        'title'         => 'required|max:255',
        'slug'          => 'required|min:3|max:255|unique:posts',
        'body'          => 'required',
    ));
    $post = new Post;
    $post->title = $request->input('title');
    $post->slug = $request->input('slug');
    $post->body = $request->input('body');
    $post->save();
    return redirect('admin/posts')->with('success', 'post is successfully saved');
}
</code>```

Title: Laravel Slug Duplicate

Body:
when i trying to create post with the same slug it create post normally also in update the same problem
in this case i'v duplicate slugs for post

i search a lot about this problem but i didn't get any answers

any idea to solve this problem ?

Model

protected $fillable = [
    'title', 'slug', 'body',
];

Controller

    public function slug($string, $separator = '-') {
    if (is_null($string)) {
        return "";
    }

    $string = trim($string);

    $string = mb_strtolower($string, "UTF-8");;

    $string = preg_replace("/[^a-z0-9_\sءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]#u/", "", $string);

    $string = preg_replace("/[\s-]+/", " ", $string);

    $string = preg_replace("/[\s_]/", $separator, $string);

    return $string;
}
public function store(Request $request)
{
    $this->validate($request, array(
        'title'         => 'required|max:255',
        'slug'          => 'required|min:3|max:255|unique:posts',
        'body'          => 'required',
    ));
    $post = new Post;
    $post->title = $request->input('title');
    $post->slug = $this->slug($request->slug);
    $post->body = $request->input('body');
    $post->save();

    return redirect('admin/posts')->with('success', 'post is successfully saved');
}
    public function update(Request $request, $id)
{
    if ($request->isMethod('get'))
        return view('content.admin.post.index', ['url' => Post::find($id)]);
    else {
        $rules = [
            'title'         => 'required|max:255',
            'slug'          => 'required|min:3|max:255|unique:posts,slug,{$post->slug},slug',
            'body'          => 'required',
            ];
        $this->validate($request, $rules);
        $post = Post::find($id);

        $post->title = $request->title;
        $post->slug = $this->slug($request->slug);
        $post->body = $request->body;

        $post->save();

        return redirect('/admin/posts');
    }
}

Body:
Preform your transformations on the slug field before passing it to the validator.

public function store(Request $request)
{
    $request->slug = $this->slug($request->slug);
    $this->validate($request, array(
        'title'         => 'required|max:255',
        'slug'          => 'required|min:3|max:255|unique:posts',
        'body'          => 'required',
    ));
    $post = new Post;
    $post->title = $request->input('title');
    $post->slug = $request->input('slug');
    $post->body = $request->input('body');
    $post->save();
    return redirect('admin/posts')->with('success', 'post is successfully saved');
}


问:
Getting names from text file shifts names 1 place to the left (in array)
I was trying to solve problem 22 of Euler Project. Description of what I'm trying to solve is here:
https://projecteuler.net/problem=22

Where's the problem?: I've got the names from the text file, put them on one string,
edited the string so that the names are separated by one space.
After getting those names on an array of Strings, I sort them. After finishing the program and getting the result wrong, I started testing different parts of the program and notice that the name "COLIN", which by eulerproject page is said to be the 938th, is 937th on my array. I can't seem to get why is it happening and how to fix this. Help would be much appreciated.

Here is the code:

```<code>package Project022;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class NameScore {
    private long scoreSum;

    private LinkedList<String> allNames;

    private String[] sortedNames;
    private int[] nameScores;

    public NameScore(){
        scoreSum = 0;
        allNames = new LinkedList<>();
        getNames();
    }
    private void getNames(){
        List<String> content = null;
        File names;
        // read "names.txt" file and put all the names in one line(not effective when line
        // length surpasses String maximum character range(2^31 - 1) but is good enough for us
        // for now)
        try {
            names = new File("Project022\\names.txt");
            content = Files.readAllLines(Paths.get(names.getPath()), StandardCharsets.US_ASCII);
        } catch (Exception e){
            System.out.println("something went wrong while getting the file");
        }
        assert content != null;

        //replace (",") with a space ( )
        String filtered = content.get(0).replaceAll("\",\"", " ");

        //then remove first and last (")
        filtered = filtered.substring(1, filtered.length() - 1);

        //declare "tempName" as a helper string
        StringBuilder tempName = new StringBuilder();

        //get every name and put it on the LinkedList
        for (int i = 0; i < filtered.length(); i++) {
            if (filtered.charAt(i) != ' '){
                tempName.append(filtered.charAt(i));
            } else {
                allNames.add(tempName.toString().trim());
                tempName = new StringBuilder();
            }
        }

        //now we use an pre defined array since it is faster.
        sortedNames = new String[allNames.size()];

        for (int i = 0; i < sortedNames.length; i++) {
            sortedNames[i] = allNames.get(i);
        }

        //make the new array worthy of its name
        Arrays.sort(sortedNames);

        System.out.println(sortedNames[937]);

        System.out.println(Arrays.asList(sortedNames) + "\n" + sortedNames.length);
    }

    public void calculate(){
        //we set the score for each name
        nameScores = new int[sortedNames.length];

        //
        for (int i = 0; i < nameScores.length; i++) {
            setScore(sortedNames[i], i + 1);
        }

        for (int i = 0; i < nameScores.length; i++) {
            scoreSum += nameScores[i];
        }
    }
    private void setScore(String name, int n) {
        int sc = 0;
        for (int i = 0; i < name.length(); i++) {
            sc += (int)name.toUpperCase().charAt(i) - 'A' + 1;
        }
        sc *= n;
        nameScores[n-1] = sc;
    }
    @Override
    public String toString(){ return "the score of all names is: " + scoreSum; }

    public static void main(String[] args) {
        NameScore name = new NameScore();
        name.calculate();
        System.out.println(name);
    }
}
</code>```

What I've ruled out as a problem:

the setScore() method which gives a score for every name, because I tested it with examples by hand and by program and got same results.

the calculate() method, since what it does is gets the score for each name and adds to the total sum.

答:
This works for me.

Path p = Paths.get("p022_names.txt");
try {
    List<String> lines = Files.readAllLines(p); // throws java.io.IOException
    System.out.println(lines.size()); // Only one line in file.

    // Remove all " (double quotes) characters.
    String tmp = lines.get(0).replaceAll("\"", "");

    String[] names = tmp.split(",");
    System.out.println(names.length);
    Arrays.sort(names);

    // Test against example given in problem description.
    System.out.println(names[937]); // Should be COLIN
    char[] lett = names[937].toCharArray();
    int sigma = 0;
    for (int k = 0; k < lett.length; k++) {
        sigma += lett[k] - 'A' + 1; // Since only uppercase letters in file.
    }
    int score = sigma * (937 + 1);
    System.out.println(score); // Should be 49714

    // Now obtain answer, i.e. the total of all the name scores in the file.
    int total = 0;
    for (int i = 0; i < names.length; i++) {
        char[] letters = names[i].toCharArray();
        int sum = 0;
        for (int j = 0; j < letters.length; j++) {
            sum += letters[j] - 'A' + 1;
        }
        total += sum * (i + 1);
    }
    System.out.println(total);
}
catch (IOException xIo) {
    xIo.printStackTrace();
}
```

<p>Output obtained when running above code is as follows.</p>

```1
5163
COLIN
49714
871198282
```

Body:
I was trying to solve problem 22 of Euler Project. Description of what I'm trying to solve is here:
https://projecteuler.net/problem=22

Where's the problem?: I've got the names from the text file, put them on one string,
edited the string so that the names are separated by one space.
After getting those names on an array of Strings, I sort them. After finishing the program and getting the result wrong, I started testing different parts of the program and notice that the name "COLIN", which by eulerproject page is said to be the 938th, is 937th on my array. I can't seem to get why is it happening and how to fix this. Help would be much appreciated.

Here is the code:

package Project022;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class NameScore {
    private long scoreSum;

    private LinkedList<String> allNames;

    private String[] sortedNames;
    private int[] nameScores;

    public NameScore(){
        scoreSum = 0;
        allNames = new LinkedList<>();
        getNames();
    }
    private void getNames(){
        List<String> content = null;
        File names;
        // read "names.txt" file and put all the names in one line(not effective when line
        // length surpasses String maximum character range(2^31 - 1) but is good enough for us
        // for now)
        try {
            names = new File("Project022\\names.txt");
            content = Files.readAllLines(Paths.get(names.getPath()), StandardCharsets.US_ASCII);
        } catch (Exception e){
            System.out.println("something went wrong while getting the file");
        }
        assert content != null;

        //replace (",") with a space ( )
        String filtered = content.get(0).replaceAll("\",\"", " ");

        //then remove first and last (")
        filtered = filtered.substring(1, filtered.length() - 1);

        //declare "tempName" as a helper string
        StringBuilder tempName = new StringBuilder();

        //get every name and put it on the LinkedList
        for (int i = 0; i < filtered.length(); i++) {
            if (filtered.charAt(i) != ' '){
                tempName.append(filtered.charAt(i));
            } else {
                allNames.add(tempName.toString().trim());
                tempName = new StringBuilder();
            }
        }

        //now we use an pre defined array since it is faster.
        sortedNames = new String[allNames.size()];

        for (int i = 0; i < sortedNames.length; i++) {
            sortedNames[i] = allNames.get(i);
        }

        //make the new array worthy of its name
        Arrays.sort(sortedNames);

        System.out.println(sortedNames[937]);

        System.out.println(Arrays.asList(sortedNames) + "\n" + sortedNames.length);
    }

    public void calculate(){
        //we set the score for each name
        nameScores = new int[sortedNames.length];

        //
        for (int i = 0; i < nameScores.length; i++) {
            setScore(sortedNames[i], i + 1);
        }

        for (int i = 0; i < nameScores.length; i++) {
            scoreSum += nameScores[i];
        }
    }
    private void setScore(String name, int n) {
        int sc = 0;
        for (int i = 0; i < name.length(); i++) {
            sc += (int)name.toUpperCase().charAt(i) - 'A' + 1;
        }
        sc *= n;
        nameScores[n-1] = sc;
    }
    @Override
    public String toString(){ return "the score of all names is: " + scoreSum; }

    public static void main(String[] args) {
        NameScore name = new NameScore();
        name.calculate();
        System.out.println(name);
    }
}

What I've ruled out as a problem:

the setScore() method which gives a score for every name, because I tested it with examples by hand and by program and got same results.

the calculate() method, since what it does is gets the score for each name and adds to the total sum.

Body:
This works for me.

Path p = Paths.get("p022_names.txt");
try {
    List<String> lines = Files.readAllLines(p); // throws java.io.IOException
    System.out.println(lines.size()); // Only one line in file.

    // Remove all " (double quotes) characters.
    String tmp = lines.get(0).replaceAll("\"", "");

    String[] names = tmp.split(",");
    System.out.println(names.length);
    Arrays.sort(names);

    // Test against example given in problem description.
    System.out.println(names[937]); // Should be COLIN
    char[] lett = names[937].toCharArray();
    int sigma = 0;
    for (int k = 0; k < lett.length; k++) {
        sigma += lett[k] - 'A' + 1; // Since only uppercase letters in file.
    }
    int score = sigma * (937 + 1);
    System.out.println(score); // Should be 49714

    // Now obtain answer, i.e. the total of all the name scores in the file.
    int total = 0;
    for (int i = 0; i < names.length; i++) {
        char[] letters = names[i].toCharArray();
        int sum = 0;
        for (int j = 0; j < letters.length; j++) {
            sum += letters[j] - 'A' + 1;
        }
        total += sum * (i + 1);
    }
    System.out.println(total);
}
catch (IOException xIo) {
    xIo.printStackTrace();
}

Output obtained when running above code is as follows.

1
5163
COLIN
49714
871198282


问:
Why doesn't Pandas use default python 'and' and 'or'?
I can't understand why Pandas doesn't overload/allow the use of the "and" and "or" operators built in to python when comparing dataframes</p>

```<code>import pandas as pd

In [4]: d = {'a':[True,False], 'b':[False,False]}

In [5]: x = pd.DataFrame(d)

In [6]: x['a'] & x['b']
Out[6]:
0    False
1    False
dtype: bool

In [7]: x['a'] and x['b']
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-0ee6588ad92b> in <module>
----> 1 x['a'] and x['b']

/usr/local/lib/python3.7/site-packages/pandas/core/generic.py in __nonzero__(self)
   1477     def __nonzero__(self):
   1478         raise ValueError(
-> 1479             f"The truth value of a {type(self).__name__} is ambiguous. "
   1480             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1481         )

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

In [8]:
</code>```

答: It can't. You can't overload those. Overloading would interact poorly with short-circuit semantics, so Python doesn't allow it.</p>

Body:
I can't understand why Pandas doesn't overload/allow the use of the "and" and "or" operators built in to python when comparing dataframes

import pandas as pd

In [4]: d = {'a':[True,False], 'b':[False,False]}

In [5]: x = pd.DataFrame(d)

In [6]: x['a'] & x['b']
Out[6]:
0    False
1    False
dtype: bool

In [7]: x['a'] and x['b']
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-0ee6588ad92b> in <module>
----> 1 x['a'] and x['b']

/usr/local/lib/python3.7/site-packages/pandas/core/generic.py in __nonzero__(self)
   1477     def __nonzero__(self):
   1478         raise ValueError(
-> 1479             f"The truth value of a {type(self).__name__} is ambiguous. "
   1480             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1481         )

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

In [8]:


问:
Align pictures on Powerpoint
I currently am creating a macro that will take a excel file and put it contents into a PowerPoint.
I am having trouble aligning the picture I just copy and pasted from excel into the PowerPoint. Below is the code I am using to paste the picture and keep receiving the error that "The item with the specified name wasn't found." I am wondering if this is because the macro is ran from Excel and not PowerPoint?</p>

```<code>     Sheets("Bay du Nord").Range("E3:P9").CopyPicture _
Appearance:=xlScreen, Format:=xlPicture

Slide2.Select
Slide2.Shapes.Paste.Name = "SamplePic"

Set Shp1 = ActiveSheet.Shapes("Textbox 13")
Set shp2 = ActiveSheet.Shapes("SamplePic")

shp2.Top = Shp1.Top
</code>```

答:
I'm assuming that "TextBox 3" is located on your slide, not on your worksheet, and that you want to align the pasted shape with "TextBox 3" on your slide.  If so, try the following:</p>

```<code>Sheets("Bay du Nord").Range("E3:P9").CopyPicture _
    Appearance:=xlScreen, Format:=xlPicture

Set shp1 = Slide2.Shapes("TextBox 3")

With Slide2
    .Shapes.Paste.Name = "SamplePic"
    With .Shapes(.Shapes.Count)
        .Top = shp1.Top
    End With
End With
</code>```

Title: Align pictures on Powerpoint

Body:
I currently am creating a macro that will take a excel file and put it contents into a PowerPoint.
I am having trouble aligning the picture I just copy and pasted from excel into the PowerPoint. Below is the code I am using to paste the picture and keep receiving the error that "The item with the specified name wasn't found." I am wondering if this is because the macro is ran from Excel and not PowerPoint?

     Sheets("Bay du Nord").Range("E3:P9").CopyPicture _
Appearance:=xlScreen, Format:=xlPicture

Slide2.Select
Slide2.Shapes.Paste.Name = "SamplePic"

Set Shp1 = ActiveSheet.Shapes("Textbox 13")
Set shp2 = ActiveSheet.Shapes("SamplePic")

shp2.Top = Shp1.Top

Body:
I'm assuming that "TextBox 3" is located on your slide, not on your worksheet, and that you want to align the pasted shape with "TextBox 3" on your slide.  If so, try the following:

Sheets("Bay du Nord").Range("E3:P9").CopyPicture _
    Appearance:=xlScreen, Format:=xlPicture

Set shp1 = Slide2.Shapes("TextBox 3")

With Slide2
    .Shapes.Paste.Name = "SamplePic"
    With .Shapes(.Shapes.Count)
        .Top = shp1.Top
    End With
End With


问:
With React prop-types is it possible to validate on whether a string contains something?
I have a button component with a colour prop. Colour prop can be either 'primary', 'secondary' or a hex colour e.g '#0000ff'. Of course colour: PropTypes.string will do but ideally I need to check against random strings. Is something like below possible?

```<code>Button.propTypes = {
  colour: PropTypes.oneOf(['primary', 'secondary', PropTypes.string.includes('#')]),
};
</code>```

Or a function to check that string is up to 7 characters long with first character being '#'?

答:
You can write your own validator.

See the React docs for more details.

```<code>Button.propTypes = {
  colour: function(props, propName, componentName) {
    if (props[propName] !== 'primary' &&
        props[propName] !== 'secondary' &&
        !/^#[0-9a-fA-F]{6}$/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Must be a valid color code.'
      );
    }
  }
}
</code>```

Body:
I have a button component with a colour prop. Colour prop can be either 'primary', 'secondary' or a hex colour e.g '#0000ff'. Of course colour: PropTypes.string will do but ideally I need to check against random strings. Is something like below possible?

Button.propTypes = {
  colour: PropTypes.oneOf(['primary', 'secondary', PropTypes.string.includes('#')]),
};

Or a function to check that string is up to 7 characters long with first character being '#'?

Body:
You can write your own validator.

See the React docs for more details.

Button.propTypes = {
  colour: function(props, propName, componentName) {
    if (props[propName] !== 'primary' &&
        props[propName] !== 'secondary' &&
        !/^#[0-9a-fA-F]{6}$/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Must be a valid color code.'
      );
    }
  }
}


问:
What iptables knows about pods?
Let's say we have 2 Nodes in a cluster.

Node A has 1 replica of a pod, Node B has 2 replicas. According to this talk (YouTube video with a time tag) from Google Cloud engineers, a request which was routed to Node A might be rerouted to the Node B by iptables which is inside the Node A. I have several questions regarding this behavior:

What information iptables of Node A knows about replicas of a pod outside of it? How does it know where to send the traffic?

Can it be that iptables of the Node B reroutes this request to Node C? If so, then will the egress traffic go back to the Node B -> Node A -> Client?

答: I think you might be mixing up two subsystems, service proxies and CNI. CNI is first, it’s a plug-in based system that sets up the routing rules across all your nodes so that the network appears flat. A pod IP will work like normal from any node. Exactly how that happens varies by plugin, Calico uses BGP between the nodes. Then there’s the service proxies, usually implemented using iptables though also somewhat pluggable. Those define the service IP -> endpoint IP (read: pod IP) load balancing. But the actual routing is handled by whatever your CNI plugin set up. There’s a lot of special modes and cases but that’s the basic overview.</p>

Title: What iptables knows about pods?


问:
Changing the colour of text when printing
I am currently designing a simple game and I am trying to change the colour of specific things I am printing. Already I have downloaded the colorama module and ran my code using a sample I've found online, but this doesn't work (I'll tell the details later). I am aware of a setting within the Python options but this affects the whole text not specific sections. If this helps my computer runs Windows and I am running Python 3.8. Here is the setup code, and then a few lines after is the code I have in a separate file. A few lines after that is the output:</p>

```<code>from setuptools import setup, find_packages

name = 'colorama'
version = '0.1'

def get_long_description(filename):
    readme = join(dirname(__file__), filename)
    return open(readme).read()

setup(
    name=name,
    version=version,
    description="Cross-platform colored terminal text.",
    long_description=get_long_description('README.txt'),
    keywords='color colour terminal text ansi windows crossplatform xplatform',
    author='Jonathan Hartley',
    author_email='tartley@tartley.com',
    url='http://code.google.com/p/colorama/',
    license='BSD',
    packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
    include_package_data=True,
    zip_safe=True,
    install_requires=[
      # -*- Extra requirements: -*-
    ],
    entry_points="""
# -*- Entry points: -*-
    """,
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.6',
        'Topic :: Terminals',
    ]
    # see classifiers http://pypi.python.org/pypi?%3Aaction=list_classifiers
)

import colorama
from colorama import Fore, Style
print(Fore.BLUE + "Hello World")

[34mHello World
</code>```

答:
you need to call init() somewhere after you import colorama and before you print a string with a color. for example:

```<code>import colorama
from colorama import Fore, Style
init()
print(Fore.BLUE + "Hello World")
</code>```

Body:
I am currently designing a simple game and I am trying to change the colour of specific things I am printing. Already I have downloaded the colorama module and ran my code using a sample I've found online, but this doesn't work (I'll tell the details later). I am aware of a setting within the Python options but this affects the whole text not specific sections. If this helps my computer runs Windows and I am running Python 3.8. Here is the setup code, and then a few lines after is the code I have in a separate file. A few lines after that is the output:

from setuptools import setup, find_packages

name = 'colorama'
version = '0.1'

def get_long_description(filename):
    readme = join(dirname(__file__), filename)
    return open(readme).read()

setup(
    name=name,
    version=version,
    description="Cross-platform colored terminal text.",
    long_description=get_long_description('README.txt'),
    keywords='color colour terminal text ansi windows crossplatform xplatform',
    author='Jonathan Hartley',
    author_email='tartley@tartley.com',
    url='http://code.google.com/p/colorama/',
    license='BSD',
    packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
    include_package_data=True,
    zip_safe=True,
    install_requires=[
      # -*- Extra requirements: -*-
    ],
    entry_points="""
# -*- Entry points: -*-
    """,
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.6',
        'Topic :: Terminals',
    ]
    # see classifiers http://pypi.python.org/pypi?%3Aaction=list_classifiers
)

import colorama
from colorama import Fore, Style
print(Fore.BLUE + "Hello World")

[34mHello World

Body:
you need to call init() somewhere after you import colorama and before you print a string with a color. for example:

import colorama
from colorama import Fore, Style
init()
print(Fore.BLUE + "Hello World")


问:
Woocommerce Product Page: how to change position of 'short description', 'price' and 'variation description'
In a Woocommerce Product Page: how to change position of 'short description', 'price' and 'variation description'?

I need to put the 'Product short description' above the 'Price' and the 'Variation Description' just below the Price.

This is what I have right now:

And this is what I need:

答:
normaly you will find different hooks / different priorities in the templates folder of woocommerce.

In the content-single-product.php inside you will find some comments like:

```<code>   * @hooked woocommerce_template_single_title - 5
   * @hooked woocommerce_template_single_rating - 10
   * @hooked woocommerce_template_single_price - 10
   * @hooked woocommerce_template_single_excerpt - 20
</code>```

To modify create an new ordering in the functions.php of the child theme like this

```<code>remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_title', 5);
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);
add_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 30);
add_action('woocommerce_single_product_summary', 'woocommerce_template_single_title', 20);
</code>```

Body:
normaly you will find different hooks / different priorities in the templates folder of woocommerce.

In the content-single-product.php inside you will find some comments like:

   * @hooked woocommerce_template_single_title - 5
   * @hooked woocommerce_template_single_rating - 10
   * @hooked woocommerce_template_single_price - 10
   * @hooked woocommerce_template_single_excerpt - 20

To modify create an new ordering in the functions.php of the child theme like this

remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_title', 5);
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);
add_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 30);
add_action('woocommerce_single_product_summary', 'woocommerce_template_single_title', 20);


问:
Skip files on button click [tkinter + Python 3.5]
Suppose I have 'n' image files in a directory filedir which I want to view via tkinter console. Now, I want to skip a few files whenever necessary, using a button click event which invokes a function nextFile().

E.g.

```<code>import os

def nextFile():
    global img
    img_2 = process(img)
    return img_2

window = tk.Tk()
window.title("File Viewer")
files = os.listdir(filedir)
button1 = tk.Button(window, text="Browse Files...", fg="black", command=askopenfilename)
button2 = tk.Button(window, text="SELECT", width=50, command=nextFile)
canvas = tk.Canvas(window, width=width, height=height)
button1.pack(side=tk.LEFT)
button2.pack(side=tk.BOTTOM)
canvas.pack()

for f in files:
    img = cv2.cvtColor(cv2.imread(filedir + '/' + f), cv2.COLOR_BGR2RGB)
    photo = ImageTk.PhotoImage(image=Image.fromarray((img))
    canvas.create_image(0, 0, image=photo, anchor=tk.CENTER)

window.mainloop()
</code>```

Any help is appreciated. Thanks!

答:
Here is a simple example using PIL to load the inital image and then use a button and function to load each next image.</p>

```<code>import tkinter as tk
from PIL import ImageTk, Image
import os

path = 'C:/your/file/path/here'

def nextFile():
    # the global is needed to keep track of current index and also keep
    # a reference of the image being displayed so its is not garbage collected.
    global current_ndex, image
    current_ndex += 1
    if current_ndex < len(files):
        img = Image.open('{}/{}'.format(path, files[current_ndex]))
        image = ImageTk.PhotoImage(img)
        # clear the canvas before adding the new image.
        canvas.delete("all")
        canvas.create_image(0, 0, image=image, anchor=tk.CENTER)

my_window = tk.Tk()
my_window.title("File Viewer")
files = os.listdir(path)

current_ndex = 0

button2 = tk.Button(my_window, text="Next", width=50, command=nextFile)
canvas = tk.Canvas(my_window, width=100, height=100)
button2.pack(side=tk.BOTTOM)
canvas.pack()

first_image = files[0]

img = Image.open('{}/{}'.format(path, first_image))
image = ImageTk.PhotoImage(img)
canvas.create_image(0, 0, image=image, anchor=tk.CENTER)
my_window.mainloop()
</code>```

Body:
Suppose I have 'n' image files in a directory filedir which I want to view via tkinter console. Now, I want to skip a few files whenever necessary, using a button click event which invokes a function nextFile().

E.g.

import os

def nextFile():
    global img
    img_2 = process(img)
    return img_2

window = tk.Tk()
window.title("File Viewer")
files = os.listdir(filedir)
button1 = tk.Button(window, text="Browse Files...", fg="black", command=askopenfilename)
button2 = tk.Button(window, text="SELECT", width=50, command=nextFile)
canvas = tk.Canvas(window, width=width, height=height)
button1.pack(side=tk.LEFT)
button2.pack(side=tk.BOTTOM)
canvas.pack()

for f in files:
    img = cv2.cvtColor(cv2.imread(filedir + '/' + f), cv2.COLOR_BGR2RGB)
    photo = ImageTk.PhotoImage(image=Image.fromarray((img))
    canvas.create_image(0, 0, image=photo, anchor=tk.CENTER)

window.mainloop()

Any help is appreciated. Thanks!

Body:
Here is a simple example using PIL to load the inital image and then use a button and function to load each next image.

import tkinter as tk
from PIL import ImageTk, Image
import os

path = 'C:/your/file/path/here'

def nextFile():
    # the global is needed to keep track of current index and also keep
    # a reference of the image being displayed so its is not garbage collected.
    global current_ndex, image
    current_ndex += 1
    if current_ndex < len(files):
        img = Image.open('{}/{}'.format(path, files[current_ndex]))
        image = ImageTk.PhotoImage(img)
        # clear the canvas before adding the new image.
        canvas.delete("all")
        canvas.create_image(0, 0, image=image, anchor=tk.CENTER)

my_window = tk.Tk()
my_window.title("File Viewer")
files = os.listdir(path)

current_ndex = 0

button2 = tk.Button(my_window, text="Next", width=50, command=nextFile)
canvas = tk.Canvas(my_window, width=100, height=100)
button2.pack(side=tk.BOTTOM)
canvas.pack()

first_image = files[0]

img = Image.open('{}/{}'.format(path, first_image))
image = ImageTk.PhotoImage(img)
canvas.create_image(0, 0, image=image, anchor=tk.CENTER)
my_window.mainloop()


问:
tar in Azure Pipelines on Windows agent fails with "Cannot connect to D: resolve failed"
I'm baffled by an error I'm getting from a Windows agent (build worker) on Azure Pipelines.  This task is failing:

```<code>      - task: PowerShell@2
        displayName: 'Unpack source tarball'
        inputs:
          targetType: 'inline'
          script: |
            Set-PSDebug -Trace 1
            tar -zxf $(Pipeline.Workspace)\objconv-$(o.version).tar.gz
</code>```

with this output:

```<code>DEBUG:    3+  >>>> tar -zxf D:\a\1\objconv-2.51.tar.gz
tar (child): Cannot connect to D: resolve failed

gzip: stdin: unexpected end of file
/usr/bin/tar: Child returned status 128
/usr/bin/tar: Error is not recoverable: exiting now
</code>```

"D:\a\1" is the expansion of the $(Pipeline.Workspace) variable.  I'm suspicious of some kind of Unix-software-not-fully-ported-to-Windows issue because tar seems to be identifying itself as "/usr/bin/tar" instead of, I dunno, "C:\Windows\PowerShell-Components\tar.exe", but beyond that I got nothing.

What on earth does "Cannot connect to D: resolve failed" mean and how do I fix the task?

(Full azure-pipelines.yml visible here: https://bitbucket.org/elwoz/objconv/src/trunk/azure-pipelines.yml )

答: I would recommend using the Extract Files task instead of rolling your own. I expect you're seeing an issue with tar expecting Unix-style paths and not being able to handle Windows-style paths.

Body:
I'm baffled by an error I'm getting from a Windows agent (build worker) on Azure Pipelines.  This task is failing:

      - task: PowerShell@2
        displayName: 'Unpack source tarball'
        inputs:
          targetType: 'inline'
          script: |
            Set-PSDebug -Trace 1
            tar -zxf $(Pipeline.Workspace)\objconv-$(o.version).tar.gz

with this output:

DEBUG:    3+  >>>> tar -zxf D:\a\1\objconv-2.51.tar.gz
tar (child): Cannot connect to D: resolve failed

gzip: stdin: unexpected end of file
/usr/bin/tar: Child returned status 128
/usr/bin/tar: Error is not recoverable: exiting now

"D:\a\1" is the expansion of the $(Pipeline.Workspace) variable.  I'm suspicious of some kind of Unix-software-not-fully-ported-to-Windows issue because tar seems to be identifying itself as "/usr/bin/tar" instead of, I dunno, "C:\Windows\PowerShell-Components\tar.exe", but beyond that I got nothing.

What on earth does "Cannot connect to D: resolve failed" mean and how do I fix the task?

(Full azure-pipelines.yml visible here: https://bitbucket.org/elwoz/objconv/src/trunk/azure-pipelines.yml )


问:
Static field initialization order (C#) - can someone explain this snippet?
I am a C++ programmer learning C#. I am currently reading C#4.0 in a Nutshell.

I have come accross this statement/snipet on page 74:

Static field initializers run in the
  order in which the fields are
  declared. The following example
  illustrates this: X is initialized to
  0 and Y is initialized to 3.

```<code>class Foo
{
    public static int X = Y; // 0
    public static int Y = 3; // 3
}
</code>```

I dont understand how X can be assigned the value in Y, without Y being first declared. Am I missing something here?

As an aside, coming from a C++ background, I tend to use the term ctor for constructor - however, I haven't yet come accross the term in C# - is the term ctor also used in the C# world?

[Edit]

A further example on the same page (in the book mentioned earlier) is this:

```<code>class Program
{
    static void Main() { Console.WriteLine (Foo.X); } // 3
}
class Foo
{
    public static Foo Instance = new Foo();
    public static int X = 3;
    Foo() { Console.WriteLine (X); } // 0
}
</code>```

The book states (for the example above):

The example prints 0 followed by 3
  because the field initializer that
  instantiates a Foo executes before X
  is initialized to 3:

I have some further questions w.r.t the examples.

Both examples appear under the section entitled Static constructors and field initialization order however, the code examples dont show a static ctor - atleast, not one that I can easily recognise. I was expecting a static ctor to have the same name as the class, be parameterless and be preceeded by the 'static' keyword. So I dont see how the examples relate to the section heading. What am I missing here?

In the second example, the (non static) ctor prints out the value of X - which had explicitly been assigned the value of 3 in the previous line - and yet, the output printed out is 0. Why?!

答:
Order of declaration isn't important in terms of what's available here. It's not like the case where these are local variables, and a variable is only available after it's declared. The same is true for instance variables - and indeed methods, where a method declared earlier in the source can call one declared later in the source, etc.

However, the order of declaration is important in terms of execution of initializers, which is why you're getting that behaviour. Note that if you change these variables to const, both will take the value 3 - the compiler will work out the required order of evaluation, and will detect if there are any cycles (Which would cause an error). The constants would then be evaluated at compile-time, and the values embedded directly in IL.

For more details about what's valid etc, consult the specification.

As for terminology - I don't usually see the need to abbreviate "constructor" to "ctor", although I think it would be generally understood. I might use that abbreviation for a variable name, for example:

```<code>var ctor = typeof(...).GetConstructor(...);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am a C++ programmer learning C#. I am currently reading C#4.0 in a Nutshell.

I have come accross this statement/snipet on page 74:

Static field initializers run in the
  order in which the fields are
  declared. The following example
  illustrates this: X is initialized to
  0 and Y is initialized to 3.

class Foo
{
    public static int X = Y; // 0
    public static int Y = 3; // 3
}

I dont understand how X can be assigned the value in Y, without Y being first declared. Am I missing something here?

As an aside, coming from a C++ background, I tend to use the term ctor for constructor - however, I haven't yet come accross the term in C# - is the term ctor also used in the C# world?

[Edit]

A further example on the same page (in the book mentioned earlier) is this:

class Program
{
    static void Main() { Console.WriteLine (Foo.X); } // 3
}
class Foo
{
    public static Foo Instance = new Foo();
    public static int X = 3;
    Foo() { Console.WriteLine (X); } // 0
}

The book states (for the example above):

The example prints 0 followed by 3
  because the field initializer that
  instantiates a Foo executes before X
  is initialized to 3:

I have some further questions w.r.t the examples.

Both examples appear under the section entitled Static constructors and field initialization order however, the code examples dont show a static ctor - atleast, not one that I can easily recognise. I was expecting a static ctor to have the same name as the class, be parameterless and be preceeded by the 'static' keyword. So I dont see how the examples relate to the section heading. What am I missing here?

In the second example, the (non static) ctor prints out the value of X - which had explicitly been assigned the value of 3 in the previous line - and yet, the output printed out is 0. Why?!

Body:
Order of declaration isn't important in terms of what's available here. It's not like the case where these are local variables, and a variable is only available after it's declared. The same is true for instance variables - and indeed methods, where a method declared earlier in the source can call one declared later in the source, etc.

However, the order of declaration is important in terms of execution of initializers, which is why you're getting that behaviour. Note that if you change these variables to const, both will take the value 3 - the compiler will work out the required order of evaluation, and will detect if there are any cycles (Which would cause an error). The constants would then be evaluated at compile-time, and the values embedded directly in IL.

For more details about what's valid etc, consult the specification.

As for terminology - I don't usually see the need to abbreviate "constructor" to "ctor", although I think it would be generally understood. I might use that abbreviation for a variable name, for example:

var ctor = typeof(...).GetConstructor(...);


问:
How to toggle class "active" in an accordion
I'm trying to make my accordion behave like in the image bellow, but I'm dont know how I can toggle the "active" class with my jquery code.

The first item ("cashback online") starts as "active", but I want to remove its class when I click in another item.

The image explains very clearly the expected behavior that I want.

My code:

$('.menu').on('click', function() {
  $('.content').hide();
  $(this).find('.content').show();
});

$('.menu').on('click', function(event) {
  $target = $(event.target);
  $target.addClass('active');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sectionThree-container>ul {
  list-style: none;
}

.sectionThree-container>ul p {
  display: none;
}

.sectionThreeOptions>h2 {
  font-family: Poppins;
  font-style: normal;
  font-weight: bold;
  font-size: 22px;
  line-height: 22px;
  color: #4F4F4F;
  margin-left: 22px;
  cursor: pointer;
}

.sectionThreeOptions>h2.active {
  font-family: Poppins;
  font-style: normal;
  font-weight: bold;
  font-size: 30px;
  line-height: 22px;
  color: #222222;
  margin-left: 0;
}

.sectionThree-container .circle {
  width: 32px;
  height: 32px;
  left: 142px;
  top: 2050px;
  background: #FF6B7D;
  color: #fff;
  border-radius: 50%;
  margin: 20px 0 20px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 30px;
}

.sectionThree-container .circle.active {
  width: 60px;
  height: 60px;
  left: 128px;
  top: 1820px;
  background: #EF1247;
  margin-left: -10px;
}

.sectionThree-container>ul>li>p.active {
  margin-bottom: 60px;
}

.sectionThreeOptions {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
}</code>```

1

cashback online

        Ofereça cashback a seus clientes em nossos

        mais de 300 e-commerces parceiros através de

        uma plataforma personalizável

2

cashback offline

        Ofereça cashback em lojas físicas parceiras

        ou em sua própria rede e produtos através de uma

        experiência online e offline

3

recompensas

        Tenha sua própria plataforma de recompensas,

        permitindo que seus usuários acumulem e

        troquem pontos em mais de 50 parceiros

4

gamificação

        Torne a experiência ainda mais imersiva com

        mecânicas de gamificação na sua plataforma

        de fidelização personalizada

```

答:
You can use a single function to do everything you need, don't need two listeners.

Inside the listener/function, use jQuery to select all children from div.sectionThree-container that have class active and remove this class.

Now since you are inside the clicked .menu, this context refer to the clicked menu you want, so just find its ".content" and show it, find h2 and add "active" class, find the circle and add "active" class to it also.

See below, is that what you need?

$('.menu').on('click', function() {
  $(".sectionThree-container .active").removeClass("active")
  $('.sectionThree-container .content').hide();
  let clickedContent = $(this);
  clickedContent.find('.content').show();
  clickedContent.find('h2').addClass('active');
  clickedContent.find('.circle').addClass('active');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sectionThree-container>ul {
  list-style: none;
}

.sectionThree-container>ul p {
  display: none;
}

.sectionThreeOptions>h2 {
  font-family: Poppins;
  font-style: normal;
  font-weight: bold;
  font-size: 22px;
  line-height: 22px;
  color: #4F4F4F;
  margin-left: 22px;
  cursor: pointer;
}

.sectionThreeOptions>h2.active {
  font-family: Poppins;
  font-style: normal;
  font-weight: bold;
  font-size: 30px;
  line-height: 22px;
  color: #222222;
  margin-left: 0;
}

.sectionThree-container .circle {
  width: 32px;
  height: 32px;
  left: 142px;
  top: 2050px;
  background: #FF6B7D;
  color: #fff;
  border-radius: 50%;
  margin: 20px 0 20px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 30px;
}

.sectionThree-container .circle.active {
  width: 60px;
  height: 60px;
  left: 128px;
  top: 1820px;
  background: #EF1247;
  margin-left: -10px;
}

.sectionThree-container>ul>li>p.active {
  margin-bottom: 60px;
}

.sectionThreeOptions {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
}</code>```

1

cashback online

        Ofereça cashback a seus clientes em nossos

        mais de 300 e-commerces parceiros através de

        uma plataforma personalizável

2

cashback offline

        Ofereça cashback em lojas físicas parceiras

        ou em sua própria rede e produtos através de uma

        experiência online e offline

3

recompensas

        Tenha sua própria plataforma de recompensas,

        permitindo que seus usuários acumulem e

        troquem pontos em mais de 50 parceiros

4

gamificação

        Torne a experiência ainda mais imersiva com

        mecânicas de gamificação na sua plataforma

        de fidelização personalizada

```

If you want to reduce code lines, you can make some of the jQuery selections in a single statement, such as clickedContent.find("h2, .circle").addClass('active')

Body:
I'm trying to make my accordion behave like in the image bellow, but I'm dont know how I can toggle the "active" class with my jquery code.

The first item ("cashback online") starts as "active", but I want to remove its class when I click in another item.

The image explains very clearly the expected behavior that I want.

My code:

$('.menu').on('click', function() {
  $('.content').hide();
  $(this).find('.content').show();
});

$('.menu').on('click', function(event) {
  $target = $(event.target);
  $target.addClass('active');
});

.sectionThree-container>ul {
  list-style: none;
}

.sectionThree-container>ul p {
  display: none;
}

.sectionThreeOptions>h2 {
  font-family: Poppins;
  font-style: normal;
  font-weight: bold;
  font-size: 22px;
  line-height: 22px;
  color: #4F4F4F;
  margin-left: 22px;
  cursor: pointer;
}

.sectionThreeOptions>h2.active {
  font-family: Poppins;
  font-style: normal;
  font-weight: bold;
  font-size: 30px;
  line-height: 22px;
  color: #222222;
  margin-left: 0;
}

.sectionThree-container .circle {
  width: 32px;
  height: 32px;
  left: 142px;
  top: 2050px;
  background: #FF6B7D;
  color: #fff;
  border-radius: 50%;
  margin: 20px 0 20px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 30px;
}

.sectionThree-container .circle.active {
  width: 60px;
  height: 60px;
  left: 128px;
  top: 1820px;
  background: #EF1247;
  margin-left: -10px;
}

.sectionThree-container>ul>li>p.active {
  margin-bottom: 60px;
}

.sectionThreeOptions {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
}

1

cashback online

        Ofereça cashback a seus clientes em nossos

        mais de 300 e-commerces parceiros através de

        uma plataforma personalizável

2

cashback offline

        Ofereça cashback em lojas físicas parceiras

        ou em sua própria rede e produtos através de uma

        experiência online e offline

3

recompensas

        Tenha sua própria plataforma de recompensas,

        permitindo que seus usuários acumulem e

        troquem pontos em mais de 50 parceiros

4

gamificação

        Torne a experiência ainda mais imersiva com

        mecânicas de gamificação na sua plataforma

        de fidelização personalizada

Body:
You can use a single function to do everything you need, don't need two listeners.

Inside the listener/function, use jQuery to select all children from div.sectionThree-container that have class active and remove this class.

Now since you are inside the clicked .menu, this context refer to the clicked menu you want, so just find its ".content" and show it, find h2 and add "active" class, find the circle and add "active" class to it also.

See below, is that what you need?

$('.menu').on('click', function() {
  $(".sectionThree-container .active").removeClass("active")
  $('.sectionThree-container .content').hide();
  let clickedContent = $(this);
  clickedContent.find('.content').show();
  clickedContent.find('h2').addClass('active');
  clickedContent.find('.circle').addClass('active');
});

.sectionThree-container>ul {
  list-style: none;
}

.sectionThree-container>ul p {
  display: none;
}

.sectionThreeOptions>h2 {
  font-family: Poppins;
  font-style: normal;
  font-weight: bold;
  font-size: 22px;
  line-height: 22px;
  color: #4F4F4F;
  margin-left: 22px;
  cursor: pointer;
}

.sectionThreeOptions>h2.active {
  font-family: Poppins;
  font-style: normal;
  font-weight: bold;
  font-size: 30px;
  line-height: 22px;
  color: #222222;
  margin-left: 0;
}

.sectionThree-container .circle {
  width: 32px;
  height: 32px;
  left: 142px;
  top: 2050px;
  background: #FF6B7D;
  color: #fff;
  border-radius: 50%;
  margin: 20px 0 20px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 30px;
}

.sectionThree-container .circle.active {
  width: 60px;
  height: 60px;
  left: 128px;
  top: 1820px;
  background: #EF1247;
  margin-left: -10px;
}

.sectionThree-container>ul>li>p.active {
  margin-bottom: 60px;
}

.sectionThreeOptions {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="sectionThree-container">
  <ul>
    <li class="menu">
      <div class="sectionThreeOptions">
        <div class="circle active">1</div>
        <h2 class="active">cashback online</h2>
      </div>
      <p class="content" style="display: inline">
        Ofereça cashback a seus clientes em nossos </br>
        mais de 300 e-commerces parceiros através de </br>
        uma plataforma personalizável
      </p>
    </li>
    <li class="menu">
      <div class="sectionThreeOptions">
        <div class="circle">2</div>
        <h2>cashback offline</h2>
      </div>
      <p class="content">
        Ofereça cashback em lojas físicas parceiras </br>
        ou em sua própria rede e produtos através de uma </br>
        experiência online e offline
      </p>
    </li>
    <li class="menu">
      <div class="sectionThreeOptions">
        <div class="circle">3</div>
        <h2>recompensas</h2>
      </div>
      <p class="content">
        Tenha sua própria plataforma de recompensas,</br>
        permitindo que seus usuários acumulem e </br>
        troquem pontos em mais de 50 parceiros
      </p>
    </li>
    <li class="menu">
      <div class="sectionThreeOptions">
        <div class="circle">4</div>
        <h2>gamificação</h2>
      </div>
      <p class="content">
        Torne a experiência ainda mais imersiva com </br>
        mecânicas de gamificação na sua plataforma </br>
        de fidelização personalizada
      </p>
    </li>
  </ul>

  <div class="sectionThreeOptionsImage">
    <img src="images/imagemUm.png" id="sectionThreeImage" alt="">
  </div>
</div>
</div>

If you want to reduce code lines, you can make some of the jQuery selections in a single statement, such as clickedContent.find("h2, .circle").addClass('active')


问:
Split text file after specific line in python
I'm trying to write a code to read Fresco files and plot the results. Fresco produces one big file that looks something like this

```<code>theta  sigma
1        0.1
2        0.1
3        0.2
...
END
some text...
theta   sigma
1        0.3
2        0.2
...
END
more data...
</code>```

I want to produce a new file after every 'END' to analyze the data separately. I tried some of the solutions proposed to other answers like

```<code>with open('fort.16', 'r') as infile, open('output_fort.16', 'w') as outfile:
copy= False
for line in infile:
    if line.strip() == '# legend':
        copy = True
        continue
    elif line.strip()=='End':
        copy = False
    elif copy:
        outfile.write(line)
</code>```

but this is not what i need.
Im fairly new to python so any help is much appreciated.

答:
```<code>fp = open("random.txt")

data = []
temp = []

for i, line in enumerate(fp):
    if line.strip() == "END":
        new_file = open("file"+str(i)+".txt", "a+")
        for i in temp:
            new_file.write(i+"\n")
        temp = []
        new_file.close()
        continue
    temp.append(line.strip())

fp.close()
print(data)
</code>```

Here you go this one, creates a new file everytime. The file name is file and the index of where ever the "END" line was found. :)

Body:
I'm trying to write a code to read Fresco files and plot the results. Fresco produces one big file that looks something like this

theta  sigma
1        0.1
2        0.1
3        0.2
...
END
some text...
theta   sigma
1        0.3
2        0.2
...
END
more data...

I want to produce a new file after every 'END' to analyze the data separately. I tried some of the solutions proposed to other answers like

with open('fort.16', 'r') as infile, open('output_fort.16', 'w') as outfile:
copy= False
for line in infile:
    if line.strip() == '# legend':
        copy = True
        continue
    elif line.strip()=='End':
        copy = False
    elif copy:
        outfile.write(line)

but this is not what i need.
Im fairly new to python so any help is much appreciated.

Body:
fp = open("random.txt")

data = []
temp = []

for i, line in enumerate(fp):
    if line.strip() == "END":
        new_file = open("file"+str(i)+".txt", "a+")
        for i in temp:
            new_file.write(i+"\n")
        temp = []
        new_file.close()
        continue
    temp.append(line.strip())

fp.close()
print(data)

Here you go this one, creates a new file everytime. The file name is file and the index of where ever the "END" line was found. :)


问:
JFile Chooser Query
How to display JFile-Chooser at the Center of the screen. The conventional method of using ToolKit is not working.</p>

答:
Check out Javadoc for the method JFileChooser#showDialog(Component parent, String approveButtonText) throws HeadlessException, it says:

The parent argument determines two
  things: the frame on which the open
  dialog depends and the component whose
  position the look and feel should
  consider when placing the dialog. If
  the parent is a Frame object (such as
  a JFrame) then the dialog depends on
  the frame and the look and feel
  positions the dialog relative to the
  frame (for example, centered over the
  frame). If the parent is a component,
  then the dialog depends on the frame
  containing the component, and is
  positioned relative to the component
  (for example, centered over the
  component). If the parent is null,
  then the dialog depends on no visible
  window, and it's placed in a
  look-and-feel-dependent position such
  as the center of the screen.

Title: JFile Chooser Query