问:
Comparing hashes and delete files with same hash in powershell not working
I am doing a script that identifies the hashes of all the files of a path (and recursively). This is alright.

My problem comes when, after I have identified which hashes are the same, I want to save them into an array so later I can delete these files that have the same Hash (if I want to), or just print the duplicate files. And I have been all afternoon and evening trying to figure out how to do it.
My code at the moment:

```<code>Write-Host "Write a path: "
$UserInput=Read-Host
Get-ChildItem -Path $UserInput -Recurse

#Get-FileHash cmdlet to get the hashes
$files = Get-ChildItem -Path $UserInput -Recurse | where { !$_.PSIsContainer }
$files | % {(Get-FileHash -Path $_.FullName -Algorithm MD5)}

#Creating an array for all the values and an array for the duplicates
$originals=@()
$copies=@()

 #grouping the hashes that are duplicated cmdlet Group-Object:
$Duplicates = Get-ChildItem -Path $UserInput -Recurse -File |Group {($_|Get-FileHash).Hash} |Where Count -gt 1
foreach($FileGroup in $Duplicates)
{
    Write-Host "These files share hash : $($FileGroup.Name)"
    $FileGroup.Group.FullName |Write-Host
    $copies+=$Duplicates

}
</code>```

So the last part "$copies+=$Duplicates" does not work properly.

In the begining I was thinking of saving the first file in the "original" array. If the second one has the same hash, save that 2nd in the "copies" array. But I am not sure if I can do that in the 1st part of the script when getting the hashes.

After that, the second array would have the duplicates, so it would be easy to delete them from the computer.

答:
You should only need to use Get-ChildItem once, once you have all the files you can create a hash for them and then group the hashes to find duplicates. See my example code below:

```<code>Write-Host "Write a path: "
$UserInput=Read-Host

#Get-FileHash cmdlet to get the hashes
$files = Get-ChildItem -Path $UserInput -Recurse | Where-Object -FilterScript { !$_.PSIsContainer }
$hashes = $files | ForEach-Object -Process {Get-FileHash -Path $_.FullName -Algorithm MD5}

$duplicates = $hashes | Group-Object -Property Hash | Where-Object -FilterScript {$_.Count -gt 1}

foreach($duplicate in $duplicates)
{
    Write-Host -Object "These files share hash : $($duplicate.Group.Path -join ', ')"

    # delete first duplicate
    # Remove-Item -Path $duplicate.Group[0].Path -Force -WhatIf

    # delete second duplicate
    # Remove-Item -Path $duplicate.Group[1].Path -Force -WhatIf

    # delete all duplicates except the first
    # foreach($duplicatePath in ($duplicate.Group.Path | Select-Object -Skip 1))
    # {
    #     Remove-Item -Path $duplicatePath -Force -WhatIf
    # }
}
</code>```

Uncomment the code at the end to delete duplicates based on your preferences and when you're ready to delete files make sure you also remove the -WhatIf parameter.

This is the output i receive from the above command if i uncomment out the "delete all duplicates except the first"

```<code>Write a path:
H:\
These files share hash : H:\Rename template 2.csv, H:\Rename template.csv
What if: Performing the operation "Remove File" on target "H:\Rename template.csv".
</code>```

Body:
I am doing a script that identifies the hashes of all the files of a path (and recursively). This is alright.

My problem comes when, after I have identified which hashes are the same, I want to save them into an array so later I can delete these files that have the same Hash (if I want to), or just print the duplicate files. And I have been all afternoon and evening trying to figure out how to do it.
My code at the moment:

Write-Host "Write a path: "
$UserInput=Read-Host
Get-ChildItem -Path $UserInput -Recurse

#Get-FileHash cmdlet to get the hashes
$files = Get-ChildItem -Path $UserInput -Recurse | where { !$_.PSIsContainer }
$files | % {(Get-FileHash -Path $_.FullName -Algorithm MD5)}

#Creating an array for all the values and an array for the duplicates
$originals=@()
$copies=@()

 #grouping the hashes that are duplicated cmdlet Group-Object:
$Duplicates = Get-ChildItem -Path $UserInput -Recurse -File |Group {($_|Get-FileHash).Hash} |Where Count -gt 1
foreach($FileGroup in $Duplicates)
{
    Write-Host "These files share hash : $($FileGroup.Name)"
    $FileGroup.Group.FullName |Write-Host
    $copies+=$Duplicates

}

So the last part "$copies+=$Duplicates" does not work properly.

In the begining I was thinking of saving the first file in the "original" array. If the second one has the same hash, save that 2nd in the "copies" array. But I am not sure if I can do that in the 1st part of the script when getting the hashes.

After that, the second array would have the duplicates, so it would be easy to delete them from the computer.

Body:
You should only need to use Get-ChildItem once, once you have all the files you can create a hash for them and then group the hashes to find duplicates. See my example code below:

Write-Host "Write a path: "
$UserInput=Read-Host

#Get-FileHash cmdlet to get the hashes
$files = Get-ChildItem -Path $UserInput -Recurse | Where-Object -FilterScript { !$_.PSIsContainer }
$hashes = $files | ForEach-Object -Process {Get-FileHash -Path $_.FullName -Algorithm MD5}

$duplicates = $hashes | Group-Object -Property Hash | Where-Object -FilterScript {$_.Count -gt 1}

foreach($duplicate in $duplicates)
{
    Write-Host -Object "These files share hash : $($duplicate.Group.Path -join ', ')"

    # delete first duplicate
    # Remove-Item -Path $duplicate.Group[0].Path -Force -WhatIf

    # delete second duplicate
    # Remove-Item -Path $duplicate.Group[1].Path -Force -WhatIf

    # delete all duplicates except the first
    # foreach($duplicatePath in ($duplicate.Group.Path | Select-Object -Skip 1))
    # {
    #     Remove-Item -Path $duplicatePath -Force -WhatIf
    # }
}

Uncomment the code at the end to delete duplicates based on your preferences and when you're ready to delete files make sure you also remove the -WhatIf parameter.

This is the output i receive from the above command if i uncomment out the "delete all duplicates except the first"

Write a path:
H:\
These files share hash : H:\Rename template 2.csv, H:\Rename template.csv
What if: Performing the operation "Remove File" on target "H:\Rename template.csv".


来源: stackexchange

问:
Basic blur event in a Telerik Nativescript Mobile App
I am writing a cross-platform mobile app using Telerik AppBuilder with NativeScript. I am going nuts trying to figure out how to get a basic "blur" or "onTextChanged" event on a TextField. I can figure out how to do things like "tap" events, but then why is it so hard to find a sample of someone doing "blur" or "onTextChanged"?

I've tried this:

```<code>var tagField = view.getViewById(page, "tfDescription")
tagField.set("onblur", function(eventData) {
    pageData.set("debug", "blur this field: " + JSON.stringify(eventData));
});
</code>```

I've also tried every attribute I can think of in the xml:

```<code><TextField id="tfDescription" blur="blur" onblur="blur" onLoseFocus="blur" focusLost="blur" textChanged="blur" row="2" text="{{ description }}" />
</code>```

None of these work. Does anyone have any clue how to do this?

Thanks

答:
In nativescript 3+ this is how I catch blur events.

The sample code is in nativescript (core)

example.js

```<code>const view = require("ui/core/view");
const textFieldModule = require("ui/text-field");

exports.pageLoaded = (args) => {
  let page = args.object;
  let myTextFieldView = view.getViewById(page, "myTextField");
  myTextFieldView.on(textFieldModule.TextField.blurEvent, function(eventData) {
      console.log('blur event triggered');
  }, this);
}
</code>```

example.xml

```<code><Page loaded="pageLoaded">
  ...
  <TextField
    id="myTextField"
    hint="My Text Field"
    text="{{ myTextField }}" />
  ...
</Page>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am writing a cross-platform mobile app using Telerik AppBuilder with NativeScript. I am going nuts trying to figure out how to get a basic "blur" or "onTextChanged" event on a TextField. I can figure out how to do things like "tap" events, but then why is it so hard to find a sample of someone doing "blur" or "onTextChanged"?

I've tried this:

var tagField = view.getViewById(page, "tfDescription")
tagField.set("onblur", function(eventData) {
    pageData.set("debug", "blur this field: " + JSON.stringify(eventData));
});

I've also tried every attribute I can think of in the xml:

<TextField id="tfDescription" blur="blur" onblur="blur" onLoseFocus="blur" focusLost="blur" textChanged="blur" row="2" text="{{ description }}" />

None of these work. Does anyone have any clue how to do this?

Thanks

Body:
In nativescript 3+ this is how I catch blur events.

The sample code is in nativescript (core)

example.js

const view = require("ui/core/view");
const textFieldModule = require("ui/text-field");

exports.pageLoaded = (args) => {
  let page = args.object;
  let myTextFieldView = view.getViewById(page, "myTextField");
  myTextFieldView.on(textFieldModule.TextField.blurEvent, function(eventData) {
      console.log('blur event triggered');
  }, this);
}

example.xml

<Page loaded="pageLoaded">
  ...
  <TextField
    id="myTextField"
    hint="My Text Field"
    text="{{ myTextField }}" />
  ...
</Page>


问:
String line or StringTokenizer with a Reader?
I had a file to read and with this code I succeeded my JUnit tests. As you can see, I pass the String line as parameter to the readPrevisione(...) method.

```<code>package oroscopo.persistence;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.StringTokenizer;

import oroscopo.model.Previsione;
import oroscopo.model.SegnoZodiacale;

public class TextFileOroscopoRepository implements OroscopoRepository {

 private HashMap<String, List<Previsione>> mapSettore = new HashMap<>();

public TextFileOroscopoRepository(Reader baseReader) throws IOException, BadFileFormatException{
    if (baseReader == null)
        throw new IllegalArgumentException("baseReader is null");
    BufferedReader bufReader = new BufferedReader(baseReader);
    String line;
    while((line=bufReader.readLine()) != null){
        readPrevisione(line,bufReader);
    }

}

private void readPrevisione(String line, BufferedReader bufReader) throws IOException, BadFileFormatException{
    String nomeSettore = line.trim();
    if (!Character.isUpperCase(nomeSettore.charAt(0)))
        throw new BadFileFormatException();
    List<Previsione> listaPrev = new ArrayList<>();
    while (!(line = bufReader.readLine()).equalsIgnoreCase("FINE")){
        try{
        StringTokenizer st1 = new StringTokenizer(line, "\t");
        if(st1.countTokens() < 2)
            throw new BadFileFormatException();
        String prev = st1.nextToken("\t").trim();
        int val = Integer.parseInt(st1.nextToken("\t").trim());
        Set<SegnoZodiacale> segni = new HashSet<>();
        if (st1.hasMoreTokens()){
            while(st1.hasMoreTokens()){
                try{
                segni.add(SegnoZodiacale.valueOf(st1.nextToken(",").trim()));
                }
                catch (IllegalArgumentException e){
                throw new BadFileFormatException();
                }
            }
            Previsione p = new Previsione(prev,val,segni);
            listaPrev.add(p);
        }
        else{
            Previsione p2 = new Previsione(prev,val);
            listaPrev.add(p2);
        }
        }
        catch (NumberFormatException e){
            throw new BadFileFormatException();
        }
        catch (NoSuchElementException e){
            throw new BadFileFormatException();
        }

    }
    mapSettore.put(nomeSettore, listaPrev);
}

@Override
public Set<String> getSettori() {
    return mapSettore.keySet();
}

@Override
public List<Previsione> getPrevisioni(String settore) {
    return mapSettore.get(settore.toUpperCase());
    }
}
</code>```

Here with the same code, instead passing the read line as parameter, I pass the StringTokenizer that already has read the line. It should work like above but my JUnit tests fail. What did I do wrong?

```<code>package oroscopo.persistence;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.StringTokenizer;

