text:
Q: Exception has occurred. RangeError (RangeError (index): Invalid value: Not in inclusive range When I Run the flutter program, this Exception has occurred.

RangeError (RangeError (index): Invalid value: Not in inclusive range 0..1: 2 how can I fix it**

Please explain what is range error and how can I solve them And why they occur and what is a possible solution to solve them.
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

    class MyApp extends StatefulWidget {
      @override
      State<StatefulWidget> createState() {
        // TODO: implement createState
        return _MyAppState();
      }
    }

    class _MyAppState extends State<MyApp> {
      int _questionIndex = 0;

      void _answerQuestion() {
        setState(() {
          _questionIndex = _questionIndex + 1;
        });
        print(_questionIndex);
      }

      @override
      Widget build(BuildContext context) {
        var questions = [
          'What\'s your favorite color?',
          'What\'s your favorite animal?',
        ];
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('My First App'),
            ),
            body: Column(
              children: [
                Text(
                  questions[_questionIndex],
                ),
                RaisedButton(
                  child: Text('Answer 1'),
                  onPressed: _answerQuestion,
                ),
                RaisedButton(
                  child: Text('Answer 2'),
                  onPressed: () => print('Answer 2 chosen!'),
                ),
                RaisedButton(
                  child: Text('Answer 3'),
                  onPressed: () {
                    // ...
                    print('Answer 3 chosen');
                  },
                ),
              ],
            ),
          ),
        );
      }
    }

A: Your questions is a list of n items, and you're trying to access the n+1th item
Basically, you can only access the items up to n only... no items exist beyond that... so, n+1, n+2, and so on are beyond the range...
Stated as Not in inclusive range
in this case, you have only 2 questions, and on each _answerQuestion method call, you're incrementing the index, so on the 3rd press you'll get this error
To fix this, you can add a question length check in your _answerQuestion method
also, you can put your questions outside of build method

Try changing your code to following
class _MyAppState extends State<MyApp> {
      int _questionIndex = 0;

      /// convert it to var if you need it to be reassigned
      /// moved it to top get its length
      final questions = [
          'What\'s your favorite color?',
          'What\'s your favorite animal?',
        ];

      void _answerQuestion() {
        /// adding this line will ensure that the `_questionIndex`
        /// is incremented up to questions length
        if (_questionIndex < questions.length) {
          setState(() {
            _questionIndex = _questionIndex + 1;
          });
        }

        print(_questionIndex);
      }