import oroscopo.model.Previsione;
import oroscopo.model.SegnoZodiacale;

public class TextFileOroscopoRepository implements OroscopoRepository {

 private HashMap<String, List<Previsione>> mapSettore = new HashMap<>();

public TextFileOroscopoRepository(Reader baseReader) throws IOException, BadFileFormatException{
    if (baseReader == null)
        throw new IllegalArgumentException("baseReader is null");
    BufferedReader bufReader = new BufferedReader(baseReader);
    String line;
    while((line=bufReader.readLine()) != null){
        StringTokenizer st = new StringTokenizer(line);
        readPrevisione(st,bufReader);
    }

}

private void readPrevisione(StringTokenizer st, BufferedReader bufReader) throws IOException, BadFileFormatException{
    String nomeSettore = st.nextToken().trim();
    if (!Character.isUpperCase(nomeSettore.charAt(0)))
        throw new BadFileFormatException();
    List<Previsione> listaPrev = new ArrayList<>();
    String line;
    while (!(line = bufReader.readLine()).equalsIgnoreCase("FINE")){
        try{
        StringTokenizer st1 = new StringTokenizer(line, "\t");
        if(st1.countTokens() < 2)
            throw new BadFileFormatException();
        String prev = st1.nextToken("\t").trim();
        int val = Integer.parseInt(st1.nextToken("\t").trim());
        Set<SegnoZodiacale> segni = new HashSet<>();
        if (st1.hasMoreTokens()){
            while(st1.hasMoreTokens()){
                try{
                segni.add(SegnoZodiacale.valueOf(st1.nextToken(",").trim()));
                }
                catch (IllegalArgumentException e){
                throw new BadFileFormatException();
                }
            }
            Previsione p = new Previsione(prev,val,segni);
            listaPrev.add(p);
        }
        else{
            Previsione p2 = new Previsione(prev,val);
            listaPrev.add(p2);
        }
        }
        catch (NumberFormatException e){
            throw new BadFileFormatException();
        }
        catch (NoSuchElementException e){
            throw new BadFileFormatException();
        }

    }
    mapSettore.put(nomeSettore, listaPrev);
}

@Override
public Set<String> getSettori() {
    return mapSettore.keySet();
}

@Override
public List<Previsione> getPrevisioni(String settore) {
    return mapSettore.get(settore.toUpperCase());
    }

}
</code>```

EDIT: Here is the File.txt that I want to read.

And here is an example of one of my JUnit test:

```<code>@Test
public void testLetturaCorrettaPrevisioni1() throws IOException, BadFileFormatException {
    Reader mr = new StringReader(
            "NOMESEZIONE\navrai la testa un po' altrove\t\t4\tARIETE,TORO,GEMELLI\ngrande intimita'\t9\nFINE\n"
                    + "SEZIONE2\ntesto di prova\t\t\t\t\t66\t\nFINE");

    OroscopoRepository or = new TextFileOroscopoRepository(mr);

    assertEquals("avrai la testa un po' altrove", or.getPrevisioni("nomesezione").get(0).getPrevisione());
    assertEquals(4, or.getPrevisioni("nomesezione").get(0).getValore());
    Set<SegnoZodiacale> validi = new HashSet<SegnoZodiacale>() {
        private static final long serialVersionUID = 1L;

        {
            add(SegnoZodiacale.ARIETE);
            add(SegnoZodiacale.TORO);
            add(SegnoZodiacale.GEMELLI);
        }
    };
    for (SegnoZodiacale s : SegnoZodiacale.values()) {
        if (validi.contains(s))
            assertTrue(or.getPrevisioni("nomesezione").get(0).validaPerSegno(s));
        else
            assertFalse(or.getPrevisioni("nomesezione").get(0).validaPerSegno(s));
    }

    assertEquals("grande intimita'", or.getPrevisioni("nomesezione").get(1).getPrevisione());
    assertEquals(9, or.getPrevisioni("nomesezione").get(1).getValore());
    for (SegnoZodiacale s : SegnoZodiacale.values()) {
        assertTrue(or.getPrevisioni("nomesezione").get(1).validaPerSegno(s));
    }
}
</code>```

答:
I've understood why it didn't work..
The String line was : "EXAMPLE\n"
but after

```<code>while((line=bufReader.readLine()) != null){
...}
</code>```

line = "EXAMPLE" because the readLine() eats the newline.
So I passed to the readPrevisione() a StringTokenizer as parameter

```<code>while((line=bufReader.readLine()) != null){
    StringTokenizer st = new StringTokenizer(line);
    readPrevisione(st,bufReader);
}

private void readPrevisione(StringTokenizer st, BufferedReader bufReader) throws IOException, BadFileFormatException{
String nomeSettore = st.nextToken().trim();
...}
</code>```

And st.nextToken() search for a \n that is not contained in "EXAMPLE". That's why it didn't work.

Body:
I had a file to read and with this code I succeeded my JUnit tests. As you can see, I pass the String line as parameter to the readPrevisione(...) method.

package oroscopo.persistence;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.StringTokenizer;

import oroscopo.model.Previsione;
import oroscopo.model.SegnoZodiacale;

public class TextFileOroscopoRepository implements OroscopoRepository {

 private HashMap<String, List<Previsione>> mapSettore = new HashMap<>();

public TextFileOroscopoRepository(Reader baseReader) throws IOException, BadFileFormatException{
    if (baseReader == null)
        throw new IllegalArgumentException("baseReader is null");
    BufferedReader bufReader = new BufferedReader(baseReader);
    String line;
    while((line=bufReader.readLine()) != null){
        readPrevisione(line,bufReader);
    }

}

private void readPrevisione(String line, BufferedReader bufReader) throws IOException, BadFileFormatException{
    String nomeSettore = line.trim();
    if (!Character.isUpperCase(nomeSettore.charAt(0)))
        throw new BadFileFormatException();
    List<Previsione> listaPrev = new ArrayList<>();
    while (!(line = bufReader.readLine()).equalsIgnoreCase("FINE")){
        try{
        StringTokenizer st1 = new StringTokenizer(line, "\t");
        if(st1.countTokens() < 2)
            throw new BadFileFormatException();
        String prev = st1.nextToken("\t").trim();
        int val = Integer.parseInt(st1.nextToken("\t").trim());
        Set<SegnoZodiacale> segni = new HashSet<>();
        if (st1.hasMoreTokens()){
            while(st1.hasMoreTokens()){
                try{
                segni.add(SegnoZodiacale.valueOf(st1.nextToken(",").trim()));
                }
                catch (IllegalArgumentException e){
                throw new BadFileFormatException();
                }
            }
            Previsione p = new Previsione(prev,val,segni);
            listaPrev.add(p);
        }
        else{
            Previsione p2 = new Previsione(prev,val);
            listaPrev.add(p2);
        }
        }
        catch (NumberFormatException e){
            throw new BadFileFormatException();
        }
        catch (NoSuchElementException e){
            throw new BadFileFormatException();
        }

    }
    mapSettore.put(nomeSettore, listaPrev);
}

@Override
public Set<String> getSettori() {
    return mapSettore.keySet();
}

@Override
public List<Previsione> getPrevisioni(String settore) {
    return mapSettore.get(settore.toUpperCase());
    }
}

Here with the same code, instead passing the read line as parameter, I pass the StringTokenizer that already has read the line. It should work like above but my JUnit tests fail. What did I do wrong?

package oroscopo.persistence;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.StringTokenizer;

import oroscopo.model.Previsione;
import oroscopo.model.SegnoZodiacale;

public class TextFileOroscopoRepository implements OroscopoRepository {

 private HashMap<String, List<Previsione>> mapSettore = new HashMap<>();

public TextFileOroscopoRepository(Reader baseReader) throws IOException, BadFileFormatException{
    if (baseReader == null)
        throw new IllegalArgumentException("baseReader is null");
    BufferedReader bufReader = new BufferedReader(baseReader);
    String line;
    while((line=bufReader.readLine()) != null){
        StringTokenizer st = new StringTokenizer(line);
        readPrevisione(st,bufReader);
    }

}

private void readPrevisione(StringTokenizer st, BufferedReader bufReader) throws IOException, BadFileFormatException{
    String nomeSettore = st.nextToken().trim();
    if (!Character.isUpperCase(nomeSettore.charAt(0)))
        throw new BadFileFormatException();
    List<Previsione> listaPrev = new ArrayList<>();
    String line;
    while (!(line = bufReader.readLine()).equalsIgnoreCase("FINE")){
        try{
        StringTokenizer st1 = new StringTokenizer(line, "\t");
        if(st1.countTokens() < 2)
            throw new BadFileFormatException();
        String prev = st1.nextToken("\t").trim();
        int val = Integer.parseInt(st1.nextToken("\t").trim());
        Set<SegnoZodiacale> segni = new HashSet<>();
        if (st1.hasMoreTokens()){
            while(st1.hasMoreTokens()){
                try{
                segni.add(SegnoZodiacale.valueOf(st1.nextToken(",").trim()));
                }
                catch (IllegalArgumentException e){
                throw new BadFileFormatException();
                }
            }
            Previsione p = new Previsione(prev,val,segni);
            listaPrev.add(p);
        }
        else{
            Previsione p2 = new Previsione(prev,val);
            listaPrev.add(p2);
        }
        }
        catch (NumberFormatException e){
            throw new BadFileFormatException();
        }
        catch (NoSuchElementException e){
            throw new BadFileFormatException();
        }

    }
    mapSettore.put(nomeSettore, listaPrev);
}

@Override
public Set<String> getSettori() {
    return mapSettore.keySet();
}

@Override
public List<Previsione> getPrevisioni(String settore) {
    return mapSettore.get(settore.toUpperCase());
    }

}

EDIT: Here is the File.txt that I want to read.

And here is an example of one of my JUnit test:

@Test
public void testLetturaCorrettaPrevisioni1() throws IOException, BadFileFormatException {
    Reader mr = new StringReader(
            "NOMESEZIONE\navrai la testa un po' altrove\t\t4\tARIETE,TORO,GEMELLI\ngrande intimita'\t9\nFINE\n"
                    + "SEZIONE2\ntesto di prova\t\t\t\t\t66\t\nFINE");

    OroscopoRepository or = new TextFileOroscopoRepository(mr);

    assertEquals("avrai la testa un po' altrove", or.getPrevisioni("nomesezione").get(0).getPrevisione());
    assertEquals(4, or.getPrevisioni("nomesezione").get(0).getValore());
    Set<SegnoZodiacale> validi = new HashSet<SegnoZodiacale>() {
        private static final long serialVersionUID = 1L;

        {
            add(SegnoZodiacale.ARIETE);
            add(SegnoZodiacale.TORO);
            add(SegnoZodiacale.GEMELLI);
        }
    };
    for (SegnoZodiacale s : SegnoZodiacale.values()) {
        if (validi.contains(s))
            assertTrue(or.getPrevisioni("nomesezione").get(0).validaPerSegno(s));
        else
            assertFalse(or.getPrevisioni("nomesezione").get(0).validaPerSegno(s));
    }

    assertEquals("grande intimita'", or.getPrevisioni("nomesezione").get(1).getPrevisione());
    assertEquals(9, or.getPrevisioni("nomesezione").get(1).getValore());
    for (SegnoZodiacale s : SegnoZodiacale.values()) {
        assertTrue(or.getPrevisioni("nomesezione").get(1).validaPerSegno(s));
    }
}

Body:
I've understood why it didn't work..
The String line was : "EXAMPLE\n"
but after

while((line=bufReader.readLine()) != null){
...}

line = "EXAMPLE" because the readLine() eats the newline.
So I passed to the readPrevisione() a StringTokenizer as parameter

while((line=bufReader.readLine()) != null){
    StringTokenizer st = new StringTokenizer(line);
    readPrevisione(st,bufReader);
}

private void readPrevisione(StringTokenizer st, BufferedReader bufReader) throws IOException, BadFileFormatException{
String nomeSettore = st.nextToken().trim();
...}

And st.nextToken() search for a \n that is not contained in "EXAMPLE". That's why it didn't work.


问:
Can a google add-on copy files from my Drive to a user's folder? Is there any way to do this?
```<code>Var file = DriveApp.getFileById(file) //in my Drive
DriveApp.getRootFolder.addFile(file); //in user' s Drive
</code>```

答:
You can copy from files on your Google Drive to a folder on other user's Drive.

addFile() you use is used for adding parents to a file. addFile() cannot be used for other user's folder even if the folder was shared. If you want to use the file together with the user, please share a file with the user.

If you want to use the file separately with the user, you can use makeCopy(). When you want to copy files to the user's folder, please share with you the destination folder which is the folder on user's Drive.

The sample script is as follows.

Sample Script :

```<code>var srcfileid = "### file id ###"; // This file is your file.
var destfolderid = "### folder id ###"; // This folder is user's folder.

var file = DriveApp.getFileById(srcfileid)
file.makeCopy(file.getName(), DriveApp.getFolderById(destfolderid));
</code>```

If I misunderstand your question, I'm sorry.

Body:
You can copy from files on your Google Drive to a folder on other user's Drive.

addFile() you use is used for adding parents to a file. addFile() cannot be used for other user's folder even if the folder was shared. If you want to use the file together with the user, please share a file with the user.

If you want to use the file separately with the user, you can use makeCopy(). When you want to copy files to the user's folder, please share with you the destination folder which is the folder on user's Drive.

The sample script is as follows.

Sample Script :

var srcfileid = "### file id ###"; // This file is your file.
var destfolderid = "### folder id ###"; // This folder is user's folder.

var file = DriveApp.getFileById(srcfileid)
file.makeCopy(file.getName(), DriveApp.getFolderById(destfolderid));

If I misunderstand your question, I'm sorry.


问:
Receive 404 after uncomment enablePrettyUrl YII2
After uncomment enablePrettyUrl get 404 error

For example:

The requested URL /site/index was not found on this server.

Apache/2.4.7 (Ubuntu) Server at yiibasic.com Port 80

When I comment it again, everything is working

```<code>'components' => [
    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
        ],
    ],
]
</code>```

Can't understand what the problem is.

.htaccess:

```<code>RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . index.php
</code>```

答:
After adding .htaccess file in your ./web folder (if using basic template ), you must then add some rules in the urlManager section of your web.php config file...see below</p>

```<code>'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'enableStrictParsing' => false,
            'rules' => array(
                '<controller:\w+>/<id:\d+>' => '<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
            ),
        ],
</code>```

Body:
After uncomment enablePrettyUrl get 404 error

For example:

The requested URL /site/index was not found on this server.

Apache/2.4.7 (Ubuntu) Server at yiibasic.com Port 80

When I comment it again, everything is working

'components' => [
    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
        ],
    ],
]

Can't understand what the problem is.

.htaccess:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . index.php

Body:
After adding .htaccess file in your ./web folder (if using basic template ), you must then add some rules in the urlManager section of your web.php config file...see below

'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'enableStrictParsing' => false,
            'rules' => array(
                '<controller:\w+>/<id:\d+>' => '<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
            ),
        ],


问:
no listing appears using swagger on jersey 2 with grizzly
I have setup swagger on jersey 2 and grizzly (no web.xml). I am able to access the swagger page however my API resources do not appear.

My main file is seen below

```<code>`
package com.beraben.jersey.test;

import com.wordnik.swagger.jaxrs.config.BeanConfig;
import java.net.URI;
import org.glassfish.grizzly.http.server.CLStaticHttpHandler;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;

/**
 *
 * @author Evan
 */
public class jerseyTestMain {

    /**
     * @param args the command line arguments
     */
    public static final String BASE_URI = "http://localhost:8080/myapp/";

    public static HttpServer startServer() {
        // create a resource config that scans for JAX-RS resources and providers
        // in com.example.rest package
        final ResourceConfig rc = new ResourceConfig().packages("com.beraben.jersey.test", "com.wordnik.swagger.jersey.listing");

        BeanConfig config = new BeanConfig();
        config.setResourcePackage("com.beraben.jersey.test");
        config.setVersion("1.0.0");
        config.setScan(true);

        // create and start a new instance of grizzly http server
        // exposing the Jersey application at BASE_URI
        return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
    }

    public static void main(String[] args) throws InterruptedException {
        final HttpServer server = startServer();

        CLStaticHttpHandler staticHttpHandler = new CLStaticHttpHandler(jerseyTestMain.class.getClassLoader(), "swagger-ui/");
        server.getServerConfiguration().addHttpHandler(staticHttpHandler, "/docs");

        Object syncObj = new Object();
        synchronized (syncObj) {
            syncObj.wait();
        }

    }

}
`
</code>```

I also have a API setup seen below

```<code>   package com.beraben.jersey.test;

import com.wordnik.swagger.annotations.Api;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 *
 * @author Evan
 */
@Path("myresource")
@Api(value = "/myresource")
public class MyResource {
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getIt(){
        return "Got it!";
    }
}
</code>```

I have no problem using the API it returns correctly.

But for some reason I cant get swagger to show details about the API calls, is there something i need to do more to get it to show details about the existing API in my code?

My static files are copied from the sample project
jersey2-grizzly2-swagger-demo

Also for reference, here is my pom file (not slight difference from the demo project is I don't use dependencyManagment to get jersey-bom instead i reference it directly).

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.beraben</groupId>
    <artifactId>jersey-test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.archetypes</groupId>
            <artifactId>jersey-quickstart-grizzly2</artifactId>
            <version>2.22.2</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey</groupId>
            <artifactId>jersey-bom</artifactId>
            <version>2.22.2</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-grizzly2-http</artifactId>
            <version>2.22.2</version>
        </dependency>
        <dependency>
            <groupId>com.wordnik</groupId>
            <artifactId>swagger-jersey-jaxrs_2.10</artifactId>
            <version>1.3.13</version>
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
</project>
</code>```

答:
After looking at the google forms, it turns out that standalone version of swagger does not actually work.

I created a separate maven web app and added my jersey project as dependencies. This worked after fiddling around with the swagger version that matched the jersey version I was using.

Body:
I have setup swagger on jersey 2 and grizzly (no web.xml). I am able to access the swagger page however my API resources do not appear.

My main file is seen below

`
package com.beraben.jersey.test;

import com.wordnik.swagger.jaxrs.config.BeanConfig;
import java.net.URI;
import org.glassfish.grizzly.http.server.CLStaticHttpHandler;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;

/**
 *
 * @author Evan
 */
public class jerseyTestMain {

    /**
     * @param args the command line arguments
     */
    public static final String BASE_URI = "http://localhost:8080/myapp/";

    public static HttpServer startServer() {
        // create a resource config that scans for JAX-RS resources and providers
        // in com.example.rest package
        final ResourceConfig rc = new ResourceConfig().packages("com.beraben.jersey.test", "com.wordnik.swagger.jersey.listing");

        BeanConfig config = new BeanConfig();
        config.setResourcePackage("com.beraben.jersey.test");
        config.setVersion("1.0.0");
        config.setScan(true);

        // create and start a new instance of grizzly http server
        // exposing the Jersey application at BASE_URI
        return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
    }

    public static void main(String[] args) throws InterruptedException {
        final HttpServer server = startServer();

        CLStaticHttpHandler staticHttpHandler = new CLStaticHttpHandler(jerseyTestMain.class.getClassLoader(), "swagger-ui/");
        server.getServerConfiguration().addHttpHandler(staticHttpHandler, "/docs");

        Object syncObj = new Object();
        synchronized (syncObj) {
            syncObj.wait();
        }

    }

}
`

I also have a API setup seen below

   package com.beraben.jersey.test;

import com.wordnik.swagger.annotations.Api;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 *
 * @author Evan
 */
@Path("myresource")
@Api(value = "/myresource")
public class MyResource {
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getIt(){
        return "Got it!";
    }
}

I have no problem using the API it returns correctly.

But for some reason I cant get swagger to show details about the API calls, is there something i need to do more to get it to show details about the existing API in my code?

My static files are copied from the sample project
jersey2-grizzly2-swagger-demo