      @override
      Widget build(BuildContext context) {

A: First of all, put your questions outside the build method so that it can be accessed by _answerQuestion()
The main issue is _questionIndex is incremented continuously without caring about the max length of questions. @iamdipanshus already describe in details.
Changes will be
class _MyAppState extends State<MyApp> {
  int _questionIndex = 0;

  List<String> questions = [
    'What\'s your favorite color?',
    'What\'s your favorite animal?',
  ];

  void _answerQuestion() {
    if (_questionIndex < questions.length) {
      setState(() {
        _questionIndex = _questionIndex + 1;
      });
    }
    print(_questionIndex);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(


text:
Q: How to use Huawei K3765 under Ubuntu? Before and after plugging in the 3G modem:
root@MACHINE:~# ls /dev/ttyUSB*
ls: cannot access /dev/ttyUSB*: No such file or directory
root@MACHINE:~#

Logs:
root@MACHINE:~# tail -f /var/log/messages
Nov  9 11:43:37 localhost kernel: [423418.057015] usb 1-2: new high speed USB device using ehci_hcd and address 99
Nov  9 11:43:38 localhost kernel: [423418.191322] usb 1-2: configuration #1 chosen from 1 choice
Nov  9 11:43:38 localhost kernel: [423418.196033] scsi121 : SCSI emulation for USB Mass Storage devices
Nov  9 11:43:38 localhost usb-modeswitch: switching 12d1:1520 (HUAWEI Technology: HUAWEI Mobile)
Nov  9 11:43:38 localhost kernel: [423418.706980] usb 1-2: USB disconnect, address 99
Nov  9 11:43:42 localhost kernel: [423422.941015] usb 1-2: new high speed USB device using ehci_hcd and address 100
Nov  9 11:43:42 localhost kernel: [423423.074346] usb 1-2: configuration #1 chosen from 1 choice
Nov  9 11:43:42 localhost kernel: [423423.076801] option 1-2:1.0: GSM modem (1-port) converter detected
Nov  9 11:43:42 localhost kernel: [423423.076889] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB0
Nov  9 11:43:42 localhost kernel: [423423.077042] option 1-2:1.2: GSM modem (1-port) converter detected
Nov  9 11:43:42 localhost kernel: [423423.077095] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB1
Nov  9 11:43:42 localhost kernel: [423423.077157] option 1-2:1.3: GSM modem (1-port) converter detected
Nov  9 11:43:42 localhost kernel: [423423.077209] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB2
Nov  9 11:43:42 localhost kernel: [423423.085767] scsi122 : SCSI emulation for USB Mass Storage devices
Nov  9 11:43:42 localhost kernel: [423423.088685] scsi123 : SCSI emulation for USB Mass Storage devices
Nov  9 11:43:43 localhost usb-modeswitch: switched to 12d1:1465 (HUAWEI Technology: HUAWEI Mobile)
Nov  9 11:43:48 localhost kernel: [423429.122630] option1 ttyUSB0: GSM modem (1-port) converter now disconnected from ttyUSB0
Nov  9 11:43:48 localhost kernel: [423429.122651] option 1-2:1.0: device disconnected
Nov  9 11:43:48 localhost kernel: [423429.122720] option1 ttyUSB1: GSM modem (1-port) converter now disconnected from ttyUSB1
Nov  9 11:43:48 localhost kernel: [423429.122743] option 1-2:1.2: device disconnected
Nov  9 11:43:48 localhost kernel: [423429.122812] option1 ttyUSB2: GSM modem (1-port) converter now disconnected from ttyUSB2
Nov  9 11:43:48 localhost kernel: [423429.122829] option 1-2:1.3: device disconnected
Nov  9 11:43:49 localhost kernel: [423429.236063] usb 1-2: USB disconnect, address 100
Nov  9 11:43:52 localhost kernel: [423432.976035] usb 1-2: new high speed USB device using ehci_hcd and address 101
Nov  9 11:43:52 localhost kernel: [423433.111196] usb 1-2: configuration #1 chosen from 1 choice
Nov  9 11:43:52 localhost kernel: [423433.112234] scsi124 : SCSI emulation for USB Mass Storage devices
Nov  9 11:43:53 localhost usb-modeswitch: switching 12d1:1520 (HUAWEI Technology: HUAWEI Mobile)
Nov  9 11:43:53 localhost kernel: [423433.626977] usb 1-2: USB disconnect, address 101
Nov  9 11:43:57 localhost kernel: [423437.977017] usb 1-2: new high speed USB device using ehci_hcd and address 102
Nov  9 11:43:57 localhost kernel: [423438.111340] usb 1-2: configuration #1 chosen from 1 choice
Nov  9 11:43:57 localhost kernel: [423438.113796] option 1-2:1.0: GSM modem (1-port) converter detected
Nov  9 11:43:57 localhost kernel: [423438.113885] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB0
Nov  9 11:43:57 localhost kernel: [423438.114029] option 1-2:1.2: GSM modem (1-port) converter detected
Nov  9 11:43:57 localhost kernel: [423438.114084] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB1
Nov  9 11:43:57 localhost kernel: [423438.114148] option 1-2:1.3: GSM modem (1-port) converter detected
Nov  9 11:43:57 localhost kernel: [423438.114200] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB2
Nov  9 11:43:57 localhost kernel: [423438.114528] scsi125 : SCSI emulation for USB Mass Storage devices
Nov  9 11:43:57 localhost kernel: [423438.114763] scsi126 : SCSI emulation for USB Mass Storage devices
Nov  9 11:43:58 localhost usb-modeswitch: switched to 12d1:1465 (HUAWEI Technology: HUAWEI Mobile)
Nov  9 11:44:03 localhost kernel: [423444.116264] option1 ttyUSB0: GSM modem (1-port) converter now disconnected from ttyUSB0
Nov  9 11:44:03 localhost kernel: [423444.116287] option 1-2:1.0: device disconnected
Nov  9 11:44:03 localhost kernel: [423444.116373] option1 ttyUSB1: GSM modem (1-port) converter now disconnected from ttyUSB1
Nov  9 11:44:03 localhost kernel: [423444.116393] option 1-2:1.2: device disconnected
Nov  9 11:44:03 localhost kernel: [423444.116466] option1 ttyUSB2: GSM modem (1-port) converter now disconnected from ttyUSB2
Nov  9 11:44:03 localhost kernel: [423444.116490] option 1-2:1.3: device disconnected
Nov  9 11:44:04 localhost kernel: [423444.229033] usb 1-2: USB disconnect, address 102
Nov  9 11:44:07 localhost kernel: [423447.940014] usb 1-2: new high speed USB device using ehci_hcd and address 103
Nov  9 11:44:07 localhost kernel: [423448.076410] usb 1-2: configuration #1 chosen from 1 choice
Nov  9 11:44:07 localhost kernel: [423448.077432] scsi127 : SCSI emulation for USB Mass Storage devices
Nov  9 11:44:08 localhost usb-modeswitch: switching 12d1:1520 (HUAWEI Technology: HUAWEI Mobile)
Nov  9 11:44:08 localhost kernel: [423448.592693] usb 1-2: USB disconnect, address 103
Nov  9 11:44:12 localhost kernel: [423452.932013] usb 1-2: new high speed USB device using ehci_hcd and address 104
Nov  9 11:44:12 localhost kernel: [423453.066182] usb 1-2: configuration #1 chosen from 1 choice
Nov  9 11:44:12 localhost kernel: [423453.068633] option 1-2:1.0: GSM modem (1-port) converter detected
Nov  9 11:44:12 localhost kernel: [423453.068723] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB0
Nov  9 11:44:12 localhost kernel: [423453.068866] option 1-2:1.2: GSM modem (1-port) converter detected
Nov  9 11:44:12 localhost kernel: [423453.068920] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB1
Nov  9 11:44:12 localhost kernel: [423453.068982] option 1-2:1.3: GSM modem (1-port) converter detected
Nov  9 11:44:12 localhost kernel: [423453.069046] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB2
Nov  9 11:44:12 localhost kernel: [423453.086987] scsi128 : SCSI emulation for USB Mass Storage devices
Nov  9 11:44:12 localhost kernel: [423453.097383] scsi129 : SCSI emulation for USB Mass Storage devices
Nov  9 11:44:13 localhost usb-modeswitch: switched to 12d1:1465 (HUAWEI Technology: HUAWEI Mobile)
Nov  9 11:44:19 localhost kernel: [423459.520090] option1 ttyUSB0: GSM modem (1-port) converter now disconnected from ttyUSB0
Nov  9 11:44:19 localhost kernel: [423459.520112] option 1-2:1.0: device disconnected
Nov  9 11:44:19 localhost kernel: [423459.520184] option1 ttyUSB1: GSM modem (1-port) converter now disconnected from ttyUSB1
Nov  9 11:44:19 localhost kernel: [423459.520210] option 1-2:1.2: device disconnected
Nov  9 11:44:19 localhost kernel: [423459.520278] option1 ttyUSB2: GSM modem (1-port) converter now disconnected from ttyUSB2
Nov  9 11:44:19 localhost kernel: [423459.520295] option 1-2:1.3: device disconnected
Nov  9 11:44:19 localhost kernel: [423459.633030] usb 1-2: USB disconnect, address 104
Nov  9 11:44:23 localhost kernel: [423463.978147] usb 1-2: new high speed USB device using ehci_hcd and address 105
Nov  9 11:44:23 localhost kernel: [423464.111465] usb 1-2: configuration #1 chosen from 1 choice
Nov  9 11:44:23 localhost kernel: [423464.114922] scsi130 : SCSI emulation for USB Mass Storage devices
Nov  9 11:44:24 localhost usb-modeswitch: switching 12d1:1520 (HUAWEI Technology: HUAWEI Mobile)
Nov  9 11:44:24 localhost kernel: [423464.629736] usb 1-2: USB disconnect, address 105
Nov  9 11:44:28 localhost kernel: [423468.969014] usb 1-2: new high speed USB device using ehci_hcd and address 106
Nov  9 11:44:28 localhost kernel: [423469.103236] usb 1-2: configuration #1 chosen from 1 choice
Nov  9 11:44:28 localhost kernel: [423469.105684] option 1-2:1.0: GSM modem (1-port) converter detected
Nov  9 11:44:28 localhost kernel: [423469.105769] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB0
Nov  9 11:44:28 localhost kernel: [423469.105913] option 1-2:1.2: GSM modem (1-port) converter detected
Nov  9 11:44:28 localhost kernel: [423469.105970] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB1
Nov  9 11:44:28 localhost kernel: [423469.106231] option 1-2:1.3: GSM modem (1-port) converter detected
Nov  9 11:44:28 localhost kernel: [423469.106288] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB2
Nov  9 11:44:28 localhost kernel: [423469.106462] scsi131 : SCSI emulation for USB Mass Storage devices
Nov  9 11:44:28 localhost kernel: [423469.106706] scsi132 : SCSI emulation for USB Mass Storage devices
Nov  9 11:44:29 localhost usb-modeswitch: switched to 12d1:1465 (HUAWEI Technology: HUAWEI Mobile)
Nov  9 11:44:35 localhost kernel: [423475.735012] option1 ttyUSB0: GSM modem (1-port) converter now disconnected from ttyUSB0
Nov  9 11:44:35 localhost kernel: [423475.735033] option 1-2:1.0: device disconnected
Nov  9 11:44:35 localhost kernel: [423475.735105] option1 ttyUSB1: GSM modem (1-port) converter now disconnected from ttyUSB1
Nov  9 11:44:35 localhost kernel: [423475.735133] option 1-2:1.2: device disconnected
Nov  9 11:44:35 localhost kernel: [423475.735201] option1 ttyUSB2: GSM modem (1-port) converter now disconnected from ttyUSB2
Nov  9 11:44:35 localhost kernel: [423475.735219] option 1-2:1.3: device disconnected
Nov  9 11:44:35 localhost kernel: [423475.848029] usb 1-2: USB disconnect, address 106
Nov  9 11:44:39 localhost kernel: [423479.932153] usb 1-2: new high speed USB device using ehci_hcd and address 107
Nov  9 11:44:39 localhost kernel: [423480.066396] usb 1-2: configuration #1 chosen from 1 choice
Nov  9 11:44:39 localhost kernel: [423480.067423] scsi133 : SCSI emulation for USB Mass Storage devices
Nov  9 11:44:40 localhost usb-modeswitch: switching 12d1:1520 (HUAWEI Technology: HUAWEI Mobile)
Nov  9 11:44:40 localhost kernel: [423480.583557] usb 1-2: USB disconnect, address 107
Nov  9 11:44:44 localhost kernel: [423484.924147] usb 1-2: new high speed USB device using ehci_hcd and address 108
Nov  9 11:44:44 localhost kernel: [423485.059297] usb 1-2: configuration #1 chosen from 1 choice
Nov  9 11:44:44 localhost kernel: [423485.061750] option 1-2:1.0: GSM modem (1-port) converter detected
Nov  9 11:44:44 localhost kernel: [423485.061838] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB0
Nov  9 11:44:44 localhost kernel: [423485.061980] option 1-2:1.2: GSM modem (1-port) converter detected
Nov  9 11:44:44 localhost kernel: [423485.062035] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB1
Nov  9 11:44:44 localhost kernel: [423485.062100] option 1-2:1.3: GSM modem (1-port) converter detected
Nov  9 11:44:44 localhost kernel: [423485.062160] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB2
Nov  9 11:44:44 localhost kernel: [423485.067591] scsi134 : SCSI emulation for USB Mass Storage devices
Nov  9 11:44:44 localhost kernel: [423485.081538] scsi135 : SCSI emulation for USB Mass Storage devices
Nov  9 11:44:45 localhost usb-modeswitch: switched to 12d1:1465 (HUAWEI Technology: HUAWEI Mobile)
Nov  9 11:44:50 localhost kernel: [423490.814586] option1 ttyUSB0: GSM modem (1-port) converter now disconnected from ttyUSB0
Nov  9 11:44:50 localhost kernel: [423490.814602] option 1-2:1.0: device disconnected
Nov  9 11:44:50 localhost kernel: [423490.814680] option1 ttyUSB1: GSM modem (1-port) converter now disconnected from ttyUSB1
Nov  9 11:44:50 localhost kernel: [423490.814708] option 1-2:1.2: device disconnected
Nov  9 11:44:50 localhost kernel: [423490.814778] option1 ttyUSB2: GSM modem (1-port) converter now disconnected from ttyUSB2
Nov  9 11:44:50 localhost kernel: [423490.814797] option 1-2:1.3: device disconnected
Nov  9 11:44:50 localhost kernel: [423490.929038] usb 1-2: USB disconnect, address 108
Nov  9 11:44:54 localhost kernel: [423494.964149] usb 1-2: new high speed USB device using ehci_hcd and address 109
Nov  9 11:44:54 localhost kernel: [423495.098227] usb 1-2: configuration #1 chosen from 1 choice
Nov  9 11:44:54 localhost kernel: [423495.099271] scsi136 : SCSI emulation for USB Mass Storage devices
Nov  9 11:44:55 localhost usb-modeswitch: switching 12d1:1520 (HUAWEI Technology: HUAWEI Mobile)
Nov  9 11:44:55 localhost kernel: [423495.614634] usb 1-2: USB disconnect, address 109
Nov  9 11:44:59 localhost kernel: [423499.956044] usb 1-2: new high speed USB device using ehci_hcd and address 110
Nov  9 11:44:59 localhost kernel: [423500.090998] usb 1-2: configuration #1 chosen from 1 choice
Nov  9 11:44:59 localhost kernel: [423500.093453] option 1-2:1.0: GSM modem (1-port) converter detected
Nov  9 11:44:59 localhost kernel: [423500.093543] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB0
Nov  9 11:44:59 localhost kernel: [423500.093690] option 1-2:1.2: GSM modem (1-port) converter detected
Nov  9 11:44:59 localhost kernel: [423500.093746] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB1
Nov  9 11:44:59 localhost kernel: [423500.093809] option 1-2:1.3: GSM modem (1-port) converter detected
Nov  9 11:44:59 localhost kernel: [423500.093862] usb 1-2: GSM modem (1-port) converter now attached to ttyUSB2
Nov  9 11:44:59 localhost kernel: [423500.095971] scsi137 : SCSI emulation for USB Mass Storage devices
Nov  9 11:44:59 localhost kernel: [423500.110667] scsi138 : SCSI emulation for USB Mass Storage devices
Nov  9 11:45:00 localhost usb-modeswitch: switched to 12d1:1465 (HUAWEI Technology: HUAWEI Mobile)
Nov  9 11:45:06 localhost kernel: [423506.193916] option1 ttyUSB0: GSM modem (1-port) converter now disconnected from ttyUSB0
Nov  9 11:45:06 localhost kernel: [423506.193938] option 1-2:1.0: device disconnected
Nov  9 11:45:06 localhost kernel: [423506.194010] option1 ttyUSB1: GSM modem (1-port) converter now disconnected from ttyUSB1
Nov  9 11:45:06 localhost kernel: [423506.194038] option 1-2:1.2: device disconnected
Nov  9 11:45:06 localhost kernel: [423506.194109] option1 ttyUSB2: GSM modem (1-port) converter now disconnected from ttyUSB2
Nov  9 11:45:06 localhost kernel: [423506.194126] option 1-2:1.3: device disconnected
Nov  9 11:45:06 localhost kernel: [423506.309029] usb 1-2: USB disconnect, address 110
Nov  9 11:45:09 localhost kernel: [423509.933015] usb 1-2: new high speed USB device using ehci_hcd and address 111
Nov  9 11:45:09 localhost kernel: [423510.067119] usb 1-2: configuration #1 chosen from 1 choice
Nov  9 11:45:09 localhost kernel: [423510.068160] scsi139 : SCSI emulation for USB Mass Storage devices
Nov  9 11:45:10 localhost usb-modeswitch: switching 12d1:1520 (HUAWEI Technology: HUAWEI Mobile)
Nov  9 11:45:10 localhost kernel: [423510.583529] usb 1-2: USB disconnect, address 111
^C
root@MACHINE:~#

The problematic 3G modem is a K3765.
How to bring it to life?
lsusb:
Bus 002 Device 012: ID 12d1:1465 Huawei Technologies Co., Ltd.

Ubuntu 10.04

A: I believe the problem you're having is because the Huawei K3765 uses USB "mode-switching" to tell the dongle to stop being a CD drive (where the windows drivers are) and to just be a 3G modem.
If I'm right, just install the usb modeswitching program and it should work automatically:
sudo apt-get install usb-modeswitch

Now unplug the modem and plug it back in.
If that works, the linux kernel has the basics to work with your modem.
Follow the steps in How do I connect to the internet with a "Huwaei Ec1260" modem? to get things set up.
For more info on USB mode-switching and why it's needed, take a look at     http://www.draisberghof.de/usb_modeswitch/
Enjoy

redpajama_set_name: RedPajamaStackExchange


text:
Q: NuGet Package: Run MSBUILD upon Installation I am creating a NuGet package, and have a .targets file that gets installed into the target .csproj file when the package is installed.  This works perfectly as expected, with the .targets file having a Target element that executes before the Build and TransformOnBuild targets.
However, what I want to do now is to execute this Target after the package is installed.  That is, I do not want the user to have to manually build their .csproj after they install my package.  I want the package installation to run this defined Target after it installs the package into the target project.
The reason for this is that the Target autogenerates a few files in the target project (and are based on properties found within the target project), and I want these files to be generated with initial data upon installation and not wait until the user builds that project to create the data.
FWIW, the closest question I found that comes close to this is this one: Configure NuGet package to add a build event when installed, but this is for the build pipeline.  I am wanting to initiate a build (my Target in the .targets file) after the NuGet project installation.
EDIT:
Thanks to @matt-ward I was able to land on this final answer.  I am sharing the full answer here.  It recursively goes through the project to find any .tt files, and sets their Custom Tool to blank, and then compiles the project to generate the needed artifacts.  Here is the install.ps1 in full:
# Runs every time a package is installed in a project

param($installPath, $toolsPath, $package, $project)

# $installPath is the path to the folder where the package is installed.
# $toolsPath is the path to the tools directory in the folder where the package is installed.
# $package is a reference to the package object.
# $project is a reference to the project the package was installed to.

function AdjustCustomTool( $folder )
{
    foreach ( $i in $folder.ProjectItems )
    {
        switch ( $i.Kind )
        {
            "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}" # Folder
            {
                AdjustCustomTool( $i );
                break;
            }
            "{6BB5F8EE-4483-11D3-8BCF-00C04F8EC28C}" # File
            {
                switch ( [System.IO.Path]::GetExtension( $i.Name ) )
                {
                    ".tt"
                    {
                        $i.Properties.Item("CustomTool").Value = "";
                        break;
                    }
                }
            }
        }
    }
}
$templates = $project.ProjectItems.Item( "DragonSpark.Templates" );
AdjustCustomTool( $templates );

# Need to load MSBuild assembly if it's not loaded yet.
Add-Type -AssemblyName 'Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

# Grab the loaded MSBuild project for the project
$project = [Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($project.FullName) | Select-Object -First 1
$project.Build( "GenerateTemplateReferences" );

FWIW, here is my .targets file:

        <Error Condition="'@(TargetReferenceFile -> Count())' == 0" Text="No DragonSpark.Templates\Generated\References.tt file found" />
        <Error Condition="'@(IncludesFile -> Count())' == 0" Text="No DragonSpark.Templates\Generated\Includes.tt file found" />

        <WriteLinesToFile File="@(TargetReferenceFile)" Lines="<# /* AUTOGENERATED FILE */ #>" Overwrite="true" Encoding="Unicode" />

        <!-- T4Toolbox -->
        <WriteLinesToFile File="@(TargetReferenceFile)" Lines="<#@ include file="T4Toolbox.tt" #>" Overwrite="false" Encoding="Unicode" />
        <WriteLinesToFile File="@(TargetReferenceFile)" Lines="<#@ assembly name="" completion="T4Toolbox.dll" #>" Overwrite="false" Encoding="Unicode" />

        <!-- Visual Studio IDE -->
        <WriteLinesToFile File="@(TargetReferenceFile)" Lines="<#@ assembly name="EnvDTE, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" #>" Overwrite="false" Encoding="Unicode" />
        <WriteLinesToFile File="@(TargetReferenceFile)" Lines="<#@ assembly name="EnvDTE80, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" #>" Overwrite="false" Encoding="Unicode" />
        <WriteLinesToFile File="@(TargetReferenceFile)" Lines="<#@ assembly name="VSLangProj, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" #>" Overwrite="false" Encoding="Unicode" />
        <WriteLinesToFile File="@(TargetReferenceFile)" Lines="<#@ assembly name="Microsoft.VisualStudio.Shell.Interop.8.0, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" #>" Overwrite="false" Encoding="Unicode" />
        <WriteLinesToFile File="@(TargetReferenceFile)" Lines="<#@ assembly name="Microsoft.VisualStudio.TextTemplating.Interfaces.10.0, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" #>" Overwrite="false" Encoding="Unicode" />
        <WriteLinesToFile File="@(TargetReferenceFile)" Lines="<#@ assembly name="Microsoft.VisualStudio.TextTemplating.12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" #>" Overwrite="false" Encoding="Unicode" />

        <!-- With HintPath -->
        <WriteLinesToFile File="@(TargetReferenceFile)" Lines="<#@ assembly name="%24%28ProjectDir%29%(Reference.HintPath)" #>" Overwrite="false" Encoding="Unicode" Condition="'%(Reference.HintPath)' != '' And $([System.String]::new('%(Reference.HintPath)').Contains('T4Toolbox.dll')) == 'false'" />

        <!-- Without HintPath -->
        <WriteLinesToFile File="@(TargetReferenceFile)" Lines="<#@ assembly name="%(Reference.Identity)" #>" Overwrite="false" Encoding="Unicode" Condition="'%(Reference.HintPath)' == ''" />

        <!-- ProjectReference -->
        <WriteLinesToFile File="@(TargetReferenceFile)" Lines="<#@ assembly name="%24%28ProjectDir%29%(ProjectReference.RelativeDir)bin\$(Configuration)\%(ProjectReference.Name).dll" #>" Overwrite="false" Encoding="Unicode" Condition="'%(ProjectReference.Name)' != ''" />

        <!-- Includes -->
        <WriteLinesToFile File="@(IncludesFile)" Lines="<# /* AUTOGENERATED FILE */ #>" Overwrite="true" Encoding="Unicode" />
        <WriteLinesToFile File="@(IncludesFile)" Lines="<#@ include file="..\Includes\%(Includes.Filename)%(Includes.Extension)" #>" Overwrite="false" Encoding="Unicode" />

        <Message Text="Generating %(TargetReferenceFile.FullPath) &%(IncludesFile.FullPath)" Importance="high" />
    </Target>
</Project>

A: You could use a PowerShell script (install.ps1) to run a build after the NuGet package is installed.
The PowerShell script could use the Visual Studio API to do the build. Something similar to the following would build the project:
param($installPath, $toolsPath, $package, $project)

$config = $dte.Solution.SolutionBuild.ActiveConfiguration.Name
$dte.Solution.SolutionBuild.BuildProject($config, $project.UniqueName, $false)

To build a specific MSBuild target is more tricky. You could call MSBuild.exe directly. This is something the PostSharp NuGet package does. Or possibly you could use the MSBuild API to build a particular target. Something like:
Add-Type -AssemblyName 'Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

# Grab the loaded MSBuild project for the project
$buildProject = [Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($project.FullName) | Select-Object -First 1

$buildProject.Build("YourTargetName")

Note that I have not tested these PowerShell scripts. They are meant to give you a pointer to the correct implementation.


text:
Q: SQL Server Transpose I want to transpose a Select but can't get my head around Pivot and I am even more perplexed by the following found at numerous tutorials:
"Had the source data been properly normalized there would been no need to transform the columns and rows. If you find yourself needing to perform this type of transformation regularly, then you have a problem with your schema design".
Specifically how would normalization enable a Select to return the transposed values for:
SELECT
    Date, Activity
FROM
    EVENTS
WHERE
    CITY = 'Seattle'

(i.e. rather than event dates going down column1 I'd like the dates to go across as columns)

A: Perhaps you can choose a method similar to following sample,
I used dynamic SQL with CTE statement and CASE operator.
I just used the CTE expression for converting datetime to date data type not to repeat convertion in each CASE statement
declare @mm varchar(2) = datepart(mm,getdate())
declare @sql nvarchar(max)
set @sql = N'
;with cte as (
    SELECT
        DATEPART(dd,[date]) dd,
        convert(date,[date]) [date],
        Activity
    FROM
        [events]
)
SELECT
    case when dd = 1 then Activity end as ''' + '01/'+@mm+'/2016' + ''',
    case when dd = 2 then Activity end as ''' + '01/'+@mm+'/2016' + ''',
    case when dd = 3 then Activity end as ''' + '01/'+@mm+'/2016' + ''',
    case when dd = 17 then Activity end as ''' + '01/'+@mm+'/2016' + ''',
    case when dd = 18 then Activity end as ''' + '01/'+@mm+'/2016' + ''',
    case when dd = 19 then Activity end as ''' + '01/'+@mm+'/2016' + ''',
    case when dd = 20 then Activity end as ''' + '01/'+@mm+'/2016' + ''',
    case when dd = 28 then Activity end as ''' + '01/'+@mm+'/2016' + ''',
    case when dd = 29 then Activity end as ''' + '01/'+@mm+'/2016' + ''',
    case when dd = 30 then Activity end as ''' + '01/'+@mm+'/2016' + '''
FROM cte'
print @sql
exec sp_executeSQL @sql

Of course a dynamic pivot query will fit your requirement better.
You can start by static pivot examples to understand the structure, then work on your sample case. At the final step, you can convert your code to dynamic pivot query


text:
Q: Using .htaccess with dynamic folders - wordpress I have this .htaccess file in the root of my wordpress site.
RewriteEngine on

#For the spanish language, redirect to the spanish translation
RewriteCond %{HTTP:Accept-Language} ^es [NC]
RewriteRule ^$ %{REQUEST_URI}es/ [L,R=301]

#For every other language (including English) use English(the default)
RewriteRule ^$ %{REQUEST_URI}/ [L,R=301] #can remove this i know

This is working fine for the root of the site. e.g www.mysite.com, if the user's browser language has spanish default, it will redirect to www.mysite.com/es/
However, if the user clicks another link to www.mysite.com/help/, it does not load the help page in spanish - expected it to load automatically, www.mysite.com/help/es/
Note:

*

*I cannot put .htaccess in all sub folders - they are dynamically generated. (or i don't know how to)

*I have tried putting these settings in /etc/apache2/apache2.conf in the  . It still does not help.

*I need to avoid infinite loops

How do i make this happen?
This is the complete mod_rewrite part, after the first answer
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteRule ^assets/css/(.*) /wp-content/themes/mytheme/assets/css/$1 [QSA,L]
RewriteRule ^assets/js/(.*) /wp-content/themes/mytheme/assets/js/$1 [QSA,L]
RewriteRule ^assets/img/(.*) /wp-content/themes/mytheme/assets/img/$1 [QSA,L]
RewriteRule ^plugins/(.*) /wp-content/plugins/$1 [QSA,L]

#For the spanish language, redirect to the spanish translation
RewriteCond %{HTTP:Accept-Language} ^es [NC]
RewriteCond %{REQUEST_URI} !es [NC]
RewriteRule .? /es%{REQUEST_URI} [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

A: Try this one:
RewriteEngine on

#For the spanish language, redirect to the spanish translation
RewriteCond %{HTTP:Accept-Language} ^es [NC]
RewriteCond %{REQUEST_URI} !es [NC]
RewriteRule .? %{REQUEST_URI}es/ [L,R=301]


text:
Q: Angular - capturar valor do datapicker Olá, estou com um problema em uma aplicação angular 2, eu tenho 2 Datepicker
<input type="text" data-date-format="dd/mm/yyyy" class="form-control pull-right" ng-model="ctrl.campanha.dataInicial" id="datepicker1" ng-init="initDatepicker1()">

<input type="text" data-date-format="dd/mm/yyyy" class="form-control pull-right" ng-model="ctrl.campanha.dataFinal" id="datepicke2" ng-init="initDatepicker2()">

estou inicializando eles no meu Controller por meio dos seguintes metodos
$scope.initDatepicker1 = function () {

            $('#datepicker1').datepicker({
                autoclose: true
            })
        }

        $scope.initDatepicker2 = function () {
            $('#datepicke2').datepicker({
                autoclose: true
            })
        }
function validacoes() {

        console.log(vm.campanha.dataInicial)
        console.log(vm.campanha.dataFinal)
        return true
    }

Quando tento recuperar os valores dos Datepicker por meio da função validacoes(), que e chamada por meio de um ng-click eles aparecem como undefined, apesar de aparecerem  dentro do input os valores, veja:

como posso resolver esse problema ?


text:
Q: Vue Cli 3 Local fonts not loading When trying to load custom local fonts in Vue CLI 3 the fonts still will not appear. I am not receiving any error messages. The inspector shows the correct rule being loaded, but fonts are falling back to serif on #app. Fonts are not showing up in my dist folder anywhere.
I have tried adding loaders in vue.config.js, changing url paths, and moving the @font-face rules around to different locations, changing the public path to ' ' and '/', importing scss into main.js.
Font loading:
@font-face {
    font-family: 'OpenSans-Regular';
    src: url('/assets/fonts/OpenSans-Regular.eot');
    src: url('/assets/fonts/OpenSans-Regular.eot?#iefix') format('embedded-opentype'),
         url('/assets/fonts/OpenSans-Regular.otf') format('font-opentype'),
         url('/assets/fonts/OpenSans-Regular.woff') format('font-woff'),
         url('/assets/fonts/OpenSans-Regular.ttf') format('font-truetype'),
         url('/assets/fonts/OpenSans-Regular.svg#OpenSans-Regular') format('svg');
    font-weight: normal;
    font-style: normal;
}

And use within App.vue:

That styling is placed within my main.scss file. The file structure as follows:
src
  assets
    fonts
      OpenSans-Regular.eot
      OpenSans-Regular.woff
      etc
  styles
    main.scss
  App.vue
vue.config.js

vue.config.js file is as follows:
module.exports = {
  publicPath: '/',
  css: {
    sourceMap: true,
    loaderOptions: {
      sass: {
        data: `@import "@/styles/main.scss";`
      }
    }
  },
  configureWebpack: {
    module: {
      rules: [{
        test: /\.(ttf|otf|eot|woff|woff2)$/,
        use: {
          loader: "file-loader",
          options: {
            name: "fonts/[name].[ext]",
          },
        },
      }]
    }
  }
}

I have also tried a chainWebpack in vue.config.js to no avail:
chainWebpack: config => {
    config
      .module
      .rule("file")
      .test(/\.(woff2?|eot|ttf|otf)(\?.*)?$/,)
      .use("url-loader")
      .loader("url-loader")
      .options({
        limit: 10000,
        name: 'assets/fonts/[name].[ext]'
      })
      .end();
  }

A: Did you try
@font-face {
font-family: 'OpenSans-Regular';
src: url('~@/assets/fonts/OpenSans-Regular.eot');
src: url('~@/assets/fonts/OpenSans-Regular.eot?#iefix') format('embedded-opentype'),
     url('~@/assets/fonts/OpenSans-Regular.otf') format('font-opentype'),
     url('~@/assets/fonts/OpenSans-Regular.woff') format('font-woff'),
     url('~@/assets/fonts/OpenSans-Regular.ttf') format('font-truetype'),
     url('~@/assets/fonts/OpenSans-Regular.svg#OpenSans-Regular') format('svg');
font-weight: normal;
font-style: normal;
}

Works for me Vue CLI 3, no vue.config.js settings.
I'm loading my styles like this:
import Vue from 'vue';

import router from './router';
import store  from './store';
// eslint-disable-next-line
import styles from './scss/app.scss';

import App from './App.vue';

Vue.config.productionTip = false;

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app');

Not sure if that is good practice.

A: What I ended up doing was moving to a file loader method to get the fonts to package over and set the the public path.
vue.config.js
module.exports = {
  assetsDir: 'assets/',
  publicPath: '/', // Base directory for dev
  css: {
    sourceMap: true,
    loaderOptions: {
      sass: {
        data: `@import "@/styles/main.scss";`
      }
    }
  },
  chainWebpack: config => {
    config.module
      .rule("fonts")
      .test(/\.(ttf|otf|eot|woff|woff2)$/)
      .use("file-loader")
        .loader("file-loader")
        .tap(options => {
          options = {
            // limit: 10000,
            name: '/assets/fonts/[name].[ext]',
          }
          return options
        })
        .end()
  }
};

File-loader doesn't see the files unless called in the js so I imported them in main.js The console log is to navigate around the linter flagging unused imports
// Fonts need to be called in js for webpack to see and copy over
import OpenSansReg from './assets/fonts/OpenSans-Regular.ttf';
import OpenSansLight from './assets/fonts/OpenSans-Light.ttf';
import OpenSansBold from './assets/fonts/OpenSans-Bold.ttf';

console.log(OpenSansReg, OpenSansBold, OpenSansLight);

then in one of my scss files
@font-face {
    font-family: 'OpenSans-Regular';
    src: url('/assets/fonts/OpenSans-Regular.eot?#iefix') format('embedded-opentype'),
         url('/assets/fonts/OpenSans-Regular.otf') format('opentype'),
         url('/assets/fonts/OpenSans-Regular.woff') format('woff'),
         url('/assets/fonts/OpenSans-Regular.ttf') format('truetype'),
         url('/assets/fonts/OpenSans-Regular.svg#OpenSans-Regular') format('svg');
    font-weight: normal;
    font-style: normal;
}

A: For me, I just took out that 'format()' thing and works... Finally..

A: I stuck my custom icon-font in the head tags of my initial index.html page Which also has a custom font import. The same page that you would stick your

. All the other pages /components can use the font-family for me.

...
<link rel="stylesheet" href="icon-font/styles.css" />

But if i try any other location in the project it fails. and the Scss doesnt even compile.

A: This helped me
In src folder main.js just added:
import '../src/fonts/fonts.css'

in the font the following code:
@font-face {
    font-family: 'Conv4240';
    src: url('~@/fonts/Conv4240/4240.eot');
    src: local('☺'),
      url('~@/fonts/Conv4240/4240.woff') format('woff'),
      url('~@/fonts/Conv4240/4240.ttf') format('truetype'),
      url('~@/fonts/Conv4240/4240.otf') format('opentype'),
      url('~@/fonts/Conv4240/4240.svg') format('svg');
    font-weight: normal;
    font-style: normal;
}

And everything started to work


text:
Q: From Uri to Environment.DIRECTORY_DCIM A user chooses a directory through the following code:
public void startChoose(View view) {
    Intent i = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
    i.addCategory(Intent.CATEGORY_DEFAULT);
    startActivityForResult(Intent.createChooser(i, "Choose directory"), 8010);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
      switch (requestCode) {
        case 8010:
            mypath = data.getData().toString();
            break;
    }
}

His directory is stored in mypath as following (e.g. with DCIM):
content://com.android.externalstorage.documents/tree/primary%3ADCIM

Now, is it possible to go from content://com.android.externalstorage.documents/tree/primary%3ADCIM to Environment.DIRECTORY_DCIMand how?
Asked differently, I would like to get the variable Environment.DIRECTORY_DCIM for mypath when the User chooses the DCIM directory. How can one do that?

A:
Now, is it possible to go from content://com.android.externalstorage.documents/tree/primary%3ADCIM to Environment.DIRECTORY_DCIMand how?

No. The Uri that you get back does not have to correspond to a file (e.g., it points to a document in Google Drive). Even if it corresponds to a file, it does not have to reside in a directory that is tied to Environment (e.g., it points to a file in a custom directory).
Please just use the Uri.


text:
Q: Upload to google drive using cURL and set name and location I'm attempting to upload a file to Google Drive using cURL.  The files get uploaded, but, only in the root and are always named "Untitled".
My base script looks like this:
curl
    --silent
    --request POST
    --data-binary "@c:\temp\myfile.jpg"
    -H "Authorization: Bearer abcdefg"
    -H "Content-Type: image/jpeg
    "https://www.googleapis.com/upload/drive/v2/files?uploadType=media"

Using these links as references:
Upload file to Drive and set file name
https://gist.github.com/deanet/3427090
https://developers.google.com/drive/web/manage-uploads
I note that this might be required, which is defined on Google's documentation (see link)
-H "Slug: myfile3.jpg"

But this has no effect whether or not I put it in.
Using cURL help, I note this might be helpful:
 -OL MyFolder\myfile2.jpeg

...but this has no effect, either.
I also note that the string {title:file title} may be required, but I don't know how to embed it in using cURL.  Based on the above links, I thought I could just append it at the end of one of the headers, just before the body.  So, I tried to get clever and changed the content-type specification to this:
-H "Content-Type: image/jpeg {"title":"myfile4"}"

...but it also has no effect.
Curiously, Google's own documentation is incorrect, so, I suspect that the method they once used is now out of date.  The authorization specification in the link is wrong.  You must use Bearer tokens, not "GoogleLogin".  I referred to this link:
https://developers.google.com/gdata/articles/using_cURL
My entire script looked like this.  It uploads, but, not where I want it and not named the way I want it.
curl
    --silent
    --request POST
    --data-binary "@c:\temp\myfile.jpg"
    -OL MyFolder\myfile2.jpeg
    -H "Slug: myfile3.jpg"
    -H "Authorization: Bearer abcdefg"
    -H "Content-Type: image/jpeg {"title":"myfile4"}"
    "https://www.googleapis.com/upload/drive/v2/files?uploadType=media"

I realize I specified "myfile2.jpg" in one place, "myfile3.jpg" in another, and "myfile4" in yet another.  It makes no difference whether they are matched or specified at all.
Any help would be most appreciated!

A: Your problem is that you are doing the media content without the meta data. You have two ways forward :-

*

*POST the metadata to create the empty file and capture its file-id. Then use the file-id for a content upload

*Create a multipart mime body which contains both the metadata and content in a single POST

Personally, I'd go with option 1 as it separates out the two concerns, but both are equally valid. The options are described at https://developers.google.com/drive/web/manage-uploads


text:
Q: Placing $18$ numbered teams into $3$ groups. Problem
There are $18$ football teams. Each of them randomly gets placed into $3$ possible groups
such that each group contains exactly $6$ teams. The teams are numbered from $i = 1, \ldots,18$.
Without loss of generality consider group $1$.
Let $X_{\min}$ be a random variable which maps group $1$ to the lowest team number contained in it.
Find the distribution of $X_{\min}$.
Approach
Let's look at an example: Denote group $1$ as $G_1$ and say $G_1 = \{8,4,3,9,5,12\}$. The smallest number in this set is $3$. We can easily observe that $X_\min = 3$ if and only if all teams with numbers $k < 3$ were assigned to either group $2$ or group $3$.
Let $A_i$ be the event that team $i$ gets assigned to group $1$. Obviously $P(A_i) = \frac{1}{3}$.
Then the probability that some team $i$ does not get assigned to group $1$ is $P(\overline{A_i}) = 1 - P(A_i) = \frac{2}{3}$.
So in general we get
$$
    P(X_\min = k) = P(A_k \cap \overline{A_{k-1}} \cap \cdots )
$$
My question: can we write $P(X_\min = k) = P(A_k) \cdot P(\overline{A_{k-1}}) \cdot \ldots$
If not (which I think), how can I calculate this probability?
Maybe looking at arbitrary sets $\{k, x_2, x_3, x_4, x_5, x_6\}$, then choosing $5$ numbers from the remaining upper $18-k$ numbers to get all such $\binom{18 - k}{5}$ sets, so we are left with the binomial distribution:
$$
    P(X_\min = k) = \binom{18 - k}{5} \left(\frac{1}{3}\right)^1 \left(\frac{2}{3}\right)^5
$$
I feel like I'm missing something.

A: Isn't it the same as: you pick 6 different numbers from $1, 2, \ldots, 18$ and find the distribution of the smallest?
So $$\Pr(X_\min = k) = \frac{{18-k \choose 5}}{{18 \choose 6}}, \forall 1\leqslant k \leqslant 13.$$


text:
Q: WP define WP_HOME case all domain show twice in url error I added code into wp-config file for reducing database request. however, it show all domain twice in domain like:
www.abc.com/www.abc.com/wp-content...etc

I disabled all plugin but problem still not fixed. if i remove those codes then everything go back to normal.
Does anyone know why?
define('WP_SITEURL','www.abc.com')
define('WP_HOME','www.abc.com')


text:
Q: new Function() with variable parameters I need to create a function with variable number of parameters using new Function() constructor. Something like this:
args = ['a', 'b'];
body = 'return(a + b);';

myFunc = new Function(args, body);

Is it possible to do it without eval()?

Thank you very much, guys! Actually, a+b was not my primary concern. I'm working on a code which would process and expand templates and I needed to pass unknown (and variable) number of arguments into the function so that they would be introduced as local variables.
For example, if a template contains:
<span> =a </span>

I need to output the value of parameter a. That is, if user declared expanding function as
var expand = tplCompile('template', a, b, c)

and then calls
expand(4, 2, 1)

I need to substitute =a with 4. And yes, I'm well aware than Function is similar to eval() and runs very slow but I don't have any other choice.

A: @AndyE's answer is correct if the constructor doesn't care whether you use the new keyword or not. Some functions are not as forgiving.
If you find yourself in a scenario where you need to use the new keyword and you need to send a variable number of arguments to the function, you can use this
function Foo() {
  this.numbers = [].slice.apply(arguments);
};

var args = [1,2,3,4,5]; // however many you want
var f = Object.create(Foo.prototype);
Foo.apply(f, args);

f.numbers;          // [1,2,3,4,5]
f instanceof Foo;   // true
f.constructor.name; // "Foo"

ES6 and beyond!

// yup, that easy
function Foo (...numbers) {
  this.numbers = numbers
}

// use Reflect.construct to call Foo constructor
const f =
  Reflect.construct (Foo, [1, 2, 3, 4, 5])

// everything else works
console.log (f.numbers)          // [1,2,3,4,5]
console.log (f instanceof Foo)   // true
console.log (f.constructor.name) // "Foo"

A: You can do this:

let args = '...args'
let body = 'let [a, b] = args;return a + b'

myFunc = new Function(args, body);
console.log(myFunc(1, 2)) //3

A: You can do this using apply():
args = ['a', 'b', 'return(a + b);'];
myFunc = Function.apply(null, args);

Without the new operator, Function gives exactly the same result.  You can use array functions like push(), unshift() or splice() to modify the array before passing it to apply.
You can also just pass a comma-separated string of arguments to Function:
args = 'a, b';
body = 'return(a + b);';

myFunc = new Function(args, body);

On a side note, are you aware of the arguments object?  It allows you to get all the arguments passed into a function using array-style bracket notation:
myFunc = function () {
    var total = 0;

    for (var i=0; i < arguments.length; i++)
        total += arguments[i];

    return total;
}

myFunc(a, b);

This would be more efficient than using the Function constructor, and is probably a much more appropriate method of achieving what you need.

A: If you're just wanting a sum(...) function:
function sum(list) {
    var total = 0, nums;
    if (arguments.length === 1 && list instanceof Array) {
        nums = list;
    } else {
        nums = arguments;
    }
    for (var i=0; i < nums.length; i++) {
        total += nums[i];
    }
    return total;
}

Then,
sum() === 0;
sum(1) === 1;
sum([1, 2]) === 3;
sum(1, 2, 3) === 6;
sum([-17, 93, 2, -841]) === -763;

If you want more, could you please provide more detail? It's rather difficult to say how you can do something if you don't know what you're trying to do.

A: There's a few different ways you could write that.
// assign normally
var ab = ['a','b'].join('');
alert(ab);
// assign with anonymous self-evaluating function
var cd = (function(c) {return c.join("");})(['c','d']);
alert(cd);
// assign with function declaration
function efFunc(c){return c.join("");}
var efArray = ['e','f'];
var ef = efFunc(efArray);
alert(ef);
// assign with function by name
var doFunc = function(a,b) {return window[b](a);}
var ghArray = ['g','h'];
var ghFunc = function(c){return c.join("");}
var gh = doFunc(ghArray,'ghFunc');
alert(gh);
// assign with Class and lookup table
var Function_ = function(a,b) {
  this.val = '';
  this.body = b.substr(0,b.indexOf('('));
  this.args = b.substr(b.indexOf('(')+1,b.lastIndexOf(')')-b.indexOf('(')-1);
  switch (this.body) {
    case "return":
      switch (this.args) {
        case "a + b": this.val = a.join(''); break;
      }
    break;
  }
}
var args = ['i', 'j'];
var body = 'return(a + b);';
var ij = new Function_(args, body);
alert(ij.val);

A: A new feature introduced in ES5 is the reduce method of arrays. You can use it to sum numbers, and it is possible to use the feature in older browsers with some compatibility code.

A: Maybe you want an annoymous function to call an arbitary function.
// user string function
var userFunction = 'function x(...args) { return args.length}';

Wrap it
var annoyFn = Function('return function x(...args) { return args.length}')()
// now call it
annoyFn(args)

A: new Function(...)

Declaring function in this way causes
  the function not to be compiled, and
  is potentially slower than the other
  ways of declaring functions.

Let is examine it with JSLitmus  and run a small test script:
<script src="JSLitmus.js"></script>
<script>

JSLitmus.test("new Function ... ", function() {
    return new Function("for(var i=0; i<100; i++) {}");
});

JSLitmus.test("function() ...", function() {
       return (function() { for(var i=0; i<100; i++) {}  });
});

</script>

What I did above is create a function expression and function constructor performing same operation. The result is as follows:
FireFox Performance Result

IE Performance Result

Based on facts I recommend to use function expression instead of function constructor
var a = function() {
 var result = 0;
 for(var index=0; index < arguments.length; index++) {
  result += arguments[index];
 }
 return result;
 }
alert(a(1,3));

A: function construct(){
         this.subFunction=function(a,b){
         ...
         }
}
var globalVar=new construct();

vs.
var globalVar=new function (){
              this.subFunction=function(a,b){
              ...
              }
}

I prefer the second version if there are sub functions.

A: the b.apply(null, arguments) does not work properly when b inherits a prototype, because 'new' being omitted, the base constructor is not invoked.

A: In this sample i used lodash:
function _evalExp(exp, scope) {
  const k = [null].concat(_.keys(scope));
  k.push('return '+exp);
  const args = _.map(_.keys(scope), function(a) {return scope[a];});
  const func = new (Function.prototype.bind.apply(Function, k));
  return func.apply(func, args);
}

_evalExp('a+b+c', {a:10, b:20, c:30});


text:
Q: How to handle duplicates in emailaddreses when using multiple signup forms with MailChimp? I have various signup forms on my website, all adding to 1 list in MailChimp.
Each signup form has different purpose, e.g. free ebook, video etc.
By using a hidden source field I managed to provide the correct download urls etc.
But... How to handle a visitor who signs up on multiple forms?
I want to share the related materials with him, but MC marks the duplicate as error and requests to update profile... with no option to obtain the related material.

A: You'll probably need to use the API to make this work, a simple form isn't going to cut it.
There are some options. If there are only a handful of things, have them be interest groups. When someone signs up, say for a free ebook, mark the free ebook interest group and subscribe them if necessary.
You can then create an automation for each interest group to send the material.

A: I would consider creating multiple lists for this purpose, since a MC list can never contain any duplicates.


text:
Q: Unwanted Object Updates inside VBA Collection I am trying to build a collection with a new key on top of an older collection. I've looked at other, similar topics but they all had particular issues that I couldn't relate to mine.  My collection issue requires that I take an object from an older collection (Col_0), split it into a twin object with slightly different property values, and then place both into a new collection with a key based on one of the altered properties.  My problem is that the altered twin overwrites the original inside the new collection.  Here is a brief example:
Public Sub FillOutput(ID As String, Col_0 As Collection)
'---Obj is a class scope object not defined here.
'---ID is the item key for items in Col_0 collection
Dim Col_1 As Collection
Set Obj_0 = Col_0.Item(ID)
'---Now I have the right item from the collection
Loop_Count = 0
Set Col_1 = New Collection

While Loop_Count < 2
     If Loop_Count = 0 Then
         Obj_0.Color = "Red"
         Col_1.Add Obj_0, CStr(Obj_0.Color)

     ElseIf Loop_Count = 1 Then
         Obj_0.Color = "Blue"
         Col_1.Add Obj_0, CStr(Obj_0.Color)
     End If

Loop_Count = Loop_Count + 1
Wend 'Loop_count
End If
End Sub

I've tried a number of things such as creating an interim object that gets initialized and set to nothing inside the loop.  As below:
ElseIf Loop_Count = 1 Then
         Set pObj = New clsObjTable
         pObj = Obj_0
         pObj.Color = "Blue"
         Col_1.Add pObj, CStr(pObj.Color)
         Set pObj = Nothing
     End If

Still doesn't work.  My final collection keeps getting overwritten such that both items are "Blue".  I have a suspicion that its about keys getting transferred and screwed up but I just don't know enough here.  Any help or guidance here would be much appreciated!

A: Collections do not actually contain copies of objects, they only contain references to them. If you change your object after adding it to the collection, the object referenced in your collection has the changes too.
The only way to change this behavior, is to manually copy the object. But that's not an easy thing to do. Read this question on cloning objects, but note that you can't just clone built-in objects.
You could try to create a helper function to move all relevant properties from your object to a fresh copy of an object of the same object type, and then return the copy, when struggling with a built-in Access object. But some objects have read-only or private properties, and are thus unclonable.


text:
Q: Change image dimensions Matlab 3d image I have af tiff file and i want to change this image dimensions. Is there a easy way to do this?
My problem is that i want to convert af TIFF file from RGB to Indexed using rgb2ind function. It gives me this error:
RGB image has to be M-by-N-by-3 array.
Does anyone know what the problem is?

A: If your image has 4 dimensions (eg. RGB + alpha channel), doing this:
YourImage(:,:,4) = [];

will remove the 4th dimension.


text:
Q: Breaking down equations like $2^22^{n-2}+(4 \cdot 3^{2})3^{n-2}=2^n+4 \cdot 3^n$ I'm looking at a proof in my book and it isn't clear to me how one goes from one step to the other in the following parts:
$$5(2^{n-1}+4 \cdot 3^{n-1})-6(2^{n-2}+4 \cdot 3^{n-2})=$$
$$(5 \cdot 2 - 6)2^{n-2}+(5 \cdot 4 \cdot 3 - 6 \cdot 4)3^{n-2}$$
and how
$$2^22^{n-2}+(4 \cdot 3^{2})3^{n-2}=$$
$$2^n+4 \cdot 3^n$$
The exponents in particular are confusing. Could someone break it down?

A: It's
$$\begin{align*}
5(2^{n-1}+4\cdot3^{n-1})-6(2^{n-2}+4\cdot3^{n-2)}&=\Big(5\cdot2^{n-1}+\color{brown}{5\cdot4\cdot3^{n-1}}\Big)-\Big(6\cdot2^{n-2}+\color{brown}{6\cdot4\cdot3^{n-2}}\Big)\\
&=\Big(5\cdot2^{n-1}-6\cdot2^{n-2}\Big)+\Big(\color{brown}{5\cdot4\cdot3^{n-1}-6\cdot4\cdot3^{n-2}}\Big)\\
&=\Big(5\cdot2\cdot2^{n-2}-6\cdot2^{n-2}\Big)+\\
&\qquad+\Big(5\cdot4\cdot3\cdot3^{n-2}-6\cdot4\cdot3^{n-2}\Big)\\
&=(5\cdot2-6)2^{n-2}+(5\cdot4\cdot3-6\cdot4)3^{n-2}
\end{align*}$$
and
$$\begin{align*}
2^22^{n-2}+(4\cdot3^2)3^{n-2}&=2^{2+(n-2)}+4\cdot(3^2\cdot3^{n-2})\\
&=2^n+4\cdot3^{2+(n-2)}\\
&=2^n+4\cdot3^n\;.
\end{align*}$$


text:
Q: How to change tokenization (huggingface)? In NER task we want to classification sentence tokens with using different approaches (BIO, for example). But we cant join any subtokens when tokenizer divides sentences stronger.
I would like to classificate 'weight 40.5 px' sentence with custom tokenization (by space in this example)
But after tokenization
tokenizer.convert_ids_to_tokens(tokenizer(['weight', '40.5', 'px'], is_split_into_words=True)['input_ids'])

i had
['[CLS]', 'weight', '40', '.', '5', 'p', '##x', '[SEP]']
when '40.5' splitted into another tokens '40', '.', '5'. Its problem for me, because i want to classificate 3 tokens ('weight', '40.5', 'px'), but it not merge automaticaly, because '40', '.', '5' not looks like '40', '##.', '##5'.
What can i do to solve this problem?


text:
Q: C++ Problems copying string "buffer" to an vector > I am new to C++, and I am a little bit overwhelmed by the class structures available, I have no experience with the different librairies hence I am trying to figure out what is the best structures to use for basics tasks.
I am trying to create a function that reads a file and copy it to a working structure, I first tried without any classes or objects, it was not possible to return a valid pointer to a char* [][] structure (don't know if it's the best way to proceed), so I am trying to come up with another solution based on vector<vector > code I picked up somewhere, hopefully it can work this way.
Below is the code I am trying to work out.
void readFile2(FILE* f) {
  string buf = "abc";
  int a = countLine(f);
  int b = countCol(f);
  long bytes;
  char c;
  int d = 0;
  fseek(f, 0L, SEEK_END);
  bytes = ftell(f);
  fseek(f, 0L, SEEK_SET);

  int x,y = 0;
  vector<vector<string> > vec;
  for (int i = 0;i<a;i++) {
    vector<string> v1;
    for (int j = 0;j<b;j++) {
      v1.push_back(buf);
    }
    vec.push_back(v1);
  }

  buf.erase();

  for (int i=0;i<bytes;i++) {
    c = fgetc(f);
    if (c == '\t') {
      cout<<"buf : "<<buf<<endl;
      ***cout<<"vec : "<<vec[y][x]<<endl;***
      d = 0;
      y += 1;
      buf.erase();
    } else if (c == '\n') {
      cout<<"buf : "<<buf<<endl;
      **cout<<"vec : "<<vec[y][x]<<endl;**
      d = 0;
      x += 1;
      y = 0;
      buf.erase();
    } else {
      buf.push_back(c);
      d++;
    }
  }

Question :

*

*The vector[y][x] I am trying to fill up with strings coming the buffer in the second part of the function (inbetween asterisks in the above code) does not display anything, although it is correctly initalized with string elements during the initialisation part of the code.

*strcpy(vec[y][x],buf) (not present here) does not work either because is requires char* pointer (strange for a function that is named after str, thus I'm kinda stuck because have no idea what to use nor if the structure is correct.

*I am trying to design the function to return a valid pointer to the vector that could be used by another function in the main(), I don't know however if it is the correct way or the most efficient way to load the file in memory and generate an array structure.
Thank you in advance for your time.

A: A completely new version that is very much straight down the line c++. Your code was basically c code
#include <string>
#include <fstream>
#include <vector>
#include <sstream>

int main() {

    std::ifstream input("test.txt");
    std::vector<std::vector<std::string>> fields;
    int count = 0;
    while (input) {
       std::string line;
       std::getline(input, line);
       std::stringstream strs(line);
       fields.push_back(std::vector<std::string>());
       while (strs) {
           std::string field;
           std::getline(strs, field, '\t');
           fields[count].push_back(field);
       }
       count++;
    }

    for (auto& l : fields) {
      for (auto& f : l) {
        std::cout << f;
      }
      std::cout << "\n";
    }
}


text:
Q: Progress dialog UI Freezes/Slow I have a progress dialog that I use for a part in my program where I do a time intensive operation in the background but when the dialog gets displayed the UI or spinner icon freezes/slow/hesitates making the program appear as if it froze. In my onPostExecute of my AsyncTask I dismiss the dialog.
Why would this happen since I am doing all the work in the background?
here is my code
pDialog = ProgressDialog.show(FullGame.this,"Starting New Game","Please Wait...", true);
new StartNewGame().execute();

    private class StartNewGame extends AsyncTask<Void,Void,Boolean>{

    @Override
    protected Boolean doInBackground(Void... params) {
        try{
            ContentValues values = new ContentValues();
            Cursor c = getContentResolver().query(Games.PART1_URI,new String[] {Games.PART1_NUM},
                    Games.PART1_GAME_ID+"="+gameID+" AND "+Games.PART1_FRAME_NUM+"="+10,null,null);
            c.moveToFirst();
            String num = c.getString(0);
            int part1 =0;
            if(num.equals("-")){
                part1=0;
            }else{
                part1=Integer.parseInt(num);
            }

            c = getContentResolver().query(Games.PART2_URI,new String[] {Games.PART2_NUM},
                    Games.PART2_GAME_ID+"="+gameID+" AND "+Games.PART2_FRAME_NUM+"="+10,null,null);
            c.moveToFirst();
            int part2 = 0;
            if(num.equals("-")){
                part2=0;
            }else{
                part2=Integer.parseInt(num);
            }

            c = getContentResolver().query(Games.PART3_URI,new String[] {Games.PART3_NUM},
                    Games.PART3_GAME_ID+"="+gameID,null,null);
            c.moveToFirst();
            int part3 = 0;
            if(num.equals("-")){
                part3=0;
            }else{
                part3=Integer.parseInt(num);
            }

            if(part1 == 10){
                values.clear();
                values.put(Games.STRIKES_FRAME_NUM,10);
                values.put(Games.STRIKES_BOWLER_ID,bowlerClickedID);
                values.put(Games.STRIKES_GAME_ID,gameID);
                getContentResolver().insert(Games.STRIKES_URI, values);
            }
            if(part2 == 10){
                values.clear();
                values.put(Games.STRIKES_FRAME_NUM,10);
                values.put(Games.STRIKES_BOWLER_ID,bowlerClickedID);
                values.put(Games.STRIKES_GAME_ID,gameID);
                getContentResolver().insert(Games.STRIKES_URI, values);
            }
            if(((part2+part3) == 10) && !score.checkSpare(10)){
                values.clear();
                values.put(Games.SPARES_BOWLER_ID,bowlerClickedID);
                values.put(Games.SPARES_FRAME_NUM,10);
                values.put(Games.SPARES_GAME_ID,gameID);
                getContentResolver().insert(Games.SPARES_URI, values);
            }
            if(part3 == 10){
                values.clear();
                values.put(Games.STRIKES_FRAME_NUM,10);
                values.put(Games.STRIKES_BOWLER_ID,bowlerClickedID);
                values.put(Games.STRIKES_GAME_ID,gameID);
                getContentResolver().insert(Games.STRIKES_URI, values);
            }
        c.close();
        }catch(Exception e){
            Log.d("FullGame",e.toString());
        }

        Date date = new Date(System.currentTimeMillis());
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
        String newDate = df.format(date);

        ContentValues values = new ContentValues();
        values.put(Games.GAMES_BOWLER_ID,bowlerClickedID);
        values.put(Games.GAMES_TEAM_ID,1);
        values.put(Games.GAMES_DATE,newDate);
        values.put(Games.GAME_SEASON, pref.getLong(Preferences.SELECTED_SEASON, 1));
        values.put(Games.GAMES_TOURNAMENT_ID, tournamentID);
        Uri uri = getContentResolver().insert(Games.GAMES_URI, values);
        gameID = ContentUris.parseId(uri);
        int gameid = Integer.valueOf(String.valueOf(gameID));
        values.clear();
        Cursor cName = getContentResolver().query(BowlersDB.CONTENT_URI,new String[] {BowlersDB.FIRST_NAME},BowlersDB.ID+"="+bowlerClickedID,null,null);
        cName.moveToFirst();
        String name = cName.getString(0);
        for(int i = 0;i<10;i++){
            int num = i+1;
            values.put(Games.NAMES_FRAME_NUM,num);
            values.put(Games.NAMES_GAME_ID,gameid);
            values.put(Games.NAMES_NAME,name);
            getContentResolver().insert(Games.NAMES_URI, values);
            names(i,name);
            values.clear();
            values.put(Games.PART1_FRAME_NUM,num);
            values.put(Games.PART1_NUM,"0");
            values.put(Games.PART1_GAME_ID,gameid);
            getContentResolver().insert(Games.PART1_URI, values);
            values.clear();
            values.put(Games.PART2_FRAME_NUM,num);
            values.put(Games.PART2_NUM,"0");
            values.put(Games.PART2_GAME_ID,gameid);
            getContentResolver().insert(Games.PART2_URI, values);
            values.clear();
            values.put(Games.TOTALS_FRAME_NUM,num);
            values.put(Games.TOTALS_FRAME_TOTAL,"0");
            values.put(Games.TOTALS_GAME_ID,gameid);
            getContentResolver().insert(Games.TOTALS_URI, values);
            values.clear();
            values.put(Games.POCKETS_BOWLER_ID,bowlerClickedID);
            values.put(Games.POCKETS_FRAME_NUM,i);
            values.put(Games.POCKETS_GAME_ID,gameID);
            values.put(Games.POCKETS_TEAM_ID, teamSelectedID);
            values.put(Games.POCKETS_TOURNAMENT_ID, tournamentID);
            values.put(Games.POCKETS_NUM, 0);
            values.put(Games.POCKETS_SEASON, pref.getLong(Preferences.SELECTED_SEASON, 1));
            getContentResolver().insert(Games.POCKETS_URI, values);
            values.clear();
        }

        values.put(Games.PART3_GAME_ID,gameid);
        values.put(Games.PART3_NUM,"0");
        getContentResolver().insert(Games.PART3_URI, values);
        cName.close();
        part1Array = new int[10];
        part2Array = new int[10];
        totalsArray = new int[10];
        part3 = 0;
        mPinsUp = new ArrayList<Long>();
        mPinsUp.add((long) 1);
        mPinsUp.add((long) 2);
        mPinsUp.add((long) 3);
        mPinsUp.add((long) 4);
        mPinsUp.add((long) 5);
        mPinsUp.add((long) 6);
        mPinsUp.add((long) 7);
        mPinsUp.add((long) 8);
        mPinsUp.add((long) 9);
        mPinsUp.add((long) 10);
        return true;
    }

    protected void onPostExecute(Boolean result){
            pDialog.dismiss();
    }

}

UPDATE:
running through the code in debug mode last night it seems to start to do it in the for loop but still all of this is done in a separate thread and I am only inserting values into my database
UPDATE 2
if I comment out the for loop the progress dialog gets displayed for less than a second so even though I am doing everything in an AsyncTask the inserts must still run in the UI thread

A: This probably happens because your background thread consumes 100% of device CPU. When CPU is busy processing one thread, UI thread won't be updated and therefore you see it as frozen
Try to detect what's the most aggressive operation by removing parts of code from your doInBackground and running the app again. Also try to see how it performs when device is not plugged via USB - this some times provides weird results

A: Figured it out, I had a runaway method going on the UI thread that i did not notice

A: You are using the ProgressDialog wrong.
You need to add a onPreExecute method, and there you define and show your ProgressDialog. Then doInBackground is performed on another thread, and eventually in onPostExecute you dismiss the dialog.
Here's a simple example:
class RefreshChanges extends AsyncTask<String, Void, String> {
        private ProgressDialog mProgressDialog = new ProgressDialog(
                mContext);

        @Override
        protected void onPreExecute() {
            mProgressDialog.setTitle("Whatever title");
            mProgressDialog.setMessage("Whatever message");
            mProgressDialog.show();
        }

        protected String doInBackground(String... strings) {
            // Do whatever processing you want...
            return "";
        }

        protected void onPostExecute(String result) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }
    new RefreshChanges().execute();

By the way, I also recommend you not to use hardcoded strings. Instead, you can go to the strings.xml file under res\values\ and define a string. Then in your code, you can use either getString(R.string.yourStringId) or R.string.yourStringId. It depends whether the method accepts Id's or not (Methods that accept Id's, actually perform getString with the Id you sent it).

A: I have implemented the dialog this way with success.
private ProgressDialog progress;

private class AsynTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
           progress = ProgressDialog.show(context, "", "Please wait...", true);

       }

        @Override
        protected void onPostExecute(Void params) {
             if (progress.isShowing())
                  progress.dismiss();

       }

        @Override
        protected Void doInBackground(Void... arg0) {
             // Do some work
             return null;
       }
 }

A: i don't see any fault in your code, but you have to understand that only writing code in another thread does not means it will get another processor. if your device is having single core processor it does time slicing and does work in round robin way. if your device has multiple cores it will do actual multiple threading. so if you have single core processor it will show you some lag in progress bar.


text:
Q: Server/Client java.net.SocketException I'm trying to build a client/server application that sends files but I'm having an issue with larger files.  I'm using a BufferedInputStream to read information from a file and OutputStream to write to the socket.  I have a loop that reads 1 KB from the file and then sends it, which works fine for the first 25 loops then crashes with a socket write error.  Any ideas? Here's the code.
Client
import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class TCPClient
{
public static void main(String[] args)
{
    /*Variables*/
    int serverPort = 8899;
    String ip = "localhost";
    File myFile = new File("GeneratedFile.txt"); //fileToBeSent.txt

    System.out.println(myFile.length());

    try
    {
        /*Connect to Server*/
        Socket sock = new Socket(ip, serverPort);
        System.out.println("Connection Made");

        /*Create Streams*/
        FileInputStream fis = new FileInputStream(myFile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        OutputStream clientOutput = sock.getOutputStream();

        /*This is the old code for transfer*/
        /*Create Byte Array
        byte[] myByteArray = new byte[(int) myFile.length()];  //was 1024

        /*Send File
        bis.read(myByteArray, 0, 1024);
        clientOutput.write(myByteArray, 0, 1024);
        clientOutput.flush();
        */

        for(long i = 0; i <= myFile.length(); i += 1024)
        {
            byte[] myByteArray = new byte[1024];
            bis.read(myByteArray, 0, 1024);
            clientOutput.write(myByteArray, 0, 1024);
            clientOutput.flush();
            System.out.println("i is: " + i);
        }
        System.out.println("File Written");
        sock.close();
    } catch (IOException ex)
    {
        Logger.getLogger(TCPClient.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("You can't do that!");
    }
    System.out.println("Finished");
}
}

Server
import java.io.*;
import java.net.*;

public class RequestHandler
{
public void handleRequest()
{
    try
    {
        ServerSocket welcomeSocket = new ServerSocket(8899);

        while(true)
        {
            Socket socket = welcomeSocket.accept();
            System.out.println("Socket Open");

            /* Create byte array */
            byte[] mybytearray = new byte[1024 * 512];

            /* Create streams */
            InputStream is = socket.getInputStream();
            FileOutputStream fos = new FileOutputStream("newFile.txt",true);
            BufferedOutputStream bos = new BufferedOutputStream(fos);

            /*Write to file*/
            int bytesRead = is.read(mybytearray, 0, mybytearray.length);
            bos.write(mybytearray, 0, bytesRead);

            /*Close Stream and Socket*/
            bos.close();
            socket.close();
        }
    } catch (Exception e)
    {
        e.printStackTrace();
    }
}
public static void main(String args[])
{
    RequestHandler rq = new RequestHandler();
    rq.handleRequest();
    System.out.println("Here");
}
}

A: Your copying technique is incorrect. This is how to copy streams in Java:
byte[] buffer = new byte[8192]; // or whatever you like, but declare it outside the loop
int count;
while ((count = in.read(buffer)) > 0)
{
  out.write(buffer, 0, count);
}
out.flush();
// then in a finally block ...
out.close();
in.close();

You need this at both ends. You cannot assume that any given read will fill the buffer, so you must loop until EOS. Note that you don't flush inside the loop.


text:
Q: Collect a list of ids based on multiple fields I have a person object with personId, age and gender.
public class Person {
    private int personId;
    private int age;
    private int gender; // 0 for male and 1 for female
}

List<Person> person = new Arraylist<>();
person.add(new Person(1,1,1));
person.add(new Person(2,2,0));
person.add(new Person(3,10,1));
person.add(new Person(4,11,0));
person.add(new Person(5,20,1));
person.add(new Person(6,20,1));
person.add(new Person(7,2,0));
person.add(new Person(8,20,0));
person.add(new Person(9,11,0));
person.add(new Person(10,20,1));

I would like to create a temp object like this with age, gender and list of studentIds.
TempObject {
    private int age;
    private int gender;
    private List<Integer> studentIds;
}

Now, I want to create TempObject with with age, gender and list of studentIds. This object should have a pair of age, gender and list of student ids corresponding to age and gender. Can someone help me out. I have tried using java8's grouping by.
new TempObject(1,1,[1]);
new TempObject(2,0,[2,7]);
new TempObject(10,1,[3]);
new TempObject(11,0,[4,9]);
new TempObject(20,1,[5,6,10]);
new TempObject(20,0,[8]);

A: you can watch here for a very good guide
Anyway, i hope it helps you (maybe a little bit).
Main-Class
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class mainMethod {

    public static void main(String[] args) {
        List<Person> persons = new ArrayList<>();
        persons.add(new Person(1, 1, 1));
        persons.add(new Person(2, 2, 0));
        persons.add(new Person(3, 1, 1));
        persons.add(new Person(4, 11, 0));
        persons.add(new Person(5, 20, 1));
        persons.add(new Person(6, 20, 1));
        persons.add(new Person(7, 2, 0));
        persons.add(new Person(8, 20, 0));
        persons.add(new Person(9, 11, 0));
        persons.add(new Person(10, 20, 1));

        TempObjectMapper tempObjectMapper = new TempObjectMapper(persons.stream()
                .collect(Collectors.groupingBy(Person::getAge, Collectors.groupingBy(Person::getGender))));

        List<TempObject> tempObjects = tempObjectMapper.getObjects();

        System.out.println(tempObjects.toString());
    }
}

TempObjectMapper
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class TempObjectMapper {

    private Map<Integer, Map<Integer, List<Person>>> map;

    public TempObjectMapper(Map<Integer, Map<Integer, List<Person>>> collect) {
        this.map = collect;
    }

    public List<TempObject> getObjects() {
        List<TempObject> list = new ArrayList<TempObject>();

        this.map.forEach((key, value) -> {
            int age = key;
            Map<Integer,List<Person>> map1 = value;

            map1.forEach((key1, value1) -> {
                int gender = key1;
                List<Person> person = value1;
                list.add(new TempObject(age, gender, person));
            });
        });
        return list;
    }

}

TempObject
import java.util.List;

public class TempObject {

    private int age;

    private int gender;

    private List<Person> persons;

    public TempObject(int age, int gender, List<Person> persons) {
        this.age = age;
        this.gender = gender;
        this.persons = persons;
    }

    @Override
    public String toString() {
        return String.format("TempObject: [%s,%s,%s]" , this.age, this.gender, this.persons.toString());
    }
}

Person
public class Person {
    private int personId;
    private int age;
    private int gender;  //0 for male and 1 for female

    public Person(int id, int age, int gender) {
        this.personId = id;
        this.age = age;
        this.gender = gender;
    }
    public int getPersonId() {
        return this.personId;
    }

    public int getAge() {
        return this.age;
    }

    public int getGender() {
        return this.gender;
    }

    @Override
    public String toString() {
        return String.format("Person: [%s, %s, %s]", this.personId,this.age,this.gender);
    }
 }

You can filter your list with this line
persons.stream()
.collect(Collectors.groupingBy(Person::getAge, Collectors.groupingBy(Person::getGender)))

A: You can use Collectors.toMap(keyMapper,valueMapper,mergeFunction,mapFactory) method to collect the TreeMap of duplicates comparing by two fields: age and gender, and merging ids to the list:
List<Person> persons = Arrays.asList(
        new Person(1, 1, 1),
        new Person(2, 2, 0),
        new Person(3, 10, 1),
        new Person(4, 11, 0),
        new Person(5, 20, 1),
        new Person(6, 20, 1),
        new Person(7, 2, 0),
        new Person(8, 20, 0),
        new Person(9, 11, 0),
        new Person(10, 20, 1));

ArrayList<TempObject> tempObjects =
        new ArrayList<>(persons.stream()
                // convert Person to TempObject
                .map(e -> new TempObject(e.getAge(), e.getGender(),
                        Collections.singletonList(e.getPersonId())))
                // collect a Map<TempObject, TempObject>
                .collect(Collectors.toMap(
                        // key of the map
                        Function.identity(),
                        // value of the map
                        Function.identity(),
                        // merge function
                        (to1, to2) -> {
                            // merging two lists of ids
                            to1.setStudentIds(List
                                    .of(to1.getStudentIds(), to2.getStudentIds())
                                    .stream()
                                    .flatMap(List::stream)
                                    .distinct()
                                    .collect(Collectors.toList()));
                            return to1;
                        },
                        // map factory - specify a comparator
                        // for duplicates by age and gender
                        () -> new TreeMap<>(Comparator
                                .comparing(TempObject::getGender)
                                .thenComparing(TempObject::getAge))))
                // get a Collection
                // of the values
                .values());

tempObjects.forEach(System.out::println);
// age=2, gender=0, studentIds=[2, 7]
// age=11, gender=0, studentIds=[4, 9]
// age=20, gender=0, studentIds=[8]
// age=1, gender=1, studentIds=[1]
// age=10, gender=1, studentIds=[3]
// age=20, gender=1, studentIds=[5, 6, 10]

See also: Sort List<Map<String,Object>> based on value


text:
Q: hadoop installation directory error I am trying to setup hadoop from the blog :    http://www.bogotobogo.com/Hadoop/BigData_hadoop_Install_on_ubuntu_single_node_cluster.php
I can do :
hduser@laptop:~$ wget    http://mirrors.sonic.net/apache/hadoop/common/hadoop-2.6.0/hadoop-2.6.0.tar.gz
hduser@laptop:~$ tar xvzf hadoop-2.6.0.tar.gz

after that when  I try to :
hduser@laptop:~/hadoop-2.6.0$ sudo mv * /usr/local/hadoop

and it gives an error like No Such file or directory.
What is the main problem here?
Thank you

A: Once the hadoop is untarred , check the actual path where it has done this operation and verify the path you are on is correct .
hduser@laptop:~$ tar xvzf hadoop-2.6.0.tar.gz .
hduser@laptop:~$ ls -lrt
And see if it is here

A: You should probably do
 sudo mv ~/hadoop-2.6.0 /usr/local/hadoop

A: Give a try with,
hduser@laptop:~$ tar xvzf hadoop-2.6.0.tar.gz .
hduser@laptop:~$ sudo mkdir -p /usr/local/hadoop
hduser@laptop:~$ mv hadoop-2.6.0 /usr/local/hadoop

Here, I found a very simple tutorial to install apache hadoop single node cluster setup


text:
Q: Как создать Маркову цепь с файлом под названием 1.txt(работаю в collab) import os
import markovify

import markovify

with open("1.txt", encoding='utf-8') as f:
    text = f.read()
text_model = markovify.Text(text)
for i in range(4):
    print(text_model.make_short_sentence(380))

вот код, что я набросал, но результат выходит следующий:
None
None
None
None

Что делать?
поправка: при внесении большого текста, как например приведённого в ответе ниже, он выдаёт следующую ошибку:
KeyError                                  Traceback (most recent call last)
<ipython-input-13-d9c4af63990a> in <module>()
      6
      7 # Build the model.
----> 8 text_model = markovify.Text(text)
      9
     10 # Print one randomly-generated sentence

2 frames
/usr/local/lib/python3.6/dist-packages/markovify/chain.py in precompute_begin_state(self)
     96         """
     97         begin_state = tuple([ BEGIN ] * self.state_size)
---> 98         choices, cumdist = compile_next(self.model[begin_state])
     99         self.begin_cumdist = cumdist
    100         self.begin_choices = choices

KeyError: ('___BEGIN__', '___BEGIN__')

A: Метод .make_short_sentence() возвращает None, когда он не может сгенерировать предложение.
Вероятно ваш текст очень короткий, с небольшим количеством предложений, чтобы было возможно сделать с него предложение не совпадающие очень сильно с частью оригинального текста.
Сделайте ваш текст в файле 1.txt более длинным, с большим количеством длинных предложений.
(Например более чем 1 KB с более чем 8 длинными предложениями.)

Пример вывода из вашей программы, когда в файле 1.txt сказка Волк и лиса:

Было у меня и маслице слизала да муку рассыпала?
Стала в кладовушке подлизано!
Явилась из кладовушки, волку говорит: — Я буду дрова носить, печку топить.
Первую ночь лиса на приступочке спала, на вторую забралась в кладовушку, посмотри там хорошенько.


text:
Q: Unable to Connect to GitHub.com For Cloning in ffmpeg installation I am trying to clone the Yasm  git repository
Command:- git clone --depth 1 git://github.com/yasm/yasm.git ,
but i am getting the following message when i enter the above command
Error:-
Cloning into 'yasm'...
fatal: unable to connect to github.com:
github.com[0: 192.30.252.131]: errno=Connection timed out

I am installing YASM for ffmpeg installation in centos6.x.
FFMPEG installation link: Ffmpeg installation link
Any ideas what the problem is?
Thanks in advance for any help.

A: Cloning works for me.  And pinging 192.30.252.131 works too.
Maybe it's a transient problem?


text:
Q: Rails & Groupdate gem to find users with more than X videos per month Users in my Rails app make videos. I'm using the Groupdate gem to get the monthly active users (meaning the number of user who made more than 1 video in the month):
Video.group_by_month(:created_at).count("DISTINCT user_id")
which returns something like this:
{
 Mon, 01 Aug 2022=>116,
 Thu, 01 Sep 2022=>101,
 Sat, 01 Oct 2022=>109,
 Tue, 01 Nov 2022=>153,
 Thu, 01 Dec 2022=>104
}

Now I want to get the number of user who made more than X videos, grouped by month as before.
How do I do that?


text:
Q: Angularjs ng-repeat index 3 i have a code
  $scope.filteredItems =  [];
  $scope.itemsPerPage  =  10;
  $scope.itemdata    =  [];
  $scope.currentPage   =  1;
  $scope.max = 5;
  $scope.data_berita = function () {
$http.get('manajemen_data/berita/get_data').then(function(res)
{
  $scope.itemdata =  res.data;
  $scope.currentPage = 1; //current page
  $scope.entryLimit = 10; //max no of items to display in a page
  $scope.filteredItems = $scope.itemdata.length; //Initially for no filter
  $scope.totalItems = $scope.itemdata.length;
});

}
Her problem is that I display data in a table at the limit of 10 automatic $ index + 1 value 1-10 data. when I moved the page using pagination suppose to page 2 $ index + 1 I am one another how to be 11 when he moved his page?

A: Set $index to ($scope.itemsPerPage * $scope.currentPage)+1
Example. if you want to display page 2, then (10 * 1)+1=11


text:
Q: Ayuda con error en Visual C++ 2010 Buenas tardes, alguien podria ayudarme con el siguiente problema en mi codigo c++.
1>  Generating Code...
1>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\string.h(54): warning RC4011: identifier truncated to '_CRT_SECURE_CPP_OVERLOAD_STANDA'
1>
2>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\string.h(76): warning RC4011: identifier truncated to '_CRT_SECURE_CPP_OVERLOAD_SECURE'
1>
1>  Info.vcxproj -> C:\Users\gramt\Documents\Visual Studio 2010\Projects\Info\Debug\Info.exe

1>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\string.h(54): warning RC4011: identifier truncated to '_CRT_SECURE_CPP_OVERLOAD_STANDA'

Este error corresponde a este código dentro de la cabecera string.h
El codigo:
#if defined(__cplusplus) && _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_MEMORY
extern "C++"
{
 #ifndef _CRT_ENABLE_IF_DEFINED
  #define _CRT_ENABLE_IF_DEFINED
    template<bool _Enable, typename _Ty>
    struct _CrtEnableIf;

    template<typename _Ty>
    struct _CrtEnableIf<true, _Ty>
    {
        typedef _Ty _Type;
    };
 #endif
    template <size_t _Size, typename _DstType>
    inline
    typename _CrtEnableIf<(_Size > 1), void *>::_Type __cdecl memcpy(_DstType (&_Dst)[_Size], _In_opt_bytecount_(_SrcSize) const void *_Src, _In_ size_t _SrcSize) _CRT_SECURE_CPP_NOTHROW
    {
        return memcpy_s(_Dst, _Size * sizeof(_DstType), _Src, _SrcSize) == 0 ? _Dst : 0;
    }
}
#endif

Otro error:
2>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\string.h(76): warning RC4011: identifier truncated to '_CRT_SECURE_CPP_OVERLOAD_SECURE'

Este error corresponde a este código dentro de la cabecera string.h
El codigo:
#if defined(__cplusplus) && _CRT_SECURE_CPP_OVERLOAD_SECURE_NAMES_MEMORY
extern "C++"
{
    template <size_t _Size, typename _DstType>
    inline
    errno_t __CRTDECL memcpy_s(_DstType (&_Dst)[_Size], _In_opt_bytecount_(_SrcSize) const void * _Src, _In_ rsize_t _SrcSize) _CRT_SECURE_CPP_NOTHROW </P>
    {
        return memcpy_s(_Dst, _Size * sizeof(_DstType), _Src, _SrcSize);
    }
}
#endif

A: Para empezar no son mensajes de error sino de advertencia (no es lo mismo error que warning aunque haya que prestar atención a ambos tipos de mensajes).
Después, si echamos un vistazo a la documentación de Microsoft sobre el error:

identificador truncado en 'identifier'
Un identificador era demasiado largo y se ha truncado en el nombre que aparece en la advertencia.

Así pues parece que el origen del problema es exactamente el mismo que el que te está mostrando el compilador:
warning RC4011: identifier truncated to '_CRT_SECURE_CPP_OVERLOAD_STANDA'
                ^^^^^^^^^^^^^^^^^^^^

Una solución pasa entonces por reducir la longitud del identificador para evitar el mensaje de advertencia.
Por cierto, te muestra una advertencia en vez de un error porque el código puede compilar... la advertencia está presente porque al truncar los identificadores puede suceder que dos diferentes acaben coincidiendo.
Visto lo visto el tamaño de los identificadores en VS2010 está limitado a 31 caracteres (32 si añadimos el finalizador de cadena).
Como nota final. No se qué pretendes con eso de extern C++ pero no sirve para absolutamente nada. Bueno, vamos a matizarlo un poco.
extern C sirve para permitir un enlazado a la usanza de C, lo que permite crear código compatible con C y con C++ (una interfaz de unión). En cambio extern C++ permite, en el caso de trabajar con C, indicar que ahí se encuentra código C++... lo que permite que el compilador ignore esa instrucción y se quede tan contento... dudo muy mucho que estés mezclando compiladores en tu caso así que es mejor que dejes de usar esa característica, lo que te permitirá limpiar un poco el código.


text:
Q: Is this the proper way to wait for this function to finish before calling it again?(React-Native) I have a function that listens to Firestore database and fetches some data in realtime. Then it calls another function to make a calculation. Now, I wanna know if I am doing it the right way because I dont want the first function to call the second one before the second one is finished.
_fetchPatientsList() {
    function onResult(QuerySnapshot) { //first function
        this.setState({ dataSource: QuerySnapshot });
        this._calculateLocationDistance(); //second function
    }

    firestore()
        .collection('coolection').doc().collection('public')
        .where('act', '==', 1)
        .orderBy('time', 'asc')
        .limit(10)
        .onSnapshot(onResult, onError);
}

_calculateLocationDistance = () => {
  //some calculations
}

A: I don't have full context on what you're building but according to the docs, onSnapshot runs anytime the document's contents change. That may or may not be exactly what you want.
https://firebase.google.com/docs/firestore/query-data/listen
If you just want to guarantee ordering of the functions, you could do:
firestore()
        .collection('coolection').doc().collection('public')
        .where('act', '==', 1)
        .orderBy('time', 'asc')
        .limit(10)
        .then(onResult)
        .catch(onError);

or with async/await syntax:
try {
  const result = await firestore()
        .collection('coolection').doc().collection('public')
        .where('act', '==', 1)
        .orderBy('time', 'asc')
        .limit(10)

  onResult(result);
} catch (err) {
  onError(err);
}


text:
Q: Shred Recycle Bin - Python I am developing a file shredder for windows 32 using Python 2.7. One of the desired features is be able to shred all recycle bin contents.
As for other files, outside of the recycle bin, we implemented a "shred" function, which overwrites the file contents with garbage, and deletes the file.
However, in order to use this "shred" function on the recycle bin contents, we considered using this library. Using this library we can undelete the item first (restore it), then shred it. But, this method is not suitable because:

*

*It may confuse the user who will shred the recycle bin contents, as he might see recycle contents appearing again in the file system while shredding.

*Windows will display the "Resotring" dialog box, while the undelete function is running. This is not desirable.
Is there any advice on how to implement a recycle bin shredder?

A: You can use the shell module from Pywin32 to get the real path:
from win32com.shell import shell, shellcon
idl = shell.SHGetSpecialFolderLocation(0, shellcon.CSIDL_BITBUCKET)
d = shell.SHGetDesktopFolder()
sf = d.BindToObject(idl, None, shell.IID_IShellFolder)

for i in sf:
    print sf.GetDisplayNameOf(i, shellcon.SHGDN_NORMAL)
    print sf.GetDisplayNameOf(i, shellcon.SHGDN_FORPARSING)


text:
Q: How can I put superLink for email in itextpdf? I have to place a email address in a cell of a table in itextPdf,  it is required to when I click the email address, outlook window can opened and email can be sent directly by adding some message to it. Below is my code, and when i click the email address, it doesn't work, who have some advice about it, thanks!
Chunk mail = new Chunk("xxxx@xx.com", font).setAnchor("xxxx@xx.com");
            PdfPCell cell = new PdfPCell();
            cell.addElement(mail);

A: This works for me:
Chunk mail = new Chunk("xxxx@xx.com", font).setAnchor("mailto:xxxx@xx.com");

It seems like you forgot to add the mailto: in front of the mail address.


text:
Q: ASCIIDOC PDF Generation Footnote renders in the text and not to end of page my first question here excited
in my ASCIIDOC code I have
Big Name{wj}footnote:[Big because X] is found.

This is perfectly rendered to the end of the (one an long) page generating html.
Big Name [1] is found.

<a lot of other text till the end of the one long html page>

--
1. Big because X

But generating PDF it renders into the text:
Big Name [1: Big because X] is found.

Why the PDF-generation is dfferent?
How can I control the type of rendering during PDF generation?
I use
asciidoctor sample.adoc
asciidoctor -r asciidoctor-pdf -b pdf sample.adoc

with
asciidoctor -v
Asciidoctor 1.5.4 [http://asciidoctor.org]
Runtime Environment (ruby 2.3.3p222 (2016-11-21) [x86_64-linux-gnu]) (lc:UTF-8 fs:UTF-8 in:- ex:UTF-8)

A: It seems like there is a bug in asciidoctor-pdf (see https://github.com/asciidoctor/asciidoctor-pdf/issues/73).
However, I'm able to generate footnotes (and other book-related structures) with asciidoctor-fopub (see https://github.com/asciidoctor/asciidoctor-fopub).
So after downloading the fopub, you have first to convert your adoc to xml and then convert the xml to pdf.
so commands will be something similar to this:
asciidoctor -b docbook -a data-uri! your_document.adoc
/path/to/fopub your_document.xml


text:
Q: Highcharts X axis date bold I am trying to make the date bold and red color in my highcharts x axis where time is also present in 12 hour format. I have done the following code but it is making all of the elements in x axis as bold as my time is in 12 hour format.
Highcharts.each($('.highcharts-xaxis-labels')[0].children, function(p, i) {
                    if (p.textContent.match(/[a-z]/i)) {
                      $(p).css({
                        fill: '#951515',
                        fontWeight: 'bold'
                      })
                    }
                  })

How do I achieve this ?

A: Try this change in the condition to match.
If it is NOT a time, make it bold black.
Highcharts.each($('.highcharts-xaxis-labels')[0].children, function(p, i) {
  if ( !p.textContent.match(/\d\d[ap]m/i)) {
    $(p).css({
      fill: '#951515',
      fontWeight: 'bold'
    })
  }
})

\d\d[ap]m will match 04am, 16pm, etc.


text:
Q: Route with name 'na......' does not exist. $router.push() go to wrong path Vue Js I faced to problem with incorrectly work method $router.push() in vue-router.
I have two pages which have same buttons and these buttons execute same methods (go to page addToMyLibrary page). Below I describe how these methods work
Method: router.push(),  I use this.$route.name in order to change dynamicly name property inside push() (need to change between route.name: 'sectionDocs.search.addToMyLibrary' and route.name: 'sectionDocs.view.addToMyLibrary' according to current page).
When we locate on the page /sectionDocs/search/:documentId  after execute this method we go to the page path: '/sectionDocs/search/addToMyLibrary/:documentId' , but when I use this method on the page path: 'sectionDocs/:documentId', after executing method router go to wrong page which has wrong $route.name. Instead of getting name:'sectionDocs.view.addToMyLibrary' we get dynamic path in name of route, I mean page has $route.name: ':documentId' and of course Route with name :documentId does not exist in vue-router.
I need to go to the page /sectionDocs/search/:documentId/addToMyLibrary/:documentId with $route.name: 'sectionDocs.view.addToMyLibrary', but I can`t solve the problem. Please anybody help me !
One more I can go to the page $route.name: 'sectionDocs.view.addToMyLibrary'  only if enter right path in the url /sectionDocs/search/:documentId/addToMyLibrary/:documentId
Bellow I put my code
methods: {
  add_to_library() {
    this.$router.push({
      name: this.$route.name + '.addToMyLibrary',
      params: {
        documentId: this.document.documentItemId,
        documentType: 'LoremIpsum',
      }
    });
  },
}

<template>
  <button @click="add_to_library">Add to library</button>
</template>

router:
export default {
  path: 'sectionDocs',
  component: sectionDocs,
  meta: {
    requiresAuth: true,
    title: 'SectionDocuments'
  },
  children: [{
    path: '/',
    component: sectionDocsSearch,
    meta: {
      requiresAuth: true
    },
    children: [{
      path: '/',
      name: 'sectionDocs',
      component: sectionDocsDefault,
      meta: {
        requiresAuth: true
      },
    }, {
      path: 'search',
      name: 'sectionDocs.search',
      component: sectionDocsSearchResults,
      meta: {
        requiresAuth: true
      },
      children: [
        {
          path: 'addToMyLibrary',
          component: {
            render: h => h('router-view')
          },
          meta: {
            requiresAuth: true
          },
          children: [
            {
              path: 'success',
              name: 'sectionDocs.search.addToMyLibrary.success',
              component: successfulAddMessage,
              meta: {
                requiresAuth: true
              }
            },{
              path: ':documentId',
              name: 'sectionDocs.search.addToMyLibrary',
              component: sectionDocsAddToLibrary,
              meta: {
                requiresAuth: true
              }
            }
          ]
        }
      ],
    }]
  }, {
    path: ':documentId',
    name: 'sectionDocs.view',
    component: sectionDocsView,
    meta: {
      requiresAuth: true,
      dynamicRoute: true
    },
    children: [
      {
        path: 'addToMyLibrary',
        component: {
          render: h => h('router-view')
        },
        meta: {
          requiresAuth: true
        },
        children: [
          {
            path: 'success',
            name: 'sectionDocs.view.addToMyLibrary.success',
            component: successfulAddMessage,
            meta: {
              requiresAuth: true
            }
          },{
            path: ':documentId',
            name: 'sectionDocs.view.addToMyLibrary',
            component: sectionDocsAddToLibrary,
            meta: {
              requiresAuth: true
            }
          },
        ]
      }
    ],
  }]
};