Also for reference, here is my pom file (not slight difference from the demo project is I don't use dependencyManagment to get jersey-bom instead i reference it directly).

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.beraben</groupId>
    <artifactId>jersey-test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.archetypes</groupId>
            <artifactId>jersey-quickstart-grizzly2</artifactId>
            <version>2.22.2</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey</groupId>
            <artifactId>jersey-bom</artifactId>
            <version>2.22.2</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-grizzly2-http</artifactId>
            <version>2.22.2</version>
        </dependency>
        <dependency>
            <groupId>com.wordnik</groupId>
            <artifactId>swagger-jersey-jaxrs_2.10</artifactId>
            <version>1.3.13</version>
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
</project>


问:
SFML is doing something very wired with vector Array
Hey when I am using this code it seems to place my SBOUND in the same spot and not everywhere on the 2 spot that I want it. I have no idea that the problem is and am mostly new to SFML and cant quite understand what is happening. The main code is like this.
`

```<code>#include "MainH.h"
int main()
{
int x = 200;
int y = 200;
sf::RenderWindow window(sf::VideoMode(512, 256), "Tilemap");
// create a new vertex
sf::Vertex vertex;

// set its position
vertex.position = sf::Vector2f(10, 50);

// set its color
vertex.color = sf::Color::Red;

// set its texture coordinates
vertex.texCoords = sf::Vector2f(100, 100);

////////////////////////
sf::Sprite A;
sf::Texture AT;
AT.loadFromFile("Red.png");
A.setTexture(AT);
A.setPosition(16.f, 16.f);
sf::Text A_Tex;
sf::Font A_Font;
A_Font.loadFromFile("arial.ttf");
A_Tex.setFont(A_Font);
A_Tex.setColor(sf::Color::Yellow);
A_Tex.setScale(0.35f,0.35f);
/////////////////////////////
sf::Sprite B;
sf::Texture BT;
BT.loadFromFile("Green.png");
B.setTexture(BT);
B.setPosition(30.f, 30.f);
sf::Text B_Tex;
sf::Font B_Font;
B_Font.loadFromFile("arial.ttf");
B_Tex.setFont(A_Font);
B_Tex.setColor(sf::Color::Yellow);
B_Tex.setScale(0.35f, 0.35f);

const int level[] =
{
    5, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0,
    2, 1, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3,
    2, 1, 0, 0, 2, 0, 3, 3, 3, 0, 1, 1, 1, 0, 0, 0,
    2, 1, 1, 0, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 0, 0,
    2, 0, 1, 0, 3, 0, 2, 2, 0, 0, 1, 1, 1, 1, 2, 0,
    2, 0, 1, 0, 3, 0, 2, 2, 2, 0, 1, 1, 1, 1, 1, 1,
    2, 0, 1, 0, 3, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1,
};
sf::Texture COL;
COL.loadFromFile("COL.png");

TileMap map;
if (!map.load("Set.png", sf::Vector2u(16, 16), level, 16, 8, COL))
    return -1;

bool Debug = false;
//////////////////////////////
BorderLine C;
sf::Texture BordS;
sf::Texture BordT;
BordS.loadFromFile("Border.png");
BordT.loadFromFile("TopBD.png");
C.Setup(BordS, 16 ,BordT);
////////////////////////////////
window.setKeyRepeatEnabled(false);

while (window.isOpen())
{
    C.Object = A.getPosition();
    sf::Vector2f APos = A.getPosition();
    sf::Vector2f BPos = B.getPosition();

    sf::Event event;
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
            window.close();
        if (event.type == sf::Event::Resized)
        {
            window.setView(sf::View(sf::FloatRect(0, 0, event.size.width, event.size.height)));
        }

    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) && !Collision::PixelPerfectTest(C.A_B_L, B, 256))
    {
        // left key is pressed: move our character
        A.move(-.01f, 0);
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) && !Collision::PixelPerfectTest(C.A_B_R, B, 256))
    {
        // left key is pressed: move our character
        for (unsigned int i = 0; i < map.SBOUND.size(); ++i)
            map.SBOUND[i].move(.01f, 0);
        for (unsigned int i = 0; i < map.TEX.size(); ++i)
            map.TEX[i].move(.01f, 0);

        A.move(.01f, 0);
    }

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && !Collision::PixelPerfectTest(C.A_B_T, B, 256))
    {
        // left key is pressed: move our character

        for (unsigned int i = 0; i < map.SBOUND.size(); ++i)
            map.SBOUND[i].move(0, -.01f);
        for (unsigned int i = 0; i < map.TEX.size(); ++i)
            map.TEX[i].move(0, -.01f);

        A.move(0, -.01f);
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) && !Collision::PixelPerfectTest(C.A_B_B, B, 256))

    {
        for (unsigned int i = 0; i < map.SBOUND.size(); ++i)
            map.SBOUND[i].move(0, .01f);
        for (unsigned int i = 0; i < map.TEX.size(); ++i)
            map.TEX[i].move(0, .01f);

        // left key is pressed: move our character
        A.move(0, .01f);
    }
    A_Tex.setPosition(APos.x + 16, APos.y + 16);
    A_Tex.setString(to_string(APos.x) + "," + to_string(APos.y));

    B_Tex.setPosition(BPos.x + 16, BPos.y + 16);
    B_Tex.setString(to_string(BPos.x) + "," + to_string(BPos.y));
    // LEFT         window.draw(C.A_B_L);
    // RIGHT        window.draw(C.A_B_R);
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
    {
        // left key is pressed: move our character
        Debug = true;
    }
    else
    {
        Debug = false;
    }

    window.clear();
    window.draw(map);
    window.draw(A);
    window.draw(B);
    C.A();
    window.draw(C.A_B_R);
    window.draw(C.A_B_L);
    window.draw(C.A_B_T);
    window.draw(C.A_B_B);

    if (Debug) {
        window.draw(A_Tex);
        window.draw(B_Tex);
    }

    for (unsigned int i = 0; i < map.SBOUND.size(); ++i)
        window.draw(map.SBOUND[i]);
    for (unsigned int i = 0; i < map.TEX.size(); ++i)
        window.draw(map.TEX[i]);

    window.display();
}

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

The class code is as fallowed:

```<code>#include "MainH.h"
class TileMap : public sf::Drawable, public sf::Transformable
{
public:

sf::Texture A;
std::vector<sf::Sprite> SBOUND;
std::vector<sf::Text> TEX;

sf::Font FT;
bool load(const std::string& tileset, sf::Vector2u tileSize, const int* tiles, unsigned int width, unsigned int height , sf::Texture& texture)
{

    FT.loadFromFile("arial.ttf");

    A = texture;
    SBOUND.resize(90);
    for (int a = 0; a < 88; a = a + 1) {
        SBOUND[a].setTexture(A);
    }
    TEX.resize(90);
    for (int a = 0; a < 88; a = a + 1) {
        TEX[a].setFont(FT);
        TEX[a].setString("HERE");
        TEX[a].setColor(sf::Color::Red);
        TEX[a].setScale(0.5f,0.5f);
    }

    // load the tileset texture
    if (!m_tileset.loadFromFile(tileset))
        return false;

    // resize the vertex array to fit the level size
    m_vertices.setPrimitiveType(sf::Quads);
    m_vertices.resize(width * height * 4);

    // populate the vertex array, with one quad per tile
    for (unsigned int i = 0; i < width; ++i)
        for (unsigned int j = 0; j < height; ++j)
        {
            // get the current tile number
            int tileNumber = tiles[i + j * width];
            // find its position in the tileset texture
            int tu = tileNumber % (m_tileset.getSize().x / tileSize.x);
            int tv = tileNumber / (m_tileset.getSize().x / tileSize.x);
            // get a pointer to the current tile's quad
            sf::Vertex* quad = &m_vertices[(i + j * width) * 4];

            // define its 4 corners
            quad[0].position = sf::Vector2f(i * tileSize.x, j * tileSize.y);
            quad[1].position = sf::Vector2f((i + 1) * tileSize.x, j * tileSize.y);
            quad[2].position = sf::Vector2f((i + 1) * tileSize.x, (j + 1) * tileSize.y);
            quad[3].position = sf::Vector2f(i * tileSize.x, (j + 1) * tileSize.y);

            if (tileNumber == 2) {
                std::cout << tileNumber << std::endl;
                SBOUND[j].setPosition(sf::Vector2f((i + 1) * tileSize.x, (j + 1) * tileSize.y));

                TEX[j].setPosition(sf::Vector2f(i * tileSize.x, j * tileSize.y));

                sf::Vector2f V;
                V = SBOUND[j].getPosition();
                std::cout << V.x << " , " << V.y << std::endl;

                std::cout << tileSize.x * i << " Tile_X " << std::endl;
                std::cout << tileSize.y * (j+1) << " Tile_Y " << std::endl;

            }

            // define its 4 texture coordinates
            quad[0].texCoords = sf::Vector2f(tu * tileSize.x, tv * tileSize.y);
            quad[1].texCoords = sf::Vector2f((tu + 1) * tileSize.x, tv * tileSize.y);
            quad[2].texCoords = sf::Vector2f((tu + 1) * tileSize.x, (tv + 1) * tileSize.y);
            quad[3].texCoords = sf::Vector2f(tu * tileSize.x, (tv + 1) * tileSize.y);
        }

    return true;
}

private:

virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const
{
    // apply the transform
    states.transform *= getTransform();

    // apply the tileset texture
    states.texture = &m_tileset;

    // draw the vertex array
    target.draw(m_vertices, states);
}

sf::VertexArray m_vertices;
sf::Texture m_tileset;
};
</code>```

The tile index should be on top of every tile that is Id 2. It only covers some and not all of them.

答: Solved: I was just getting the wrong Points for the sprites</p>

Body:
Hey when I am using this code it seems to place my SBOUND in the same spot and not everywhere on the 2 spot that I want it. I have no idea that the problem is and am mostly new to SFML and cant quite understand what is happening. The main code is like this.
`

#include "MainH.h"
int main()
{
int x = 200;
int y = 200;
sf::RenderWindow window(sf::VideoMode(512, 256), "Tilemap");
// create a new vertex
sf::Vertex vertex;

// set its position
vertex.position = sf::Vector2f(10, 50);

// set its color
vertex.color = sf::Color::Red;

// set its texture coordinates
vertex.texCoords = sf::Vector2f(100, 100);

////////////////////////
sf::Sprite A;
sf::Texture AT;
AT.loadFromFile("Red.png");
A.setTexture(AT);
A.setPosition(16.f, 16.f);
sf::Text A_Tex;
sf::Font A_Font;
A_Font.loadFromFile("arial.ttf");
A_Tex.setFont(A_Font);
A_Tex.setColor(sf::Color::Yellow);
A_Tex.setScale(0.35f,0.35f);
/////////////////////////////
sf::Sprite B;
sf::Texture BT;
BT.loadFromFile("Green.png");
B.setTexture(BT);
B.setPosition(30.f, 30.f);
sf::Text B_Tex;
sf::Font B_Font;
B_Font.loadFromFile("arial.ttf");
B_Tex.setFont(A_Font);
B_Tex.setColor(sf::Color::Yellow);
B_Tex.setScale(0.35f, 0.35f);

const int level[] =
{
    5, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0,
    2, 1, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3,
    2, 1, 0, 0, 2, 0, 3, 3, 3, 0, 1, 1, 1, 0, 0, 0,
    2, 1, 1, 0, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 0, 0,
    2, 0, 1, 0, 3, 0, 2, 2, 0, 0, 1, 1, 1, 1, 2, 0,
    2, 0, 1, 0, 3, 0, 2, 2, 2, 0, 1, 1, 1, 1, 1, 1,
    2, 0, 1, 0, 3, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1,
};
sf::Texture COL;
COL.loadFromFile("COL.png");

TileMap map;
if (!map.load("Set.png", sf::Vector2u(16, 16), level, 16, 8, COL))
    return -1;

bool Debug = false;
//////////////////////////////
BorderLine C;
sf::Texture BordS;
sf::Texture BordT;
BordS.loadFromFile("Border.png");
BordT.loadFromFile("TopBD.png");
C.Setup(BordS, 16 ,BordT);
////////////////////////////////
window.setKeyRepeatEnabled(false);

while (window.isOpen())
{
    C.Object = A.getPosition();
    sf::Vector2f APos = A.getPosition();
    sf::Vector2f BPos = B.getPosition();

    sf::Event event;
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
            window.close();
        if (event.type == sf::Event::Resized)
        {
            window.setView(sf::View(sf::FloatRect(0, 0, event.size.width, event.size.height)));
        }

    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) && !Collision::PixelPerfectTest(C.A_B_L, B, 256))
    {
        // left key is pressed: move our character
        A.move(-.01f, 0);
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) && !Collision::PixelPerfectTest(C.A_B_R, B, 256))
    {
        // left key is pressed: move our character
        for (unsigned int i = 0; i < map.SBOUND.size(); ++i)
            map.SBOUND[i].move(.01f, 0);
        for (unsigned int i = 0; i < map.TEX.size(); ++i)
            map.TEX[i].move(.01f, 0);

        A.move(.01f, 0);
    }

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && !Collision::PixelPerfectTest(C.A_B_T, B, 256))
    {
        // left key is pressed: move our character

        for (unsigned int i = 0; i < map.SBOUND.size(); ++i)
            map.SBOUND[i].move(0, -.01f);
        for (unsigned int i = 0; i < map.TEX.size(); ++i)
            map.TEX[i].move(0, -.01f);

        A.move(0, -.01f);
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) && !Collision::PixelPerfectTest(C.A_B_B, B, 256))

    {
        for (unsigned int i = 0; i < map.SBOUND.size(); ++i)
            map.SBOUND[i].move(0, .01f);
        for (unsigned int i = 0; i < map.TEX.size(); ++i)
            map.TEX[i].move(0, .01f);

        // left key is pressed: move our character
        A.move(0, .01f);
    }
    A_Tex.setPosition(APos.x + 16, APos.y + 16);
    A_Tex.setString(to_string(APos.x) + "," + to_string(APos.y));

    B_Tex.setPosition(BPos.x + 16, BPos.y + 16);
    B_Tex.setString(to_string(BPos.x) + "," + to_string(BPos.y));
    // LEFT         window.draw(C.A_B_L);
    // RIGHT        window.draw(C.A_B_R);
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
    {
        // left key is pressed: move our character
        Debug = true;
    }
    else
    {
        Debug = false;
    }

    window.clear();
    window.draw(map);
    window.draw(A);
    window.draw(B);
    C.A();
    window.draw(C.A_B_R);
    window.draw(C.A_B_L);
    window.draw(C.A_B_T);
    window.draw(C.A_B_B);

    if (Debug) {
        window.draw(A_Tex);
        window.draw(B_Tex);
    }

    for (unsigned int i = 0; i < map.SBOUND.size(); ++i)
        window.draw(map.SBOUND[i]);
    for (unsigned int i = 0; i < map.TEX.size(); ++i)
        window.draw(map.TEX[i]);

    window.display();
}

return 0;
}`

The class code is as fallowed:

#include "MainH.h"
class TileMap : public sf::Drawable, public sf::Transformable
{
public:

sf::Texture A;
std::vector<sf::Sprite> SBOUND;
std::vector<sf::Text> TEX;

sf::Font FT;
bool load(const std::string& tileset, sf::Vector2u tileSize, const int* tiles, unsigned int width, unsigned int height , sf::Texture& texture)
{

    FT.loadFromFile("arial.ttf");

    A = texture;
    SBOUND.resize(90);
    for (int a = 0; a < 88; a = a + 1) {
        SBOUND[a].setTexture(A);
    }
    TEX.resize(90);
    for (int a = 0; a < 88; a = a + 1) {
        TEX[a].setFont(FT);
        TEX[a].setString("HERE");
        TEX[a].setColor(sf::Color::Red);
        TEX[a].setScale(0.5f,0.5f);
    }

    // load the tileset texture
    if (!m_tileset.loadFromFile(tileset))
        return false;

    // resize the vertex array to fit the level size
    m_vertices.setPrimitiveType(sf::Quads);
    m_vertices.resize(width * height * 4);

    // populate the vertex array, with one quad per tile
    for (unsigned int i = 0; i < width; ++i)
        for (unsigned int j = 0; j < height; ++j)
        {
            // get the current tile number
            int tileNumber = tiles[i + j * width];
            // find its position in the tileset texture
            int tu = tileNumber % (m_tileset.getSize().x / tileSize.x);
            int tv = tileNumber / (m_tileset.getSize().x / tileSize.x);
            // get a pointer to the current tile's quad
            sf::Vertex* quad = &m_vertices[(i + j * width) * 4];

            // define its 4 corners
            quad[0].position = sf::Vector2f(i * tileSize.x, j * tileSize.y);
            quad[1].position = sf::Vector2f((i + 1) * tileSize.x, j * tileSize.y);
            quad[2].position = sf::Vector2f((i + 1) * tileSize.x, (j + 1) * tileSize.y);
            quad[3].position = sf::Vector2f(i * tileSize.x, (j + 1) * tileSize.y);

            if (tileNumber == 2) {
                std::cout << tileNumber << std::endl;
                SBOUND[j].setPosition(sf::Vector2f((i + 1) * tileSize.x, (j + 1) * tileSize.y));

                TEX[j].setPosition(sf::Vector2f(i * tileSize.x, j * tileSize.y));

                sf::Vector2f V;
                V = SBOUND[j].getPosition();
                std::cout << V.x << " , " << V.y << std::endl;

                std::cout << tileSize.x * i << " Tile_X " << std::endl;
                std::cout << tileSize.y * (j+1) << " Tile_Y " << std::endl;

            }

            // define its 4 texture coordinates
            quad[0].texCoords = sf::Vector2f(tu * tileSize.x, tv * tileSize.y);
            quad[1].texCoords = sf::Vector2f((tu + 1) * tileSize.x, tv * tileSize.y);
            quad[2].texCoords = sf::Vector2f((tu + 1) * tileSize.x, (tv + 1) * tileSize.y);
            quad[3].texCoords = sf::Vector2f(tu * tileSize.x, (tv + 1) * tileSize.y);
        }

    return true;
}

private:

virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const
{
    // apply the transform
    states.transform *= getTransform();

    // apply the tileset texture
    states.texture = &m_tileset;

    // draw the vertex array
    target.draw(m_vertices, states);
}

sf::VertexArray m_vertices;
sf::Texture m_tileset;
};

The tile index should be on top of every tile that is Id 2. It only covers some and not all of them.


问:
Clustering a sparse co-occurrence matrix
I have two N x N co-occurrence matrices (484x484 and 1060x1060) that I have to analyze. The matrices are symmetrical along the diagonal and contain lots of zero values. The non-zero values are integers.

I want to group together the positions that are non-zero. In other words, what I want to do is the algorithm on this link. When order by cluster is selected, the matrix gets re-arranged in rows and columns to group the non-zero values together.

Since I am using Python for this task, I looked into SciPy Sparse Linear Algebra library, but couldn't find what I am looking for.

Any help is much appreciated. Thanks in advance.

答:
If you have a matrix dist with pairwise distances between objects, then you can find the order on which to rearrange the matrix by applying a clustering algorithm on this matrix (http://scikit-learn.org/stable/modules/clustering.html). For example it might be something like:

```<code>from sklearn import cluster
import numpy as np
model = cluster.AgglomerativeClustering(n_clusters=20,affinity="precomputed").fit(dist)
new_order = np.argsort(model.labels_)
ordered_dist = dist[new_order] # can be your original matrix instead of dist[]
ordered_dist = ordered_dist[:,new_order]
</code>```

The order is given by the variable model.labels_, which has the number of the cluster to which each sample belongs. A few observations:

You have to find a clustering algorithm that accepts a distance matrix as input. AgglomerativeClustering is such an algorithm (notice the affinity="precomputed" option to tell it that we are using pre-computed distances).

What you have seems to be a pairwise similarity matrix, in which case you need to transform it to a distance matrix (e.g. dist=1 - data/data.max())

In the example I assumed 20 clusters, you may have to play with this variable a bit. Alternatively, you might try to find the best one-dimensional representation of your data (using e.g. MDS) to describe the optimal ordering of samples.

Body:
If you have a matrix dist with pairwise distances between objects, then you can find the order on which to rearrange the matrix by applying a clustering algorithm on this matrix (http://scikit-learn.org/stable/modules/clustering.html). For example it might be something like:

from sklearn import cluster
import numpy as np
model = cluster.AgglomerativeClustering(n_clusters=20,affinity="precomputed").fit(dist)
new_order = np.argsort(model.labels_)
ordered_dist = dist[new_order] # can be your original matrix instead of dist[]
ordered_dist = ordered_dist[:,new_order]

The order is given by the variable model.labels_, which has the number of the cluster to which each sample belongs. A few observations:

You have to find a clustering algorithm that accepts a distance matrix as input. AgglomerativeClustering is such an algorithm (notice the affinity="precomputed" option to tell it that we are using pre-computed distances).

What you have seems to be a pairwise similarity matrix, in which case you need to transform it to a distance matrix (e.g. dist=1 - data/data.max())

In the example I assumed 20 clusters, you may have to play with this variable a bit. Alternatively, you might try to find the best one-dimensional representation of your data (using e.g. MDS) to describe the optimal ordering of samples.


问:
Using as.Date in R to convert to dates and getting series of "NA"s
Using the following code to try to get my date column into the right format, but it's just returning all of the dates as "NA".

```<code>setwd("C:\\Users\\user\\Documents\\Files\\a")
data <- read.csv("file1.csv")

data$Date <- as.Date(data$Date, format = "d%/m%/Y%")
</code>```

Edit: date values as follows: 11/09/2009

答:
You could try converting the date with the package lubridate </p>

```<code>library(lubridate)
date <- parse_date_time(x = date,
                orders = c("d m y", "d B Y", "mdy"),
                locale = "eng")
</code>```

<p>After you may specify which format you want the date to be: </p>

```<code>character_date <- as.character(as.Date(date, "%m/%d/%Y"), format = "%m/%d/%Y")
</code>```

Body:
Using the following code to try to get my date column into the right format, but it's just returning all of the dates as "NA".

setwd("C:\\Users\\user\\Documents\\Files\\a")
data <- read.csv("file1.csv")

data$Date <- as.Date(data$Date, format = "d%/m%/Y%")

Edit: date values as follows: 11/09/2009

Body:
You could try converting the date with the package lubridate

library(lubridate)
date <- parse_date_time(x = date,
                orders = c("d m y", "d B Y", "mdy"),
                locale = "eng")

After you may specify which format you want the date to be:

character_date <- as.character(as.Date(date, "%m/%d/%Y"), format = "%m/%d/%Y")


问:
Passing Member Function Pointers Between Modules
Just a curiosity question!  This seems to suggest that member function pointers are in fact different sizes pending compiler and compile options used, and this seems to suggest that function pointers are passed just fine between modules, so what about member function pointers?  I mean with all the hassles that are already presented in passing data between modules it would seem rather silly to even attempt this?  Or what about scenarios involving static libraries?  If two different compilers are used am I wrong to assume that any scenario involving the passing of a member function pointer would be fruitless?</p>

答: Member function pointers are quite different beasts from function pointers.  They must encode not only the function pointer to the member function, but must also encode the the correct type for the member function, so that the run-time knows how to call the member-function.  This is very dependent on how the compiler implements classes, and that implementation certainly changes between compiler vendors, and often changes within compilers based on how the compiler is invoked.  </p>

ContentLicense: CC BY-SA 2.5


问:
Wordpress saving button is doing something weird
Every time I use saving button from post editor in wordpress, my browser asks me if I want to leave the page.

I have a few plugins installed, I'm developing a new one. It never happened to me before working on wordpress.

I'm using wp_insert_post hook to do some things every time I save post/page.

EDIT 1

Every time I update a single post, browser shows me an alert telling me If I want to leave the page. I discovered, that the plugin that cause this alert to show it's YOAST.

Can you please give a hand, and tell me what do I have to do to solve this problem?

Thanks,

Ismael

答:
in order to do something every time you publish or update a post in wordpress you have to use save_post:

for example if you want to send an email every time a post or page is updated on your website.

```<code>function my_project_updated_send_email( $post_id ) {

    // If this is just a revision, don't send the email.
    if ( wp_is_post_revision( $post_id ) )
        return;

    $post_title = get_the_title( $post_id );
    $post_url = get_permalink( $post_id );
    $subject = 'A post has been updated';

    $message = "A post has been updated on your website:\n\n";
    $message .= $post_title . ": " . $post_url;

    // Send email to admin.
    wp_mail( 'admin@example.com', $subject, $message );

}
add_action( 'save_post', 'my_project_updated_send_email' );
</code>```

Body:
in order to do something every time you publish or update a post in wordpress you have to use save_post:

for example if you want to send an email every time a post or page is updated on your website.

function my_project_updated_send_email( $post_id ) {

    // If this is just a revision, don't send the email.
    if ( wp_is_post_revision( $post_id ) )
        return;

    $post_title = get_the_title( $post_id );
    $post_url = get_permalink( $post_id );
    $subject = 'A post has been updated';

    $message = "A post has been updated on your website:\n\n";
    $message .= $post_title . ": " . $post_url;

    // Send email to admin.
    wp_mail( 'admin@example.com', $subject, $message );

}
add_action( 'save_post', 'my_project_updated_send_email' );


问:
How to have a global variable coming from db in symfony template?
How can I have a global variable in symfony template?
I did read this
but I prefer to fetch parameter from database, I think this service will be loaded on startup before it can fetch anything from db. Is it possible to do a trick to do so?</p>

答:
As of this day, the class signature has changed. You must implement \ Twig_Extension_GlobalsInterface, without it, your globals won't show up.

```<code>class MyTwigExtension extends \Twig_Extension implements Twig_Extension_GlobalsInterface
{ }
</code>```

Bye!

Body:
As of this day, the class signature has changed. You must implement \ Twig_Extension_GlobalsInterface, without it, your globals won't show up.

class MyTwigExtension extends \Twig_Extension implements Twig_Extension_GlobalsInterface
{ }

Bye!


答: Apps Script add-ons run as the user who installed them. Moving the file from your Drive to someone else's account would require the script to somehow gain access to your account. I don't think Google will ever allow this to happen. However, I'm not sure if your question was really about the add-ons as described here https://developers.google.com/apps-script/add-ons/</p>

Title: Can a google add-on copy files from my Drive to a user's folder? Is there any way to do this?

Body:
Var file = DriveApp.getFileById(file) //in my Drive
DriveApp.getRootFolder.addFile(file); //in user' s Drive


问:
Is there a way to get the original request URL with params in a Filter without Rebuilding
I have a servlet Filter inside a Java EE project and need to obtain the original request url and the URL params. I am currently rebuilding the original URL with the following code, but this feels completely wrong:

```<code>StringBuilder urlBuilder = new StringBuilder(req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+req.getContextPath());
if(req.getParameterMap() != null && req.getParameterMap().size() > 0) urlBuilder.append("?"+getParameterString(req.getParameterMap()));

private StringBuilder getParameterString(Map<String, String[]> params){
    StringBuilder sb = new StringBuilder("");
    for(String key : params.keySet()){
        for(String param : params.get(key)){
            sb.append(String.format("%s=%s&", key, param));
        }
    }
    return sb;
}
</code>```

What I would really like to do is something more like the following:

```<code>req.getUrlWithParams()
</code>```

This seeems better since I am effectively undoing what the servlet container has done parsing the parameters in and all I actually want to do is to receive the original URL unparsed.

答:
If your request object is an instance of HttpServletRequest, you can do this.</p>

```<code>if (req instanceof HttpServletRequest) {
    HttpServletRequest httpReq = (HttpServletRequest) req;
    StringBuffer url = httpReq.getRequestURL();
    if (httpReq.getQueryString() != null) {
        url.append("?");
        url.append(httpReq.getQueryString());
    }
    String urlString = url.toString();
}
</code>```

Body:
I have a servlet Filter inside a Java EE project and need to obtain the original request url and the URL params. I am currently rebuilding the original URL with the following code, but this feels completely wrong:

StringBuilder urlBuilder = new StringBuilder(req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+req.getContextPath());
if(req.getParameterMap() != null && req.getParameterMap().size() > 0) urlBuilder.append("?"+getParameterString(req.getParameterMap()));

private StringBuilder getParameterString(Map<String, String[]> params){
    StringBuilder sb = new StringBuilder("");
    for(String key : params.keySet()){
        for(String param : params.get(key)){
            sb.append(String.format("%s=%s&", key, param));
        }
    }
    return sb;
}

What I would really like to do is something more like the following:

req.getUrlWithParams()

This seeems better since I am effectively undoing what the servlet container has done parsing the parameters in and all I actually want to do is to receive the original URL unparsed.

Body:
If your request object is an instance of HttpServletRequest, you can do this.

if (req instanceof HttpServletRequest) {
    HttpServletRequest httpReq = (HttpServletRequest) req;
    StringBuffer url = httpReq.getRequestURL();
    if (httpReq.getQueryString() != null) {
        url.append("?");
        url.append(httpReq.getQueryString());
    }
    String urlString = url.toString();
}


问:
Ignore the require statement on webpack 2 bundling time and exclude that require statement from the bundled js
I implement a React.Component in a.js. This file will be used for client and server side rendering. Of course a.js has require("a.scss")

Is there a way to do on webpack.config.js only to tell webpack not to read all the scss` require statement during the bundling?

I did try the IgnorePlugin to *.scss. The bundling process is fine but node gives runtime error which is Cannot find module './a.scss'

Here are the unwanted suggestions

I don't want to use DefinePlugin or EnvironmentPlugin because I don't want to wrap the require("a.scss") inside an if statement

I don't want to use ExtractTextWebpackPlugin to extract the scss which is I am currently using. Let node can run the bundled js perfectly.

答:
This is the solution</p>

```<code>{
  "test": /\.s?css$/,
  "use": "null-loader"
}
</code>```

Body:
This is the solution

{
  "test": /\.s?css$/,
  "use": "null-loader"
}


问:
Is there a method in Ruby Object to pass itself to a block or proc?
I think it would be natural to have in Ruby something like:

```<code>class Object
  def yield_self
    yield(self)
  end
end
</code>```

Does there exist a method like this by any chance?  (I haven't found.)  Does anybody else think it would be nice to have it?

答:
yield_self has been added to ruby core a month ago as of June 2017. https://bugs.ruby-lang.org/projects/ruby-trunk/repository/revisions/58528

It's in ruby 2.5.0 after revision number 58528, although I'm not exactly sure how to get that code yet. Perhaps if someone knows how they can edit this answer

Body:
I think it would be natural to have in Ruby something like:

class Object
  def yield_self
    yield(self)
  end
end

Does there exist a method like this by any chance?  (I haven't found.)  Does anybody else think it would be nice to have it?


问:
What measurement do you use in your development process to determine *Doneness* of your software?
I just finished listening to a very eye-opening podcast on Hanselminutes about the definition of "Done". So my question to everyone is "When do you consider a piece of software to be "Done"? Is it when it's fully unit tested? Is it when it's completely documented? What measurement do you use in your development process to determine Doneness of your software?

答:
Surely dependent on context and purpose of the software?

Lunar Lander (the real thing) would have a very different definition of Done to Lunar Lander the Flash game.

Where I work, DONE is defined by a committee of non-technical managers.  You can imagine the fun and games.

OwnerDisplayName: Micah

OwnerDisplayName: edg


问:
if possible start VPN connection in iPhone app?
as topic, I want establish VPN connection in iPhone app, if it possible? but seem not public API for this purpose ...

anyone give tip, thanks.

答:
I've seen RDP over VPN using the iPhone (though I haven't set it up myself) and Cisco indicates support for VPN connections from iPhone on their ASA series:

And Apple provides instructions.

So VPN connections using a variety of protocols are definitely possible. However, initiating the connection programmatically is a different matter.

I did some additional reading (including old posts here on SO like VPN connection with Objective-C).

The more that I think about it, allowing an application to quietly initiate a VPN connection could pose a big security risk. I would be surprised to see API support for it.

However, creating your own VPN client on the iPhone (though MUCH more difficult than making an API call) is still theoretically possible.


问:
Moving Element more to the left without moving the element through resizes

Attempting to resize the browser and i cannot seem to keep the div "stickyslider" within the page when i shrink past the edge of the "green".

yes i know its the padding, but is there anyway to put the slider in that position without it resizing it until both elements (menu and slider) are the full width

I am new to this so my code is fairly disgusting.

but as you can tell the slider, drops down.

any critique on how i'm doing things is much appreciated.

a{
     color: black;
 }
.menu{
    display: inline-table;
    padding-top: 15%;
    max-width: 150px;
}

.stickyslider{
    padding-top: 15%;
    padding-right: 25%;
    padding-bottom: 15%;
    float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>

    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="CSS/style.css">
</head>
<body>
<div class="container">
    <nav class="menu">
        <a><u>name</u></a><br>
        <a>123 fake street</a><br>
        <a>+61 4 00000000</a><br>
        <br>
        <br>
        <a></a><br>
        <a></a><br>
        <a></a><br>
        <br>
        <a>Example1</a><br>
        <a>Example2</a><br>
        <a>Example3</a><br>
        <br>
        <br>
        <a>Example4</a><br>
        <a>Example5</a><br>
        <a>Example6</a><br>

        <a>Example7</a><br>
        <a>Example8</a><br>
        <a>Example9</a><br>
    </nav>
    <div class="stickyslider">
    <div id="myCarousel" class="carousel slide" data-ride="carousel">
        <!-- Indicators -->
        <ol class="carousel-indicators">
            <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
            <li data-target="#myCarousel" data-slide-to="1"></li>
            <li data-target="#myCarousel" data-slide-to="2"></li>
            <li data-target="#myCarousel" data-slide-to="3"></li>
        </ol>
        <div class="carousel-inner" role="listbox">
            <div class="item active">
                <img src="http://www.dailymobile.net/wp-content/uploads/wallpapers/android-640x480-wallpapers/android-640x480-wallpaper-4582.jpg" alt="architecture">
            </div>

            <div class="item">
                <img src="http://www.dailymobile.net/wp-content/uploads/wallpapers/android-640x480-wallpapers/android-640x480-wallpaper-4582.jpg" alt="more architecture">
            </div>

            <div class="item">
                <img src="http://www.dailymobile.net/wp-content/uploads/wallpapers/android-640x480-wallpapers/android-640x480-wallpaper-4582.jpg" alt="heaps architecture">
            </div>

            <div class="item">
                <img src="http://www.dailymobile.net/wp-content/uploads/wallpapers/android-640x480-wallpapers/android-640x480-wallpaper-4582.jpg" alt="architecture">
            </div>
        </div>

        <!-- Left and right controls -->

            <span class="glyphicon glyphicon-chevron-left"></span>

            <span class="glyphicon glyphicon-chevron-right"></span>

    </div>
        </div>
</div>

</body>
</html></code>```

答:
```<code>.stickyslider{
padding-top: 15%;
padding-right: 25%;
padding-bottom: 15%;
max-width: 20%;
float: right;
}
</code>```

Adding a max width is what worked for this code block.

Body:
Attempting to resize the browser and i cannot seem to keep the div "stickyslider" within the page when i shrink past the edge of the "green".

yes i know its the padding, but is there anyway to put the slider in that position without it resizing it until both elements (menu and slider) are the full width

I am new to this so my code is fairly disgusting.

but as you can tell the slider, drops down.

any critique on how i'm doing things is much appreciated.

a{
     color: black;
 }
.menu{
    display: inline-table;
    padding-top: 15%;
    max-width: 150px;
}

.stickyslider{
    padding-top: 15%;
    padding-right: 25%;
    padding-bottom: 15%;
    float: right;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <link rel="stylesheet" href="CSS/style.css">

        name

        123 fake street

        +61 4 00000000

        Example1

        Example2

        Example3

        Example4

        Example5

        Example6

        Example7

        Example8

        Example9

Body:
.stickyslider{
padding-top: 15%;
padding-right: 25%;
padding-bottom: 15%;
max-width: 20%;
float: right;
}

Adding a max width is what worked for this code block.


问:
Increase time complexity to overcome space complexity
So I have an array 'a0' of size let's say 105, and now I have to make some changes in this array. The ith change could be calculated using a function f(ai-1) to give ai in O(1) time, Where aj denotes array 'a' after jth change has been made to it. Meaning that ai could be calculated if we know ai-1 in constant time. I know that I have to make 105 changes beforehand.

Now the problem asks me to answer large number of queries such as ai[p]-aj[q], where ax[y], represents yth element of the array after xth change has been made to the array a0.

Now if I had space of the order of 1010, I could easily solve this problem in O(1) by storing all the 105 arrays beforehand but I don't (generally) have that kind of space. And I could also answer these queries by each time generating ai and aj from scratch and answering the queries but I can't afford that kind of time complexity either, so I was wondering if I could monitor this problem using some data-structure.

EDIT: Example:

We define an array B= {1,3,1,4,2,6}, and we define aj as the array storing the frequency of ith number after jth element has been added to B. That is, a0={0,0,0,0,0,0} now a1={1,0,0,0,0,0},  a2={1,0,1,0,0,0},  a3={2,0,1,0,0,0} a4={2,0,1,1,0,0} a5={2,1,1,1,0,0} and a6={2,1,1,1,0,1}.

f(aj) just adds a an element to B and updates the value of aj-1.

答:
If there is some a maximum number of states N, then checkpoints are a good way to go. For instance, if N=100,000, you might have:

```<code>c0      = [3, 5, 7, 1, ...]
c100   = [1, 4, 9, 8, ...]
c200   = [9, 7, 1, 2, ...]
...
c10000 = [1, 1, 4, 6, ...]
</code>```

Now you have 1000 checkpoints. You can find the nearest checkpoint to an arbitrary state x in O(1) time and reconstruct x in at most 99 operations.

Riffing off of my comment on your question and John Zwinck's answer, if your mutating function f(*) is expensive and its effects are limited to only a few elements, then you could store the incremental changes. Doing so won't decrease the time complexity of the algorithm, but may reduce the run-time.

If you had unlimited space, you would just store all of the checkpoints. Since you do not, you'll have to balance the number of checkpoints against the incrementals appropriately. That will require some experimentation, probably centered around determining how expensive f(*) is and the extent of its effects.

Another option is to look at query behavior. If users tend to query the same or nearby locations repeatedly, you may be able to leverage an LRU (least-recently used) cache.

Body:
If there is some a maximum number of states N, then checkpoints are a good way to go. For instance, if N=100,000, you might have:

c0      = [3, 5, 7, 1, ...]
c100   = [1, 4, 9, 8, ...]
c200   = [9, 7, 1, 2, ...]
...
c10000 = [1, 1, 4, 6, ...]

Now you have 1000 checkpoints. You can find the nearest checkpoint to an arbitrary state x in O(1) time and reconstruct x in at most 99 operations.

Riffing off of my comment on your question and John Zwinck's answer, if your mutating function f(*) is expensive and its effects are limited to only a few elements, then you could store the incremental changes. Doing so won't decrease the time complexity of the algorithm, but may reduce the run-time.

If you had unlimited space, you would just store all of the checkpoints. Since you do not, you'll have to balance the number of checkpoints against the incrementals appropriately. That will require some experimentation, probably centered around determining how expensive f(*) is and the extent of its effects.

Another option is to look at query behavior. If users tend to query the same or nearby locations repeatedly, you may be able to leverage an LRU (least-recently used) cache.


Title: group data by months of 6 years

Body:
i have a csv file containing 6 years of data starting from 01/01/2006 to 01/01/2011 and i need to group data by each month of the 6 years.
here's an overview of my csv file :

 timestamp,heure,lat,lon,impact,type
 2006-01-01 00:00:00,13:58:43,33.837,-9.205,10.3,1
 2006-01-02 00:00:00,00:07:28,34.5293,-10.2384,17.7,1
 2007-02-01 00:00:00,23:01:03,35.0617,-1.435,-17.1,2
 2007-02-02 00:00:00,01:14:29,36.5685,0.9043,36.8,1
 2008-01-01 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1
 2008-01-02 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1
 ....
 2011-12-31 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1

and here's the output desired :

 month 01   10 (counts of the columns)
 month 02   20
 .....
 month 12   30

any ideas ??

Body:
Consider the sample dataframe df

np.random.seed([3,1415])

tidx = pd.date_range('2006-01-01', '2011-01-01', name='Date')

df = pd.DataFrame(dict(
        heure=pd.to_timedelta(np.random.randint(24*60*60, size=len(tidx))),
        lat=np.random.rand(len(tidx)) * 10 + 30,
        lon=np.random.rand(len(tidx)) * 10 - 20,
        impact=np.random.rand(len(tidx)),
        type=np.random.randint(3, size=len(tidx))
    ), tidx)

df.head()

                     heure    impact        lat        lon  type
Date
2006-01-01 00:00:00.000037  0.312643  39.324254 -14.715073     1
2006-01-02 00:00:00.000019  0.121450  30.560726 -10.879014     0
2006-01-03 00:00:00.000060  0.080082  38.489212 -11.899611     1
2006-01-04 00:00:00.000021  0.270159  34.832683 -14.924849     0
2006-01-05 00:00:00.000066  0.112194  32.193704 -19.083123     0

Use df.index.month to group by

df.groupby(df.index.month).size()

Date
1     156
2     141
3     155
4     150
5     155
6     150
7     155
8     155
9     150
10    155
11    150
12    155
dtype: int64

You can do all the things you'd normally do with a group by... Here is an example using describe

df.groupby(df.index.strftime('%B')).impact.describe()

      count      mean       std       min       25%       50%       75%       max
Date
1     156.0  0.529216  0.279498  0.003298  0.292654  0.538437  0.774256  0.998507
2     141.0  0.501540  0.295111  0.001063  0.243723  0.491919  0.727560  0.999231
3     155.0  0.516168  0.306878  0.001178  0.227668  0.556316  0.783676  0.997126
4     150.0  0.472035  0.263685  0.004031  0.246738  0.491169  0.665894  0.987965
5     155.0  0.523897  0.320709  0.003486  0.221323  0.538594  0.841909  0.994280
6     150.0  0.542496  0.297215  0.003550  0.273098  0.589802  0.807086  0.995538
7     155.0  0.513857  0.285404  0.000933  0.285383  0.519170  0.746735  0.999551
8     155.0  0.516404  0.284407  0.004662  0.288900  0.545429  0.739392  0.996601
9     150.0  0.490965  0.299312  0.011958  0.206851  0.487708  0.737785  0.993217
10    155.0  0.513743  0.304779  0.010712  0.199390  0.563746  0.796143  0.995488
11    150.0  0.465428  0.271936  0.006345  0.221753  0.470793  0.684867  0.995886
12    155.0  0.498415  0.301704  0.004538  0.215730  0.471139  0.757360  0.997268


问:
dropzone and jquery load method
I have this code for dropzone. It works. Then on complete event it has to load a php file. I am not able to pass the content of a variable. It has an id that i need to fetch data from a database. Here the code:

```<code>Dropzone.options.myform = {
  maxFilesize:5,
  maxFiles: 1,
  acceptedFiles: ".jpeg,.jpg,.png,.gif",
  addRemoveLinks: true,
  previewsContainer: "#div_preview",
  dictDefaultMessage: "Premi per caricare le foto",
  params: '#hiddenId',
  init: function() {
    this.hiddenFileInput.removeAttribute('multiple');
  },
  complete: function(file) {
    var a = $("#hiddenId").val();
    alert(a);
    $('#div_preview').show();
    $("#div_preview").html("");
    $("#div_preview").load('php/load_cover_auto.php',{'id': '<?php echo $a; ?>' });
  }
};
</code>```

with firebug i get this reply from the server:

```<code>id<?php echo $a; ?>
</code>```

I tried also to pass variable in this way but with no luck:

```<code>$("#div_preview").load('php/load_cover_auto.php?id=a');
</code>```

What am i doing wrong?

答:
Ok I solved my problem and the solution is this one:

```<code>$("#div_preview").load('php/load_cover_auto.php',{'id': a});
</code>```

that's the right code!

Title: dropzone and jquery load method

Body:
I have this code for dropzone. It works. Then on complete event it has to load a php file. I am not able to pass the content of a variable. It has an id that i need to fetch data from a database. Here the code:

Dropzone.options.myform = {
  maxFilesize:5,
  maxFiles: 1,
  acceptedFiles: ".jpeg,.jpg,.png,.gif",
  addRemoveLinks: true,
  previewsContainer: "#div_preview",
  dictDefaultMessage: "Premi per caricare le foto",
  params: '#hiddenId',
  init: function() {
    this.hiddenFileInput.removeAttribute('multiple');
  },
  complete: function(file) {
    var a = $("#hiddenId").val();
    alert(a);
    $('#div_preview').show();
    $("#div_preview").html("");
    $("#div_preview").load('php/load_cover_auto.php',{'id': '<?php echo $a; ?>' });
  }
};

with firebug i get this reply from the server:

id<?php echo $a; ?>

I tried also to pass variable in this way but with no luck:

$("#div_preview").load('php/load_cover_auto.php?id=a');

What am i doing wrong?

Body:
Ok I solved my problem and the solution is this one:

$("#div_preview").load('php/load_cover_auto.php',{'id': a});

that's the right code!


问:
Why does it seem two values are being set to a single variable when using setInterval?
I have this code that listens for a socket emit and then starts an interval loop every 5 seconds. The interval uses jquery to change the text on the page to a value pulled from the socket emit.

```<code>   socket.on("activeBid", function(data) {
        $('#noActiveBid').hide();
        $('#activeBid1').hide();
        $('#activeBid').show();
        $('#activeBidValue').text(data.activeBid);
        setInterval(delayTime, 5000);
        function delayTime () {
          $('#ago2').text(moment(data.bidTime).fromNow());
        }
  });
</code>```

The code gets executed every 5 seconds and everything works well until I emit another socket event, causing a new data value (data.bidTime) to be sent over. The old bidTime value is staying in the interval and the new one is also getting added in so the text on the page changes between the two values every 5 seconds. Why is this?

When I console.log the data.bidTime value and then cause another emit causing another value to be sent over, I get two different values logged to the console every 5 seconds.

答:
setInterval creates a new interval that executes delayTime every 5 seconds. When calling activeBid again, the old interval keeps existing. You probably want to remove the first interval before creating a new one:

```<code>var interval;
socket.on("activeBid", function(data) {
    clearInterval(interval);

    $('#noActiveBid').hide();
    $('#activeBid1').hide();
    $('#activeBid').show();
    $('#activeBidValue').text(data.activeBid);

    function delayTime () {
      $('#ago2').text(moment(data.bidTime).fromNow());
    }

    interval = setInterval(delayTime, 5000);
});
</code>```

Body:
I have this code that listens for a socket emit and then starts an interval loop every 5 seconds. The interval uses jquery to change the text on the page to a value pulled from the socket emit.

   socket.on("activeBid", function(data) {
        $('#noActiveBid').hide();
        $('#activeBid1').hide();
        $('#activeBid').show();
        $('#activeBidValue').text(data.activeBid);
        setInterval(delayTime, 5000);
        function delayTime () {
          $('#ago2').text(moment(data.bidTime).fromNow());
        }
  });

The code gets executed every 5 seconds and everything works well until I emit another socket event, causing a new data value (data.bidTime) to be sent over. The old bidTime value is staying in the interval and the new one is also getting added in so the text on the page changes between the two values every 5 seconds. Why is this?

When I console.log the data.bidTime value and then cause another emit causing another value to be sent over, I get two different values logged to the console every 5 seconds.

Body:
setInterval creates a new interval that executes delayTime every 5 seconds. When calling activeBid again, the old interval keeps existing. You probably want to remove the first interval before creating a new one:

var interval;
socket.on("activeBid", function(data) {
    clearInterval(interval);

    $('#noActiveBid').hide();
    $('#activeBid1').hide();
    $('#activeBid').show();
    $('#activeBidValue').text(data.activeBid);

    function delayTime () {
      $('#ago2').text(moment(data.bidTime).fromNow());
    }

    interval = setInterval(delayTime, 5000);
});


问:
How to write a result of function in the global environment in R
I have these datasets: A <- 4, B <- 3, C <- 2.

So I put them in a list
D<-list(A,B,C) and want to apply this function:

```<code>s<-function(x) {
    t<-8
    x<-as.data.frame(x*t)
}

lapply(D,s)
</code>```

when I apply the lapply function it just print them.

How can I make it saving the result in the global environment instead of printing them?

So the result should be A with value of 32 B with value of 24 C with value of 16.

答:
Instead of lapply(D,s), use:

```<code>D <- lapply(D, s)
names(D) <- c("A", "B", "C")
list2env(D, envir = .GlobalEnv)
</code>```

Body:
I have these datasets: A <- 4, B <- 3, C <- 2.

So I put them in a list
D<-list(A,B,C) and want to apply this function:

s<-function(x) {
    t<-8
    x<-as.data.frame(x*t)
}

lapply(D,s)

when I apply the lapply function it just print them.

How can I make it saving the result in the global environment instead of printing them?

So the result should be A with value of 32 B with value of 24 C with value of 16.

Body:
Instead of lapply(D,s), use:

D <- lapply(D, s)
names(D) <- c("A", "B", "C")
list2env(D, envir = .GlobalEnv)


答:
it would work:</p>

```<code>df["month"]=df["timestamp"].dt.month
df.groupby(["month"].size()
</code>```

Title: group data by months of 6 years

Body:
it would work:

df["month"]=df["timestamp"].dt.month
df.groupby(["month"].size()


问:
readyState does not get past 1
Trying to put data into an XML through javascripts open() function.

but The website does not get past readyState 1,

Below is the the Javascript code

```<code>function addItem()
{
    var name = document.getElementById('Iname').value;
    var price = document.getElementById('Iprice').value;
    var quantity = document.getElementById('Iquantity').value;
    var description = document.getElementById('Idescription').value;
    xHRObject.open("GET", "listing.php", true);
    xHRObject.onreadystatechange = function() {
        if (xHRObject.readyState == 4 && xHRObject.status == 200)
        {
            document.getElementById('Information').innerHTML = xHRObject.responseText;
            xHRObject.send(null);
        }
    }
}
</code>```

I do not know if it is an error with the PHP, but its quite large so i will only post it in if required.

答: This was an error with the browser functionality, worked fine in firefox.</p>

Title: readyState does not get past 1

Body:
Trying to put data into an XML through javascripts open() function.

but The website does not get past readyState 1,

Below is the the Javascript code

function addItem()
{
    var name = document.getElementById('Iname').value;
    var price = document.getElementById('Iprice').value;
    var quantity = document.getElementById('Iquantity').value;
    var description = document.getElementById('Idescription').value;
    xHRObject.open("GET", "listing.php", true);
    xHRObject.onreadystatechange = function() {
        if (xHRObject.readyState == 4 && xHRObject.status == 200)
        {
            document.getElementById('Information').innerHTML = xHRObject.responseText;
            xHRObject.send(null);
        }
    }
}

I do not know if it is an error with the PHP, but its quite large so i will only post it in if required.


问:
Cannot connect to localhost with cURL on Command Prompt
I've just installed cURL on my hard-drive in order to use for testing with my localhost (on the command prompt). However I cannot connect to any port. You can see the directory and my input below:

C:\Users\me\curl\src>curl -v http://localhost:9000

which gives me:

Rebuilt URL to: http://localhost:9000/

timeout on name lookup is not supported

Trying ::1...

TCP_NODELAY set

Trying 127.0.0.1...

TCP_NODELAY set

connect to ::1 port 9000 failed: Connection refused

connect to 127.0.0.1 port 9000 failed: Connection refused

Failed to connect to localhost port 9000: Connection refused

Closing connection 0 curl: (7) Failed to connect to localhost port 9000: Connection refused

Perhaps I should have added that  I am using IntelliJ and have since enabled cURL on the harddrive (allowing me to access it from any directory); prompting me to try the following:

C:\Users\me\scala\play\my-project>curl -v http://localhost:9000/

which returns:

timeout on name lookup is not supported

Trying ::1...

TCP_NODELAY set

connect to ::1 port 9000 failed: Connection refused

Trying 127.0.0.1...

TCP_NODELAY set

connect to 127.0.0.1 port 9000 failed: Connection refused

Failed to connect to localhost port 9000: Connection refused

Closing connection 0 curl: (7) Failed to connect to localhost port 9000: Connection refused

So it seems that port 9000 is not open. And I am now thinking that this needs to be configured within intelliJ - here - but this looks as though it is only supported on the Ultimate Edition. This might be the cause of the issue that I am having. It may be helpful to others but it would be good to be sure of this if anyone does have any more information.

答:
Try the following server code while running curl:

```<code>import java.net._
import java.io._
import scala.io._

val server = new ServerSocket(9000)
while (true) {
    val serv = server.accept()

    val in = new BufferedSource(serv.getInputStream()).getLines()
    val out = new PrintStream(serv.getOutputStream())

    out.println(in.next())
    out.flush()
    serv.close()
}
</code>```

Body:
Try the following server code while running curl:

import java.net._
import java.io._
import scala.io._

val server = new ServerSocket(9000)
while (true) {
    val serv = server.accept()

    val in = new BufferedSource(serv.getInputStream()).getLines()
    val out = new PrintStream(serv.getOutputStream())

    out.println(in.next())
    out.flush()
    serv.close()
}


问:
Using fgets() to read multiple lines. How to go to the Next line?
So I am opening a file that contains cards data for a card game I am designing for my assignment, basically each line contains 104 characters and each line is equal to a deck of card.

I'm using a char **** because of

number of decks

num of players (4)

num of cards (13)

card is represented like 9H, 3D means nine of hearts and three of diamonds, so it uses 2 characters.

I want to use fgets() to read multiple lines but I'm not sure if this works...

for loop is just the way how the deckfile is set, I just want to know if the fgets will go to the next line when it hits \n...

```<code>    di->cards = (char ****)malloc(sizeof(char***) * di->numDecks);
    for (i = 0; i < di->numDecks; i++) {
        di->cards[i] = (char ***)malloc(sizeof(char**) * 4);
        for (j = 0; j < 4, j++) {
            di->cards[i][j] = (char **)malloc(sizeof(char*) * 13);
            for (k = 0, k < 13, k++) {
                di->cards[i][j][k] = (char *)malloc(sizeof(char) * 3);
            }
        }
    }

    for (i = 0; i < di->numDecks, i++) {
        for (j = 0; j < 13, j++) {
            for (k = 0; k < 4; k++) {
                while ((fgets(cards[i][k][j], 3, di->deckFile)) != NULL);
            }
        }
    }
</code>```

答: If you want to take the fgets input and input all of it into an array of arrays or string array how could you do that. I have tried different things but get seg faults</p>

ContentLicense: CC BY-SA 4.0

Body:
So I am opening a file that contains cards data for a card game I am designing for my assignment, basically each line contains 104 characters and each line is equal to a deck of card.

I'm using a char **** because of

number of decks

num of players (4)

num of cards (13)

card is represented like 9H, 3D means nine of hearts and three of diamonds, so it uses 2 characters.

I want to use fgets() to read multiple lines but I'm not sure if this works...

for loop is just the way how the deckfile is set, I just want to know if the fgets will go to the next line when it hits \n...

    di->cards = (char ****)malloc(sizeof(char***) * di->numDecks);
    for (i = 0; i < di->numDecks; i++) {
        di->cards[i] = (char ***)malloc(sizeof(char**) * 4);
        for (j = 0; j < 4, j++) {
            di->cards[i][j] = (char **)malloc(sizeof(char*) * 13);
            for (k = 0, k < 13, k++) {
                di->cards[i][j][k] = (char *)malloc(sizeof(char) * 3);
            }
        }
    }

    for (i = 0; i < di->numDecks, i++) {
        for (j = 0; j < 13, j++) {
            for (k = 0; k < 4; k++) {
                while ((fgets(cards[i][k][j], 3, di->deckFile)) != NULL);
            }
        }
    }