问:
Is custom property documentation in tsx files possible?
Similar to how the ide helps with descriptions when i document a function like so.

```<code>/**
 * My Test fn
 * @param a - some description here
 */
function Test(a) {}
</code>```

I would like the ide to show a description in the following scenario but I cannot get it to say anything except "(JSX Attribute) test: boolean"

```<code>interface TestProps {
    /** Some comment here */
    test: boolean;
}
class TestComp extends React.Component<TestProps, any> {
    render() {
        return <span>{this.props.test}</span>
    }
}

const test = (props) => (
    <div><TestComp test={true} /></div>
)
</code>```

Is there any way to get it to show the description when helping out with the test property?

Examples:

Notice the bottom image has -some description here and top doesn't

答:
TypeScript uses JSDoc. /* Some comment here */ is not valid JSDoc. /** Some comment here */ is the right way to do it.

Bug in VSCode / TypeScript

Beyond the fact that the comment was wrong. There was a bug that failed to show docs that has been fixed in TypeScript / VSCode.

More on JSDOC

http://usejsdoc.org/about-getting-started.html

Body:
Similar to how the ide helps with descriptions when i document a function like so.

/**
 * My Test fn
 * @param a - some description here
 */
function Test(a) {}

I would like the ide to show a description in the following scenario but I cannot get it to say anything except "(JSX Attribute) test: boolean"

interface TestProps {
    /** Some comment here */
    test: boolean;
}
class TestComp extends React.Component<TestProps, any> {
    render() {
        return {this.props.test}
    }
}

const test = (props) => (

<TestComp test={true} />

)

Is there any way to get it to show the description when helping out with the test property?

Examples:

Notice the bottom image has -some description here and top doesn't


来源: stackexchange

问:
Getting a List from another class
I've been trying to figure out how to make a List from classA accessible for ClassB
I've tried creating an instance/object of the list but it always returns empty when I get the size of the list (while in the main class its not empty).

Example:

ClassA:

```<code>List<String> players = new ArrayList<String>();
</code>```

If i used players.size() here it would return 2 for example

in ClassB I tried the following:

```<code> ClassA classA = new ClassA();
 List<String> newList = classA.players;
</code>```

newList.size() will always return 0 no matter what.

I've also tried using a getter but that doesn't seem to make a difference.

Example:

ClassA:

```<code>List<String> players = new ArrayList<String>();
public List<String> getList(){
    return this.players;
}
</code>```

ClassB:

```<code>ClassA.getList().size()
</code>```

This will also always return 0

How would I properly do this? I tried using a static and that seemed to work but i've been told:

"Static is not the right tool for the job. It's a memory management
  tool, not an access modifier."

He told me:

Instead of static and instead of creating new instances, you can pass
  instances to other classes by adding them as parameters to the
  constructor

However I don't really get what he means. If someone could explain this with an example that would be amazing. Thanks in advance!

Edit: Since a lot of you don't quite get where i want to go with this i'll post my source:
refered to as ClassA in the example

```<code>public class TeamManager {

String prefix = new Messages().prefix;
List<String> players = new ArrayList<String>();
List<String> human = new ArrayList<String>();
List<String> infected = new ArrayList<String>();

void join(Player p){
    if(!players.contains(p.getName())){
        players.add(p.getName());
        teleportToLobby(p);
        for (String temp : players) {
            Bukkit.getPlayer(temp).sendMessage("§e§l"+p.getName()+ " has joined infection. §7("+players.size()+"/16)");
        }
    }else{
        p.sendMessage(prefix + "§cFailed. You are already in the game!");
    }
}
void leave(Player p){
    if(players.contains(p.getName())){
        p.teleport(Bukkit.getWorlds().get(0).getSpawnLocation());
        players.remove(p.getName());
        for (String temp : players) {
            Bukkit.getPlayer(temp).sendMessage("§7§l"+p.getName()+ " has left infection. §7("+players.size()+"/16)");
        }
    }else{
        p.sendMessage(prefix + "§cYou are not in a game!");
    }
}
void addToHumans(String playername){
    human.add(playername);
}
void removeFromHumans(String playername){
    human.remove(playername);
}
void addToInfected(String playername){
    infected.add(playername);
}
void removeFromInfected(String playername){
    infected.remove(playername);
}

void teleportToLobby(Player p){
    Location lobby = getLocFromConfig("lobby");
    if(lobby != null){
        p.teleport(lobby);
        p.sendMessage(prefix + "§aSuccessfully added to game!");
    }else{
        p.sendMessage(prefix + "§cLobby not set! Make sure to set a lobby using /infection setlobby");
    }
}
void startGame(){
    /*if(human.size() >= 4){
    }*/
    for (String temp : players) {
        Bukkit.getPlayer(temp).sendMessage("Game will start shortly!");
    }
}
Location getLocFromConfig(String locationName){
    if(Main.plugin.getConfig().get("lobby") != null){
        double x = Main.plugin.getConfig().getInt(locationName+".x");
        double y = Main.plugin.getConfig().getInt(locationName+".y");
        double z = Main.plugin.getConfig().getInt(locationName+".z");
        World world = Main.plugin.getServer().getWorld(Main.plugin.getConfig().getString(locationName+".world"));
        Location l = new Location(world, x, y, z);
        return l;
    }else{
        Bukkit.getLogger().warning("[Infection] Lobby has not been set!");
        return null;
    }
}
int getPlayersInLobby(){
    return players.size();
}

public List<String> getPlayers(){
    List<String> players = this.players;
    return players;
}
public List<String> getHumans(){
    return human;
}
public List<String> getInfected(){
    return infected;
}
</code>```

}

Events class (referred to in the example as ClassB)

```<code>public class Events implements Listener{

TeamManager teamman = new TeamManager();
List<String> players = teamman.getPlayers();
List<String> humans = teamman.getHumans();
List<String> infected = teamman.getInfected();
@EventHandler
public void onPlayerJoin(PlayerJoinEvent e){
    //Player p = (Player) e.getPlayer();
    //e.setJoinMessage("["+lvl+"]" + e.getPlayer().getName() +"has joined the game!");
    //p.setDisplayName("[lvl1]"+p.getName());

}
@EventHandler
public void onPlayerDamage(EntityDamageByEntityEvent  e){
    if(e.getEntity() instanceof Player){
        Player p = (Player) e.getEntity();
        Bukkit.getServer().broadcastMessage("Players: "+ players);
        if(players.contains(p.getName())){
            if((p.getHealth() - p.getLastDamage()) < 1){
                for (String temp : players) {
                    Bukkit.getPlayer(temp).sendMessage("§c"+p.getName()+" got infected by "+p.getKiller().getName()+"!");
                }
                e.setCancelled(true);
                 p.setHealth(20);
                 teamman.addToInfected(p.getName());
                 teamman.removeFromHumans(p.getName());
                 p.sendMessage("§cYou have been infected!!");
            }
        }
    }
}
</code>```

}

As said above i want to be able to access the lists from TeamManager and use them in Events. And as explained players is empty in the Events class. I hope this helps.

答:
The list of A will always be empty, because you are access a list of a new instance. If you want get a list A, you have send a list A as parameter to class B. Example:</p>

```<code>class ClassA{
 List<String> players;
 ClassA(){
  players = new ArrayList<>();
 }
 public List getPlayers(){
  return this.players;
 }
}

class ClassB{
  private List<String> playersA;

  ClassB(List playersA){
   this.playersA = playersA;
 }
}

// In your main code

ClassA classA = new ClassA();
ClassB classB;
List<String> players = classA.getPlayers();
players.add("P1");
players.add("P2");

classB = new ClassB(players);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Getting a List from another class

Body:
I've been trying to figure out how to make a List from classA accessible for ClassB
I've tried creating an instance/object of the list but it always returns empty when I get the size of the list (while in the main class its not empty).

Example:

ClassA:

List<String> players = new ArrayList<String>();

If i used players.size() here it would return 2 for example

in ClassB I tried the following:

 ClassA classA = new ClassA();
 List<String> newList = classA.players;

newList.size() will always return 0 no matter what.

I've also tried using a getter but that doesn't seem to make a difference.

Example:

ClassA:

List<String> players = new ArrayList<String>();
public List<String> getList(){
    return this.players;
}

ClassB:

ClassA.getList().size()

This will also always return 0

How would I properly do this? I tried using a static and that seemed to work but i've been told:

"Static is not the right tool for the job. It's a memory management
  tool, not an access modifier."

He told me:

Instead of static and instead of creating new instances, you can pass
  instances to other classes by adding them as parameters to the
  constructor

However I don't really get what he means. If someone could explain this with an example that would be amazing. Thanks in advance!

Edit: Since a lot of you don't quite get where i want to go with this i'll post my source:
refered to as ClassA in the example

public class TeamManager {

String prefix = new Messages().prefix;
List<String> players = new ArrayList<String>();
List<String> human = new ArrayList<String>();
List<String> infected = new ArrayList<String>();

void join(Player p){
    if(!players.contains(p.getName())){
        players.add(p.getName());
        teleportToLobby(p);
        for (String temp : players) {
            Bukkit.getPlayer(temp).sendMessage("§e§l"+p.getName()+ " has joined infection. §7("+players.size()+"/16)");
        }
    }else{
        p.sendMessage(prefix + "§cFailed. You are already in the game!");
    }
}
void leave(Player p){
    if(players.contains(p.getName())){
        p.teleport(Bukkit.getWorlds().get(0).getSpawnLocation());
        players.remove(p.getName());
        for (String temp : players) {
            Bukkit.getPlayer(temp).sendMessage("§7§l"+p.getName()+ " has left infection. §7("+players.size()+"/16)");
        }
    }else{
        p.sendMessage(prefix + "§cYou are not in a game!");
    }
}
void addToHumans(String playername){
    human.add(playername);
}
void removeFromHumans(String playername){
    human.remove(playername);
}
void addToInfected(String playername){
    infected.add(playername);
}
void removeFromInfected(String playername){
    infected.remove(playername);
}

void teleportToLobby(Player p){
    Location lobby = getLocFromConfig("lobby");
    if(lobby != null){
        p.teleport(lobby);
        p.sendMessage(prefix + "§aSuccessfully added to game!");
    }else{
        p.sendMessage(prefix + "§cLobby not set! Make sure to set a lobby using /infection setlobby");
    }
}
void startGame(){
    /*if(human.size() >= 4){
    }*/
    for (String temp : players) {
        Bukkit.getPlayer(temp).sendMessage("Game will start shortly!");
    }
}
Location getLocFromConfig(String locationName){
    if(Main.plugin.getConfig().get("lobby") != null){
        double x = Main.plugin.getConfig().getInt(locationName+".x");
        double y = Main.plugin.getConfig().getInt(locationName+".y");
        double z = Main.plugin.getConfig().getInt(locationName+".z");
        World world = Main.plugin.getServer().getWorld(Main.plugin.getConfig().getString(locationName+".world"));
        Location l = new Location(world, x, y, z);
        return l;
    }else{
        Bukkit.getLogger().warning("[Infection] Lobby has not been set!");
        return null;
    }
}
int getPlayersInLobby(){
    return players.size();
}

public List<String> getPlayers(){
    List<String> players = this.players;
    return players;
}
public List<String> getHumans(){
    return human;
}
public List<String> getInfected(){
    return infected;
}

}

Events class (referred to in the example as ClassB)

public class Events implements Listener{

TeamManager teamman = new TeamManager();
List<String> players = teamman.getPlayers();
List<String> humans = teamman.getHumans();
List<String> infected = teamman.getInfected();
@EventHandler
public void onPlayerJoin(PlayerJoinEvent e){
    //Player p = (Player) e.getPlayer();
    //e.setJoinMessage("["+lvl+"]" + e.getPlayer().getName() +"has joined the game!");
    //p.setDisplayName("[lvl1]"+p.getName());

}
@EventHandler
public void onPlayerDamage(EntityDamageByEntityEvent  e){
    if(e.getEntity() instanceof Player){
        Player p = (Player) e.getEntity();
        Bukkit.getServer().broadcastMessage("Players: "+ players);
        if(players.contains(p.getName())){
            if((p.getHealth() - p.getLastDamage()) < 1){
                for (String temp : players) {
                    Bukkit.getPlayer(temp).sendMessage("§c"+p.getName()+" got infected by "+p.getKiller().getName()+"!");
                }
                e.setCancelled(true);
                 p.setHealth(20);
                 teamman.addToInfected(p.getName());
                 teamman.removeFromHumans(p.getName());
                 p.sendMessage("§cYou have been infected!!");
            }
        }
    }
}

}

As said above i want to be able to access the lists from TeamManager and use them in Events. And as explained players is empty in the Events class. I hope this helps.

Body:
The list of A will always be empty, because you are access a list of a new instance. If you want get a list A, you have send a list A as parameter to class B. Example:

class ClassA{
 List<String> players;
 ClassA(){
  players = new ArrayList<>();
 }
 public List getPlayers(){
  return this.players;
 }
}

class ClassB{
  private List<String> playersA;

  ClassB(List playersA){
   this.playersA = playersA;
 }
}

// In your main code

ClassA classA = new ClassA();
ClassB classB;
List<String> players = classA.getPlayers();
players.add("P1");
players.add("P2");

classB = new ClassB(players);


问:
PhantomJS (Selenium) Cannot Load PDFs from direct urls
I was trying to save some PDF from a link via PhantomJS (selenium). So, I refered to this code that turns webpages to pdfs. and it worked just fine when I ran the exactly same code.

So, I have this pdf I wanted to save from a direct url and I tried that script... it didn't work. It just saves a PDF with 1 white page. That's all...

My Code :

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

def execute(script, args):
    driver.execute('executePhantomScript', {'script': script, 'args' : args })

driver = webdriver.PhantomJS('phantomjs')

# hack while the python interface lags
driver.command_executor._commands['executePhantomScript'] = ('POST', '/session/$sessionId/phantom/execute')

driver.get('http://www.planetpublish.com/wp-content/uploads/2011/11/The_Scarlet_Letter_T.pdf')

try:
    WebDriverWait(driver, 40).until(EC.presence_of_element_located((By.ID, 'plugin')))
except Exception as TimeoutException:
    print("I waited for far too long and still couldn't fine the view.")
    pass

# set page format
# inside the execution script, webpage is "this"
pageFormat = '''this.paperSize = {format: "A4", orientation: "portrait" };'''
execute(pageFormat, [])

# render current page
render = '''this.render("test2.pdf")'''
execute(render, [])
</code>```

I'm not sure what's happening and why is it happening. Need some assistance.

EDIT: This is just the test PDF that I was trying to get via Selenium. There are some other PDFs which I need to get and that website is checking god-knows-what to decide whether it's a human or a bot. So, Selenium is the only way.

EDIT 2 : So, here's the website I was practicing on : http://services.ecourts.gov.in/ecourtindia/cases/case_no.php?state_cd=26&dist_cd=8&appFlag=web

Select "Cr Rev - Criminal Revision" from "Case Type" drop down and input any number in case number and year. Click on "Go".

This will show a little table, click on "view" and it should show a table on full page.

Scroll down to the "orders" table and you should see "Copy of order". That's the pdf I'm trying to get.I have tried requests as well and it did not work.

答:
I recommend you look at the pdfkit library.

```<code>import pdfkit
pdfkit.from_url('http://www.planetpublish.com/wp-content/uploads/2011/11/The_Scarlet_Letter_T.pdf', 'out.pdf')
</code>```

It makes downloading pdfs very simple with python. You will also need to download this for the library to work.

You could also try the code from this link shown below

```<code>#!/usr/bin/env python
from contextlib import closing
from selenium.webdriver import Firefox # pip install selenium
from selenium.webdriver.support.ui import WebDriverWait

# use firefox to get page with javascript generated content
with closing(Firefox()) as browser:
     browser.get('http://www.planetpublish.com/wp-content/uploads/2011/11/The_Scarlet_Letter_T.pdf')
     button = browser.find_element_by_name('button')
     button.click()
     # wait for the page to load
     WebDriverWait(browser, timeout=10).until(
         lambda x: x.find_element_by_id('someId_that_must_be_on_new_page'))
     # store it to string variable
     page_source = browser.page_source
print(page_source)
</code>```

which you will need to edit to make work for your pdf.

Body:
I was trying to save some PDF from a link via PhantomJS (selenium). So, I refered to this code that turns webpages to pdfs. and it worked just fine when I ran the exactly same code.

So, I have this pdf I wanted to save from a direct url and I tried that script... it didn't work. It just saves a PDF with 1 white page. That's all...

My Code :

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

def execute(script, args):
    driver.execute('executePhantomScript', {'script': script, 'args' : args })

driver = webdriver.PhantomJS('phantomjs')

# hack while the python interface lags
driver.command_executor._commands['executePhantomScript'] = ('POST', '/session/$sessionId/phantom/execute')

driver.get('http://www.planetpublish.com/wp-content/uploads/2011/11/The_Scarlet_Letter_T.pdf')

try:
    WebDriverWait(driver, 40).until(EC.presence_of_element_located((By.ID, 'plugin')))
except Exception as TimeoutException:
    print("I waited for far too long and still couldn't fine the view.")
    pass

# set page format
# inside the execution script, webpage is "this"
pageFormat = '''this.paperSize = {format: "A4", orientation: "portrait" };'''
execute(pageFormat, [])

# render current page
render = '''this.render("test2.pdf")'''
execute(render, [])

I'm not sure what's happening and why is it happening. Need some assistance.

EDIT: This is just the test PDF that I was trying to get via Selenium. There are some other PDFs which I need to get and that website is checking god-knows-what to decide whether it's a human or a bot. So, Selenium is the only way.

EDIT 2 : So, here's the website I was practicing on : http://services.ecourts.gov.in/ecourtindia/cases/case_no.php?state_cd=26&dist_cd=8&appFlag=web

Select "Cr Rev - Criminal Revision" from "Case Type" drop down and input any number in case number and year. Click on "Go".

This will show a little table, click on "view" and it should show a table on full page.

Scroll down to the "orders" table and you should see "Copy of order". That's the pdf I'm trying to get.I have tried requests as well and it did not work.

Body:
I recommend you look at the pdfkit library.

import pdfkit
pdfkit.from_url('http://www.planetpublish.com/wp-content/uploads/2011/11/The_Scarlet_Letter_T.pdf', 'out.pdf')

It makes downloading pdfs very simple with python. You will also need to download this for the library to work.

You could also try the code from this link shown below

#!/usr/bin/env python
from contextlib import closing
from selenium.webdriver import Firefox # pip install selenium
from selenium.webdriver.support.ui import WebDriverWait

# use firefox to get page with javascript generated content
with closing(Firefox()) as browser:
     browser.get('http://www.planetpublish.com/wp-content/uploads/2011/11/The_Scarlet_Letter_T.pdf')
     button = browser.find_element_by_name('button')
     button.click()
     # wait for the page to load
     WebDriverWait(browser, timeout=10).until(
         lambda x: x.find_element_by_id('someId_that_must_be_on_new_page'))
     # store it to string variable
     page_source = browser.page_source
print(page_source)

which you will need to edit to make work for your pdf.


问:
Facebook login popup on page load?
I am wondering if it is possible to automatically create a popup with the login url instead of displaying a button.

Currently I have  instead I want to have it so when the page loads (it is an iframe) it popups a window that the user logins in with and then the iframe refreshes.

I then need to get the access_token.

Is this possible?

答:
take a look at this page http://developers.facebook.com/docs/authentication/javascript

you can get the access_token via javascript

ContentLicense: CC BY-SA 2.5

Title: Facebook login popup on page load?


问:
sudo apachectl start not working on OS X Yosemite
I type in the command and i get this message

/System/Library/LaunchDaemons/org.apache.httpd.plist: Operation
  already in progress

So on safari i load the  http://localhost page and it gives me the error message Safari can't  connect to the server "localhost".

I'm new to this so don't have much knowledge on this but the reason i want to log in to this is to run my php scripts and test my websites on my laptop.

Ever since the os upgrade from mavericks to yosemite i couldn't run any php scrip.

答:
try this:</p>

```<code>launchctl start localhost
</code>```

Body:
try this:

launchctl start localhost


问:
Best way to draw text in MonoGame without using a SpriteFont?
Alright, so I'm working on a game in MonoGame which is set in a computer operating system. As expected, it does a lot of text rendering. The in-game OS allows users to customize almost every aspect of the operating system - people have made skins for the OS that make it look like Mac OS Sierra, almost every najor Windows release since 95, Xubuntu, Ubuntu, and way more.

This game used to be written in Windows Forms however there are features I want to implement that simply are not possible in WinForms. So, we decided to move from WinForms to MonoGame, and we are faced with one huge problem.

The skin format we've made allows the user to select any font installed on their computer to use for various elements like titlebar text, main UI text, terminal text etc. This was fine in WinForms because we could use System.Drawing to render text and that allows the use of any TrueType font on the system. If it can be loaded into a System.Drawing.Font, it can be rendered.

But, MonoGame uses a different technology for rendering text on-screen. SpriteFont objects. The problem is, there seems to be no way at all to dynamically generate a SpriteFont from the same data used to generate System.Drawing.Fonts (family, size, style, etc) in code.

So, since I seemingly can't create SpriteFonts dynamically, in my graphics helper class (which deals with drawing textures etc onto the current graphics device without needing copy-pasted code everywhere), I have my own DrawString and MeasureString methods which use System.Drawing.Graphics to composite text onto a bitmap and use that bitmap as a texture to draw onto the screen.

And, here's my code for doing exactly that.

```<code>public Vector2 MeasureString(string text, System.Drawing.Font font, int wrapWidth = int.MaxValue)
{
    using(var gfx = System.Drawing.Graphics.FromImage(new System.Drawing.Bitmap(1, 1)))
    {
        var s = gfx.SmartMeasureString(text, font, wrapWidth); //SmartMeasureString is an extension method I made for System.Drawing.Graphics which applies text rendering hints and formatting rules that I need to make text rendering and measurement accurate and usable without copy-pasting the same code.
        return new Vector2((float)Math.Ceiling(s.Width), (float)Math.Ceiling(s.Height)); //Better to round up the values returned by SmartMeasureString - it's just easier math-wise to deal with whole numbers
    }
}

public void DrawString(string text, int x, int y, Color color, System.Drawing.Font font, int wrapWidth = 0)
{
    x += _startx;
    y += _starty;
    //_startx and _starty are used for making sure coordinates are relative to the clip bounds of the current context
    Vector2 measure;
    if (wrapWidth == 0)
        measure = MeasureString(text, font);
    else
        measure = MeasureString(text, font, wrapWidth);
    using (var bmp = new System.Drawing.Bitmap((int)measure.X, (int)measure.Y))
    {
        using (var gfx = System.Drawing.Graphics.FromImage(bmp))
        {
            var textformat = new System.Drawing.StringFormat(System.Drawing.StringFormat.GenericTypographic);
            textformat.FormatFlags = System.Drawing.StringFormatFlags.MeasureTrailingSpaces;
            textformat.Trimming = System.Drawing.StringTrimming.None;
            textformat.FormatFlags |= System.Drawing.StringFormatFlags.NoClip; //without this, text gets cut off near the right edge of the string bounds

            gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel; //Anything but this and performance takes a dive.
            gfx.DrawString(text, font, new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B)), 0, 0, textformat);
        }
        var lck = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); //Lock the bitmap in memory and give us the ability to extract data from it so we can load it into a Texture2D
        var data = new byte[Math.Abs(lck.Stride) * lck.Height]; //destination array for bitmap data, source for texture data
        System.Runtime.InteropServices.Marshal.Copy(lck.Scan0, data, 0, data.Length); //cool, data's in the destination array
        bmp.UnlockBits(lck); //Unlock the bits. We don't need 'em.
        using (var tex2 = new Texture2D(_graphicsDevice, bmp.Width, bmp.Height))
        {
            for (int i = 0; i < data.Length; i += 4)
            {
                byte r = data[i];
                byte b = data[i + 2];
                data[i] = b;
                data[i + 2] = r;
            } //This code swaps the red and blue values of each pixel in the bitmap so that they are arranged as BGRA. If we don't do this, we get weird rendering glitches where red text is blue etc.

            tex2.SetData<byte>(data); //Load the data into the texture
            _spritebatch.Draw(tex2, new Rectangle(x, y, bmp.Width, bmp.Height), Color.White); //...and draw it!
        }
    }
}
</code>```

I'm already caching heaps of textures created dynamically - window buffers for in-game programs, skin textures, etc, so those don't hit the performance hard if at all, but this text rendering code hits it hard. I have trouble even getting the game above 29 FPS!

So, is there a better way of doing text rendering without SpriteFonts, and if not, is there any way at all to create a spritefont dynamically in code simply by specifying a font family, font size and style (bold, italic, strikeout etc)?

I'd say I'm intermediate with MonoGame now but I have a hard enough time getting RenderTargets to work - so if you want to answer this question please answer it as if you were talking to a kindergarten student.

Any help would be greatly appreciated, and as this is a major hot-buttin' issue in my game's development team you may see yourself mentioned in the game's credits as a major help :P

答:
You could create a custom spritefont using System.Drawing and use this one. It is basically every character that can be used, stored in a Dictionary with the corresponding Texture2D.

When you want to draw a text, you just draw every char next to eachother.

This is still slow (because drawing text without vector graphics is always slow) but at least you do not have to parse everything every frame.

Just specify somewhere what characters can be used and import them. Dictionaries are very fast in C# when it comes to indexing, so this shouldn't be a problem at all.

Hope this helps. Good luck.

Body:
Alright, so I'm working on a game in MonoGame which is set in a computer operating system. As expected, it does a lot of text rendering. The in-game OS allows users to customize almost every aspect of the operating system - people have made skins for the OS that make it look like Mac OS Sierra, almost every najor Windows release since 95, Xubuntu, Ubuntu, and way more.

This game used to be written in Windows Forms however there are features I want to implement that simply are not possible in WinForms. So, we decided to move from WinForms to MonoGame, and we are faced with one huge problem.

The skin format we've made allows the user to select any font installed on their computer to use for various elements like titlebar text, main UI text, terminal text etc. This was fine in WinForms because we could use System.Drawing to render text and that allows the use of any TrueType font on the system. If it can be loaded into a System.Drawing.Font, it can be rendered.

But, MonoGame uses a different technology for rendering text on-screen. SpriteFont objects. The problem is, there seems to be no way at all to dynamically generate a SpriteFont from the same data used to generate System.Drawing.Fonts (family, size, style, etc) in code.

So, since I seemingly can't create SpriteFonts dynamically, in my graphics helper class (which deals with drawing textures etc onto the current graphics device without needing copy-pasted code everywhere), I have my own DrawString and MeasureString methods which use System.Drawing.Graphics to composite text onto a bitmap and use that bitmap as a texture to draw onto the screen.

And, here's my code for doing exactly that.

public Vector2 MeasureString(string text, System.Drawing.Font font, int wrapWidth = int.MaxValue)
{
    using(var gfx = System.Drawing.Graphics.FromImage(new System.Drawing.Bitmap(1, 1)))
    {
        var s = gfx.SmartMeasureString(text, font, wrapWidth); //SmartMeasureString is an extension method I made for System.Drawing.Graphics which applies text rendering hints and formatting rules that I need to make text rendering and measurement accurate and usable without copy-pasting the same code.
        return new Vector2((float)Math.Ceiling(s.Width), (float)Math.Ceiling(s.Height)); //Better to round up the values returned by SmartMeasureString - it's just easier math-wise to deal with whole numbers
    }
}

public void DrawString(string text, int x, int y, Color color, System.Drawing.Font font, int wrapWidth = 0)
{
    x += _startx;
    y += _starty;
    //_startx and _starty are used for making sure coordinates are relative to the clip bounds of the current context
    Vector2 measure;
    if (wrapWidth == 0)
        measure = MeasureString(text, font);
    else
        measure = MeasureString(text, font, wrapWidth);
    using (var bmp = new System.Drawing.Bitmap((int)measure.X, (int)measure.Y))
    {
        using (var gfx = System.Drawing.Graphics.FromImage(bmp))
        {
            var textformat = new System.Drawing.StringFormat(System.Drawing.StringFormat.GenericTypographic);
            textformat.FormatFlags = System.Drawing.StringFormatFlags.MeasureTrailingSpaces;
            textformat.Trimming = System.Drawing.StringTrimming.None;
            textformat.FormatFlags |= System.Drawing.StringFormatFlags.NoClip; //without this, text gets cut off near the right edge of the string bounds

            gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel; //Anything but this and performance takes a dive.
            gfx.DrawString(text, font, new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B)), 0, 0, textformat);
        }
        var lck = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); //Lock the bitmap in memory and give us the ability to extract data from it so we can load it into a Texture2D
        var data = new byte[Math.Abs(lck.Stride) * lck.Height]; //destination array for bitmap data, source for texture data
        System.Runtime.InteropServices.Marshal.Copy(lck.Scan0, data, 0, data.Length); //cool, data's in the destination array
        bmp.UnlockBits(lck); //Unlock the bits. We don't need 'em.
        using (var tex2 = new Texture2D(_graphicsDevice, bmp.Width, bmp.Height))
        {
            for (int i = 0; i < data.Length; i += 4)
            {
                byte r = data[i];
                byte b = data[i + 2];
                data[i] = b;
                data[i + 2] = r;
            } //This code swaps the red and blue values of each pixel in the bitmap so that they are arranged as BGRA. If we don't do this, we get weird rendering glitches where red text is blue etc.

            tex2.SetData<byte>(data); //Load the data into the texture
            _spritebatch.Draw(tex2, new Rectangle(x, y, bmp.Width, bmp.Height), Color.White); //...and draw it!
        }
    }
}

I'm already caching heaps of textures created dynamically - window buffers for in-game programs, skin textures, etc, so those don't hit the performance hard if at all, but this text rendering code hits it hard. I have trouble even getting the game above 29 FPS!

So, is there a better way of doing text rendering without SpriteFonts, and if not, is there any way at all to create a spritefont dynamically in code simply by specifying a font family, font size and style (bold, italic, strikeout etc)?

I'd say I'm intermediate with MonoGame now but I have a hard enough time getting RenderTargets to work - so if you want to answer this question please answer it as if you were talking to a kindergarten student.

Any help would be greatly appreciated, and as this is a major hot-buttin' issue in my game's development team you may see yourself mentioned in the game's credits as a major help :P


问:
Cant use a return value from another function/python file
I am new to python-ish and trying to user the value held in the server variable that is returned at the bottom of select_target_server_type in another program. The first set of code is my menu.py and its just an input/decision tree.

My second code is rest_engine.py which calls menu.start_program() and that works great but when I want to retrieve the value of a function in one of the menu functions I cant get it to work it seems.

```<code>def start_program():
    select_target_server_type()

def select_target_server_type():
    # SUPPORTED SERVERS FOR API CALLS
    # DISPLAYS A LIST TO USER TO CHOOSE FROM

    print("\nWelcome!\nThese are the supported systems, please select a value by entering the corresponding "
          "numbered value\n")

    while True:
        try:
            print("1. APIC-EM")
            print("2. ISE")
            print("3. CSR")
            print("4. Quit")
            server = int(input("\nPlease select a SYSTEM TYPE to continue:   "))

            if 0 >= server or server >= 5:
                print("\n***Incorrect Selection***\n\n")
                pass
            else:
                break

        except Exception as e:
            print("\n\n***oops***")
            sys.exit(1)

    while True:
        try:
            if server == 1:
                print("\nYou have selected APIC-EM \n")
                api_top_menu()
            elif server == 2:
                print("\nYou have selected ISE \n")
                api_top_menu()
            elif server == 3:
                print("\nYou have selected CSR \n")
                api_top_menu()
            elif server == 4:
                print("\nQUITTING APPLICATION\n")
                sys.exit(0)
        except Exception as e:
            print("\n\n***oops***")
            sys.exit(1)
        return server
</code>```

Second program rest_engine.py (calls the first)

```<code>#!/usr/bin/python3

import json
import requests
import menu

menu.start_program()

name = menu.select_target_server_type()
print(name)
</code>```

Functioning Code Output:

```<code>> /usr/bin/python3.5 /home/danield/PycharmProjects/YODA/rest_engine.py
>
> Welcome! These are the supported systems, please select a value by
> entering the corresponding numbered value
>
> 1. APIC-EM
> 2. ISE
> 3. CSR
> 4. Quit
>
> Please select a SYSTEM TYPE to continue:   1
>
> You have selected APIC-EM
>
> 1. GET
> 2. PUT
> 3. DELETE
> 4. quit Please select a function to continue:   1
>
> You chose to use GET
>
> 1. INVENTORY
> 2. NETWORK DISCOVERY
> 3. TBD
> 4. Quit Please select the FUNCTION category:   1
>
> You chose Inventory
>
>
>
> ***oops***
>
> Process finished with exit code 1
</code>```

答:
A few things. First, seems like not all of those things need to be in while loops, but that's a separate issue. Second, when you do menu.start_program(), you're running your function select_target_server_type, but you don't store the return value. You only try to store the return value when you call the whole thing again: name = menu.select_target_server_type()

But you never get to that line (with name=...), because the first call, to start_program, terminates the running process.

Third, your program is running into an error and thus terminating via the sys.exit(1) line, so the function never gets the chance to return anything.

Body:
I am new to python-ish and trying to user the value held in the server variable that is returned at the bottom of select_target_server_type in another program. The first set of code is my menu.py and its just an input/decision tree.

My second code is rest_engine.py which calls menu.start_program() and that works great but when I want to retrieve the value of a function in one of the menu functions I cant get it to work it seems.

def start_program():
    select_target_server_type()

def select_target_server_type():
    # SUPPORTED SERVERS FOR API CALLS
    # DISPLAYS A LIST TO USER TO CHOOSE FROM

    print("\nWelcome!\nThese are the supported systems, please select a value by entering the corresponding "
          "numbered value\n")

    while True:
        try:
            print("1. APIC-EM")
            print("2. ISE")
            print("3. CSR")
            print("4. Quit")
            server = int(input("\nPlease select a SYSTEM TYPE to continue:   "))

            if 0 >= server or server >= 5:
                print("\n***Incorrect Selection***\n\n")
                pass
            else:
                break

        except Exception as e:
            print("\n\n***oops***")
            sys.exit(1)

    while True:
        try:
            if server == 1:
                print("\nYou have selected APIC-EM \n")
                api_top_menu()
            elif server == 2:
                print("\nYou have selected ISE \n")
                api_top_menu()
            elif server == 3:
                print("\nYou have selected CSR \n")
                api_top_menu()
            elif server == 4:
                print("\nQUITTING APPLICATION\n")
                sys.exit(0)
        except Exception as e:
            print("\n\n***oops***")
            sys.exit(1)
        return server

Second program rest_engine.py (calls the first)

#!/usr/bin/python3

import json
import requests
import menu

menu.start_program()

name = menu.select_target_server_type()
print(name)

Functioning Code Output:

> /usr/bin/python3.5 /home/danield/PycharmProjects/YODA/rest_engine.py
>
> Welcome! These are the supported systems, please select a value by
> entering the corresponding numbered value
>
> 1. APIC-EM
> 2. ISE
> 3. CSR
> 4. Quit
>
> Please select a SYSTEM TYPE to continue:   1
>
> You have selected APIC-EM
>
> 1. GET
> 2. PUT
> 3. DELETE
> 4. quit Please select a function to continue:   1
>
> You chose to use GET
>
> 1. INVENTORY
> 2. NETWORK DISCOVERY
> 3. TBD
> 4. Quit Please select the FUNCTION category:   1
>
> You chose Inventory
>
>
>
> ***oops***
>
> Process finished with exit code 1


问:
I'm utilizing an if/else statement to separate a data set into positive/negative values but have ran into an unused argument error
I'm trying to separate a set of data with an if statement based on if a value is positive. I had it working and it generated correct data but it stopped and generated the unused argument error when I generated new data.
Here is the code I used.

```<code>In:
data_random1 = runif(100,1,100)
data_random2 = runif(100,1,100)
cd1 = data_grouped1
cd2 = data_grouped2
smth_ln = lowess(cd1,cd2)
dis = smth_ln$y - cd2
data_frame = data.frame(cd1,cd2,dis)
f = c()
y = c()
ifelse(data_frame$dis >= 0, f = c(f,data_frame$dis),y = c(y,data_frame$dis))
</code>```

This generates the error:

```<code>Error in if (x > 0) { : missing value where TRUE/FALSE needed
</code>```

When I type this function seperate from the if statment it works so I am confused as to the issue.
I tried a workaround with:

```<code>for(x in c(dis[1:100])){if(x >= 0){f = c(f,x)}else{y=c(y,x)}}
</code>```

but got the error:

```<code>Error in if (x > 0) { : missing value where TRUE/FALSE needed
</code>```

Not sure how to fix this.

答:
try this</p>

```<code>data_random1 = runif(100,1,100)
data_random2 = runif(100,1,100)
cd1 = data_random1
cd2 = data_random2
smth_ln = lowess(cd1,cd2)
dis = smth_ln$y - cd2
data_frame = data.frame(cd1,cd2,dis)
f = c()
y = c()
for(i in 1:nrow(data_frame)){
  if(data_frame$dis[i] >= 0){
    f = c(f, data_frame$dis[i])
  } else{
    y = c(y, data_frame$dis[i])
  }
}
</code>```

Body:
I'm trying to separate a set of data with an if statement based on if a value is positive. I had it working and it generated correct data but it stopped and generated the unused argument error when I generated new data.
Here is the code I used.

In:
data_random1 = runif(100,1,100)
data_random2 = runif(100,1,100)
cd1 = data_grouped1
cd2 = data_grouped2
smth_ln = lowess(cd1,cd2)
dis = smth_ln$y - cd2
data_frame = data.frame(cd1,cd2,dis)
f = c()
y = c()
ifelse(data_frame$dis >= 0, f = c(f,data_frame$dis),y = c(y,data_frame$dis))

This generates the error:

Error in if (x > 0) { : missing value where TRUE/FALSE needed

When I type this function seperate from the if statment it works so I am confused as to the issue.
I tried a workaround with:

for(x in c(dis[1:100])){if(x >= 0){f = c(f,x)}else{y=c(y,x)}}

but got the error:

Error in if (x > 0) { : missing value where TRUE/FALSE needed

Not sure how to fix this.

Body:
try this

data_random1 = runif(100,1,100)
data_random2 = runif(100,1,100)
cd1 = data_random1
cd2 = data_random2
smth_ln = lowess(cd1,cd2)
dis = smth_ln$y - cd2
data_frame = data.frame(cd1,cd2,dis)
f = c()
y = c()
for(i in 1:nrow(data_frame)){
  if(data_frame$dis[i] >= 0){
    f = c(f, data_frame$dis[i])
  } else{
    y = c(y, data_frame$dis[i])
  }
}


问:
Background does not change onclick function
what's wrong with my code? For some reason my function load() does not change .firstDiv background?

I can't find any mistakes.

function load() {
document.getElementsByClassName("firstDiv").style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
  float: left;
}

.firstDiv {
  background-image: url("https://static.pexels.com/photos/200303/pexels-photo-200303.jpeg");
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);
  }</code>```

  <button onclick="load()">Change background</button>

```

答:
If you are using getElementByClassName then you need to specify the item number by specifying index like [0] OR alternatively use id

Example with Class Name:

function load() {
document.getElementsByClassName("firstDiv")[0].style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
  float: left;
}

.firstDiv {
  background-image: url("https://static.pexels.com/photos/200303/pexels-photo-200303.jpeg");
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);
  }</code>```

  <button onclick="load()">Change background</button>

```
</div>
</div>
</p>

<p><strong>For ID</strong></p>

<ol>
<li>Assign ID e.g <code><div id="firstDiv"></div></code></li>
<li><p>JS Code:</p>

```document.getElementById("firstDiv").style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";
```

Body:
what's wrong with my code? For some reason my function load() does not change .firstDiv background?

I can't find any mistakes.

function load() {
document.getElementsByClassName("firstDiv").style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";
}

.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
  float: left;
}

.firstDiv {
  background-image: url("https://static.pexels.com/photos/200303/pexels-photo-200303.jpeg");
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);
  }

  <button onclick="load()">Change background</button>

Body:
If you are using getElementByClassName then you need to specify the item number by specifying index like [0] OR alternatively use id

Example with Class Name:

function load() {
document.getElementsByClassName("firstDiv")[0].style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";
}

.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
  float: left;
}

.firstDiv {
  background-image: url("https://static.pexels.com/photos/200303/pexels-photo-200303.jpeg");
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);
  }

<div class="firstDiv"></div>

<div class="secondDiv">
  <button onclick="load()">Change background</button>
</div>

For ID

Assign ID e.g <div id="firstDiv"></div>

JS Code:

document.getElementById("firstDiv").style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";


问:
How do you define class variables accessible by all instances
I want to define a array with class-wide scope/access by all instances. Example module (bc.py):

```<code>class B:
    glist = []  # array common to all instances

    def __init__(self, number):
        glist.append(number)

    def printCurrentList():
        print ('Current List:', glist)

class C:
    def __init__(self):
        b1 = B(7)
        b2 = B(2)
        b3 = B(8)

    def printNow(self):
        B.printCurrentList()
</code>```

I am calling this from file a.py, as:

```<code>from bc import C
C().printNow()
</code>```

Getting error as:

```<code>python a.py
Traceback (most recent call last):
  File "a.py", line 2, in <module>
    C().printNow()
  File "/Users/manidipsengupta/pytorials/bc.py", line 16, in __init__
    b1 = B(7)
  File "/Users/manidipsengupta/pytorials/bc.py", line 7, in __init__
    glist.append(number)
NameError: name 'glist' is not defined
</code>```

What should be the correct syntax for this? Thank you.

答:
You have access class variables through class or instance:</p>

```<code>class B:
    glist = []  # array common to all instances

    def __init__(self, number):
        self.glist.append(number)

    @classmethod
    def printCurrentList(cls):
        print ('Current List:', cls.glist)
</code>```

Body:
I want to define a array with class-wide scope/access by all instances. Example module (bc.py):

class B:
    glist = []  # array common to all instances

    def __init__(self, number):
        glist.append(number)

    def printCurrentList():
        print ('Current List:', glist)

class C:
    def __init__(self):
        b1 = B(7)
        b2 = B(2)
        b3 = B(8)

    def printNow(self):
        B.printCurrentList()

I am calling this from file a.py, as:

from bc import C
C().printNow()

Getting error as:

python a.py
Traceback (most recent call last):
  File "a.py", line 2, in <module>
    C().printNow()
  File "/Users/manidipsengupta/pytorials/bc.py", line 16, in __init__
    b1 = B(7)
  File "/Users/manidipsengupta/pytorials/bc.py", line 7, in __init__
    glist.append(number)
NameError: name 'glist' is not defined

What should be the correct syntax for this? Thank you.

Body:
You have access class variables through class or instance:

class B:
    glist = []  # array common to all instances

    def __init__(self, number):
        self.glist.append(number)

    @classmethod
    def printCurrentList(cls):
        print ('Current List:', cls.glist)


问:
How can I dynamically resize my iframe, avoiding the browser security crossdomain restrictions?
We have an embeddable badge that creates an iframe. It needs to be a dynamic size; it changes size based on data loaded from a 3rd party API or our database. So it's not known what height it will be before it loads.

It's invoked with a  tag that loads a script from our server, which creates an iframe set to a specific src.

On my own machine, within the iframe I can do

```<code>window.parent.document.getElementById('my_frame').style.height=new_calculated_height+'px';
</code>```

but of course when it's embedded in a page different than the iframe src, that fails due to crossdomain restrictions ('unsafe access attempt' error in FF, etc.).

As we're already loading a script into the host page with full access, this is kind of silly.

Basically, I need to get a variable, the new height, from the iframe into the host page.

Could I do it in reverse maybe? Have a function on the host page ask the iframe for it's an element's offsetHeight?

答:
This can be a real pain in the butt to get working cross browser.

I strongly suggest you use easyXDM (http://easyxdm.net/). It's a JavaScript library that uses the PostMessage transport on modern browsers and uses some JavaScript ninja on old browsers.

The library allows you to communicate between an Iframe and it's parent even if they aren't on the same domain.

The library supports all the way down to IE6!

Edit: There's actually an example to resize the height of an Iframe dynamically once content is loaded: http://easyxdm.net/wp/2010/03/17/resize-iframe-based-on-content/

Christian

Body:
We have an embeddable badge that creates an iframe. It needs to be a dynamic size; it changes size based on data loaded from a 3rd party API or our database. So it's not known what height it will be before it loads.

It's invoked with a  tag that loads a script from our server, which creates an iframe set to a specific src.

On my own machine, within the iframe I can do

window.parent.document.getElementById('my_frame').style.height=new_calculated_height+'px';

but of course when it's embedded in a page different than the iframe src, that fails due to crossdomain restrictions ('unsafe access attempt' error in FF, etc.).

As we're already loading a script into the host page with full access, this is kind of silly.

Basically, I need to get a variable, the new height, from the iframe into the host page.

Could I do it in reverse maybe? Have a function on the host page ask the iframe for it's an element's offsetHeight?


问:
Why listview showing the last item twice?
My listview is showing the last item twice.

I want to show the members from database with volley and MySQL, sending request from android to API which is programmed in PHP and the API returns

JSON data.

Here is my code:

```<code>String email, member_id, member_type;
ListView community_member_list;
Context context = this;

MemberAdapter memberAdapter;
List<Model> modelList = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_community);

    SharedPreferences SP = getSharedPreferences("MemberSession", MODE_PRIVATE);
    Boolean member_logged_in = SP.getBoolean("member_logged_in", false);
    email = SP.getString("email", null);
    member_id = SP.getString("member_id", null);
    member_type = SP.getString("member_type", null);

    if (!member_logged_in)
    {
        Intent intent = new Intent(this, Login.class);
        startActivity(intent);
        finish();

    }else{

        community_member_list = (ListView) findViewById(R.id.community_members_list);

        memberAdapter = new MemberAdapter(getApplicationContext(), R.layout.community_list_item, modelList);
        community_member_list.setAdapter(memberAdapter);

        get_community_members();
    }

}

public void get_community_members()
{
    StringRequest stringRequest = new StringRequest(Request.Method.POST, new Login().site_url+"community",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {

                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray jsonArray = jsonObject.getJSONArray("members");
                        Model model = null;

                        for(int i=0; i<jsonArray.length(); i++) {

                            JSONObject finalObject = jsonArray.getJSONObject(i);

                            model = new Model();

                            model.setMember_id(finalObject.getInt("physician_id"));
                            model.setProfile_photo(finalObject.getString("profile_photo"));
                            model.setFirst_name(finalObject.getString("first_name"));
                            model.setLast_name(finalObject.getString("last_name"));
                            model.setDesignation(finalObject.getString("designation"));
                            model.setOrganization(finalObject.getString("organization"));

                            modelList.add(model);
                        }

                        memberAdapter.add(model);
                        memberAdapter.setNotifyOnChange(true);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    Toast.makeText(context, "Error "+error, Toast.LENGTH_SHORT).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params = new HashMap<>();

            params.put("member_id", member_id);

            return params;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

private class MemberAdapter extends ArrayAdapter {

    private List<Model> memberList;
    private int resource;
    private LayoutInflater inflater;

    MemberAdapter(Context context, int resource, List<Model> objects) {
        super(context, resource, objects);
        memberList = objects;
        this.resource = resource;
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    }

    @NonNull
    @Override
    public View getView(final int position, View convertView, @NonNull ViewGroup parent) {

        if(convertView == null)
        {
            convertView = inflater.inflate(resource, null);
        }

        final ImageView imageView;
        TextView textView, textView2;

        imageView = (ImageView)convertView.findViewById(R.id.imageView);
        textView = (TextView)convertView.findViewById(R.id.textView);
        textView2 = (TextView) convertView.findViewById(R.id.textView2);

        com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("http://www.plexusd.com/uploads/specialist/" + memberList.get(position).getProfile_photo(), imageView, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                imageView.setImageResource(R.mipmap.avatar);
            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {
                imageView.setImageResource(R.mipmap.avatar);
            }
        });

        textView.setText("Dr. "+memberList.get(position).getFirst_name()+" "+memberList.get(position).getLast_name());
        textView2.setText(""+memberList.get(position).getDesignation()+",\n"+memberList.get(position).getOrganization());

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

Here is the picture of list from mobile.

答:
Remove memberAdapter.add(model); inside onResponse after for loop. model object holds the last object and you are adding that in adapter again so last object showing 2 times.

```<code>try {

                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray jsonArray = jsonObject.getJSONArray("members");
                        Model model = null;

                        for(int i=0; i<jsonArray.length(); i++) {

                            JSONObject finalObject = jsonArray.getJSONObject(i);

                            model = new Model();

                            model.setMember_id(finalObject.getInt("physician_id"));
                            model.setProfile_photo(finalObject.getString("profile_photo"));
                            model.setFirst_name(finalObject.getString("first_name"));
                            model.setLast_name(finalObject.getString("last_name"));
                            model.setDesignation(finalObject.getString("designation"));
                            model.setOrganization(finalObject.getString("organization"));

                            modelList.add(model);
                        }

                        memberAdapter.add(model); // remove this.
                        memberAdapter.setNotifyOnChange(true);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
</code>```

Body:
My listview is showing the last item twice.

I want to show the members from database with volley and MySQL, sending request from android to API which is programmed in PHP and the API returns

JSON data.

Here is my code:

String email, member_id, member_type;
ListView community_member_list;
Context context = this;

MemberAdapter memberAdapter;
List<Model> modelList = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_community);

    SharedPreferences SP = getSharedPreferences("MemberSession", MODE_PRIVATE);
    Boolean member_logged_in = SP.getBoolean("member_logged_in", false);
    email = SP.getString("email", null);
    member_id = SP.getString("member_id", null);
    member_type = SP.getString("member_type", null);

    if (!member_logged_in)
    {
        Intent intent = new Intent(this, Login.class);
        startActivity(intent);
        finish();

    }else{

        community_member_list = (ListView) findViewById(R.id.community_members_list);

        memberAdapter = new MemberAdapter(getApplicationContext(), R.layout.community_list_item, modelList);
        community_member_list.setAdapter(memberAdapter);

        get_community_members();
    }

}

public void get_community_members()
{
    StringRequest stringRequest = new StringRequest(Request.Method.POST, new Login().site_url+"community",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {

                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray jsonArray = jsonObject.getJSONArray("members");
                        Model model = null;

                        for(int i=0; i<jsonArray.length(); i++) {

                            JSONObject finalObject = jsonArray.getJSONObject(i);

                            model = new Model();

                            model.setMember_id(finalObject.getInt("physician_id"));
                            model.setProfile_photo(finalObject.getString("profile_photo"));
                            model.setFirst_name(finalObject.getString("first_name"));
                            model.setLast_name(finalObject.getString("last_name"));
                            model.setDesignation(finalObject.getString("designation"));
                            model.setOrganization(finalObject.getString("organization"));

                            modelList.add(model);
                        }

                        memberAdapter.add(model);
                        memberAdapter.setNotifyOnChange(true);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    Toast.makeText(context, "Error "+error, Toast.LENGTH_SHORT).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params = new HashMap<>();

            params.put("member_id", member_id);

            return params;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

private class MemberAdapter extends ArrayAdapter {

    private List<Model> memberList;
    private int resource;
    private LayoutInflater inflater;

    MemberAdapter(Context context, int resource, List<Model> objects) {
        super(context, resource, objects);
        memberList = objects;
        this.resource = resource;
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    }

    @NonNull
    @Override
    public View getView(final int position, View convertView, @NonNull ViewGroup parent) {

        if(convertView == null)
        {
            convertView = inflater.inflate(resource, null);
        }

        final ImageView imageView;
        TextView textView, textView2;

        imageView = (ImageView)convertView.findViewById(R.id.imageView);
        textView = (TextView)convertView.findViewById(R.id.textView);
        textView2 = (TextView) convertView.findViewById(R.id.textView2);

        com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("http://www.plexusd.com/uploads/specialist/" + memberList.get(position).getProfile_photo(), imageView, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                imageView.setImageResource(R.mipmap.avatar);
            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {
                imageView.setImageResource(R.mipmap.avatar);
            }
        });

        textView.setText("Dr. "+memberList.get(position).getFirst_name()+" "+memberList.get(position).getLast_name());
        textView2.setText(""+memberList.get(position).getDesignation()+",\n"+memberList.get(position).getOrganization());

        return convertView;
    }
}

Here is the picture of list from mobile.

Body:
Remove memberAdapter.add(model); inside onResponse after for loop. model object holds the last object and you are adding that in adapter again so last object showing 2 times.

try {

                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray jsonArray = jsonObject.getJSONArray("members");
                        Model model = null;

                        for(int i=0; i<jsonArray.length(); i++) {

                            JSONObject finalObject = jsonArray.getJSONObject(i);

                            model = new Model();

                            model.setMember_id(finalObject.getInt("physician_id"));
                            model.setProfile_photo(finalObject.getString("profile_photo"));
                            model.setFirst_name(finalObject.getString("first_name"));
                            model.setLast_name(finalObject.getString("last_name"));
                            model.setDesignation(finalObject.getString("designation"));
                            model.setOrganization(finalObject.getString("organization"));

                            modelList.add(model);
                        }

                        memberAdapter.add(model); // remove this.
                        memberAdapter.setNotifyOnChange(true);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


问:
Converting IRestResponse to "image/jpg" File
I'm trying to pull an image from an API and return to the DOM through the File() method.

Here's what I have so far..

HomeController.cs:

```<code>public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult ImageFromPath()
    {
        var client = new RestClient("http://{{MYIPADDRESS}}/cgi-bin/snapshot.cgi?channel0=");
        var request = new RestRequest(Method.GET);
        request.AddHeader("postman-token", "random-postman-token");
        request.AddHeader("cache-control", "no-cache");
        request.AddHeader("authorization", "Digest username=\"MYUSERNAME\", realm=\"MYENCRYPTEDPASS\", nonce=\"LONGSTRING\", uri=\"/cgi-bin/snapshot.cgi?channel0\", response=\"RESPONSESTRING\", opaque=\"\"");
        IRestResponse response = client.Execute(request);(response.RawBytes);

        return File(response, "image/jpg");
    }
}
</code>```

The only problem here, is that the error on the return statement, response shows

cannot convert from 'RestSharp.IRestResponse' to 'byte[]'

When I was pulling the image from the local file system, it was easier and worked, here was my working code for HomeController.cs

```<code>public ActionResult ImageFromPath(string path)
{
    var ms = new MemoryStream();
    using (Bitmap bitmap = new Bitmap(path))
    {
        var height = bitmap.Size.Height;
        var width = bitmap.Size.Width;

        bitmap.Save(ms, ImageFormat.Jpeg);
    }

    ms.Position = 0;
    return File(ms, "image/jpg");
}
</code>```

Here's how I was pulling it in my front end (Index.cshtml):

```<code><img src="@Url.Action("ImageFromPath", new { path = Request.MapPath("~/img/1.jpg") })" />
</code>```

答:
This line here:

```<code>return File(response, "image/jpg");
</code>```

You are passing it response which is of type IRestResponse (a type from RestSharp).

Why would the built in MVC File method know of RestSharp?  File() takes a byte array and a string MIME type.

Try:

```<code>return File(response.RawBytes, "image/jpg");
</code>```

RawBytes is a byte array of the raw response from your HTTP Request.  If your API is returning a byte array of an image, this is what you need to pass to your file method.

Body:
I'm trying to pull an image from an API and return to the DOM through the File() method.

Here's what I have so far..

HomeController.cs:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult ImageFromPath()
    {
        var client = new RestClient("http://{{MYIPADDRESS}}/cgi-bin/snapshot.cgi?channel0=");
        var request = new RestRequest(Method.GET);
        request.AddHeader("postman-token", "random-postman-token");
        request.AddHeader("cache-control", "no-cache");
        request.AddHeader("authorization", "Digest username=\"MYUSERNAME\", realm=\"MYENCRYPTEDPASS\", nonce=\"LONGSTRING\", uri=\"/cgi-bin/snapshot.cgi?channel0\", response=\"RESPONSESTRING\", opaque=\"\"");
        IRestResponse response = client.Execute(request);(response.RawBytes);

        return File(response, "image/jpg");
    }
}

The only problem here, is that the error on the return statement, response shows

cannot convert from 'RestSharp.IRestResponse' to 'byte[]'

When I was pulling the image from the local file system, it was easier and worked, here was my working code for HomeController.cs

public ActionResult ImageFromPath(string path)
{
    var ms = new MemoryStream();
    using (Bitmap bitmap = new Bitmap(path))
    {
        var height = bitmap.Size.Height;
        var width = bitmap.Size.Width;

        bitmap.Save(ms, ImageFormat.Jpeg);
    }

    ms.Position = 0;
    return File(ms, "image/jpg");
}

Here's how I was pulling it in my front end (Index.cshtml):

Body:
This line here:

return File(response, "image/jpg");

You are passing it response which is of type IRestResponse (a type from RestSharp).

Why would the built in MVC File method know of RestSharp?  File() takes a byte array and a string MIME type.

Try:

return File(response.RawBytes, "image/jpg");

RawBytes is a byte array of the raw response from your HTTP Request.  If your API is returning a byte array of an image, this is what you need to pass to your file method.


问:
VB.net 2017 Change background color of button
I just started using vb.net 2017 instead of the 2010 version and i can't figure out how to change the background color of a button. I used to be able to do

```<code>`but1.BackColor = Colors.Blue`
</code>```

But it seems as if BackColor isn't available anymore. What could be a possible solution?

Edit: added screenshots

Form screenshot VS auto corrects color to ColorInterpolationMode

Designer screenshot

答: So turns out I had the wrong version of VS installed... I had "Universal Windows Platform development", I reinstalled VS using the ".NET desktop development" version. This solves a lot of other problems I've had in the past also!</p>

Body:
I just started using vb.net 2017 instead of the 2010 version and i can't figure out how to change the background color of a button. I used to be able to do

`but1.BackColor = Colors.Blue`

But it seems as if BackColor isn't available anymore. What could be a possible solution?

Edit: added screenshots

Form screenshot VS auto corrects color to ColorInterpolationMode

Designer screenshot


问:
How can I fill a column with random numbers in SQL? I get the same value in every row
```<code>UPDATE CattleProds
SET SheepTherapy=(ROUND((RAND()* 10000),0))
WHERE SheepTherapy IS NULL
</code>```

If I then do a SELECT I see that my random number is identical in every row. Any ideas how to generate unique random numbers?

答:
I tested 2 set based randomization methods against RAND() by generating 100,000,000 rows with each.  To level the field the output is a float between 0-1 to mimic RAND().  Most of the code is testing infrastructure so I summarize the algorithms here:

```<code>-- Try #1 used
(CAST(CRYPT_GEN_RANDOM(8) AS BIGINT)%500000000000000000+500000000000000000.0)/1000000000000000000 AS Val
-- Try #2 used
RAND(Checksum(NewId()))
-- and to have a baseline to compare output with I used
RAND() -- this required executing 100000000 separate insert statements
</code>```

Using CRYPT_GEN_RANDOM was clearly the most random since there is only a .000000001% chance of seeing even 1 duplicate when plucking 10^8 numbers FROM a set of 10^18 numbers.  IOW we should not have seen any duplicates and this had none!  This set took 44 seconds to generate on my laptop.

```<code>Cnt     Pct
-----   ----
 1      100.000000  --No duplicates
</code>```

SQL Server Execution Times:
   CPU time = 134795 ms,  elapsed time = 39274 ms.

```<code>IF OBJECT_ID('tempdb..#T0') IS NOT NULL DROP TABLE #T0;
GO
WITH L0   AS (SELECT c FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS D(c))  -- 2^4
    ,L1   AS (SELECT 1 AS c FROM L0 AS A CROSS JOIN L0 AS B)    -- 2^8
    ,L2   AS (SELECT 1 AS c FROM L1 AS A CROSS JOIN L1 AS B)    -- 2^16
    ,L3   AS (SELECT 1 AS c FROM L2 AS A CROSS JOIN L2 AS B)    -- 2^32
SELECT TOP 100000000 (CAST(CRYPT_GEN_RANDOM(8) AS BIGINT)%500000000000000000+500000000000000000.0)/1000000000000000000 AS Val
  INTO #T0
  FROM L3;

 WITH x AS (
     SELECT Val,COUNT(*) Cnt
      FROM #T0
     GROUP BY Val
)
SELECT x.Cnt,COUNT(*)/(SELECT COUNT(*)/100 FROM #T0) Pct
  FROM X
 GROUP BY x.Cnt;
</code>```

At almost 15 orders of magnitude less random this method was not quite twice as fast, taking only 23 seconds to generate 100M numbers.

```<code>Cnt  Pct
---- ----
1    95.450254    -- only 95% unique is absolutely horrible
2    02.222167    -- If this line were the only problem I'd say DON'T USE THIS!
3    00.034582
4    00.000409    -- 409 numbers appeared 4 times
5    00.000006    -- 6 numbers actually appeared 5 times
</code>```

SQL Server Execution Times:
   CPU time = 77156 ms,  elapsed time = 24613 ms.

```<code>IF OBJECT_ID('tempdb..#T1') IS NOT NULL DROP TABLE #T1;
GO
WITH L0   AS (SELECT c FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS D(c))  -- 2^4
    ,L1   AS (SELECT 1 AS c FROM L0 AS A CROSS JOIN L0 AS B)    -- 2^8
    ,L2   AS (SELECT 1 AS c FROM L1 AS A CROSS JOIN L1 AS B)    -- 2^16
    ,L3   AS (SELECT 1 AS c FROM L2 AS A CROSS JOIN L2 AS B)    -- 2^32
SELECT TOP 100000000 RAND(Checksum(NewId())) AS Val
  INTO #T1
  FROM L3;

WITH x AS (
    SELECT Val,COUNT(*) Cnt
     FROM #T1
    GROUP BY Val
)
SELECT x.Cnt,COUNT(*)*1.0/(SELECT COUNT(*)/100 FROM #T1) Pct
  FROM X
 GROUP BY x.Cnt;
</code>```

RAND() alone is useless for set-based generation so generating the baseline for comparing randomness took over 6 hours and had to be restarted several times to finally get the right number of output rows.  It also seems that the randomness leaves a lot to be desired although it's better than using checksum(newid()) to reseed each row.

```<code>Cnt  Pct
---- ----
1    99.768020
2    00.115840
3    00.000100  -- at least there were comparitively few values returned 3 times
</code>```

Because of the restarts, execution time could not be captured.

```<code>IF OBJECT_ID('tempdb..#T2') IS NOT NULL DROP TABLE #T2;
GO
CREATE TABLE #T2 (Val FLOAT);
GO
SET NOCOUNT ON;
GO
INSERT INTO #T2(Val) VALUES(RAND());
GO 100000000

WITH x AS (
    SELECT Val,COUNT(*) Cnt
     FROM #T2
    GROUP BY Val
)
SELECT x.Cnt,COUNT(*)*1.0/(SELECT COUNT(*)/100 FROM #T2) Pct
  FROM X
 GROUP BY x.Cnt;
</code>```

Body:
UPDATE CattleProds
SET SheepTherapy=(ROUND((RAND()* 10000),0))
WHERE SheepTherapy IS NULL

If I then do a SELECT I see that my random number is identical in every row. Any ideas how to generate unique random numbers?

Body:
I tested 2 set based randomization methods against RAND() by generating 100,000,000 rows with each.  To level the field the output is a float between 0-1 to mimic RAND().  Most of the code is testing infrastructure so I summarize the algorithms here:

-- Try #1 used
(CAST(CRYPT_GEN_RANDOM(8) AS BIGINT)%500000000000000000+500000000000000000.0)/1000000000000000000 AS Val
-- Try #2 used
RAND(Checksum(NewId()))
-- and to have a baseline to compare output with I used
RAND() -- this required executing 100000000 separate insert statements

Using CRYPT_GEN_RANDOM was clearly the most random since there is only a .000000001% chance of seeing even 1 duplicate when plucking 10^8 numbers FROM a set of 10^18 numbers.  IOW we should not have seen any duplicates and this had none!  This set took 44 seconds to generate on my laptop.

Cnt     Pct
-----   ----
 1      100.000000  --No duplicates

SQL Server Execution Times:
   CPU time = 134795 ms,  elapsed time = 39274 ms.

IF OBJECT_ID('tempdb..#T0') IS NOT NULL DROP TABLE #T0;
GO
WITH L0   AS (SELECT c FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS D(c))  -- 2^4
    ,L1   AS (SELECT 1 AS c FROM L0 AS A CROSS JOIN L0 AS B)    -- 2^8
    ,L2   AS (SELECT 1 AS c FROM L1 AS A CROSS JOIN L1 AS B)    -- 2^16
    ,L3   AS (SELECT 1 AS c FROM L2 AS A CROSS JOIN L2 AS B)    -- 2^32
SELECT TOP 100000000 (CAST(CRYPT_GEN_RANDOM(8) AS BIGINT)%500000000000000000+500000000000000000.0)/1000000000000000000 AS Val
  INTO #T0
  FROM L3;

 WITH x AS (
     SELECT Val,COUNT(*) Cnt
      FROM #T0
     GROUP BY Val
)
SELECT x.Cnt,COUNT(*)/(SELECT COUNT(*)/100 FROM #T0) Pct
  FROM X
 GROUP BY x.Cnt;

At almost 15 orders of magnitude less random this method was not quite twice as fast, taking only 23 seconds to generate 100M numbers.

Cnt  Pct
---- ----
1    95.450254    -- only 95% unique is absolutely horrible
2    02.222167    -- If this line were the only problem I'd say DON'T USE THIS!
3    00.034582
4    00.000409    -- 409 numbers appeared 4 times
5    00.000006    -- 6 numbers actually appeared 5 times

SQL Server Execution Times:
   CPU time = 77156 ms,  elapsed time = 24613 ms.

IF OBJECT_ID('tempdb..#T1') IS NOT NULL DROP TABLE #T1;
GO
WITH L0   AS (SELECT c FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS D(c))  -- 2^4
    ,L1   AS (SELECT 1 AS c FROM L0 AS A CROSS JOIN L0 AS B)    -- 2^8
    ,L2   AS (SELECT 1 AS c FROM L1 AS A CROSS JOIN L1 AS B)    -- 2^16
    ,L3   AS (SELECT 1 AS c FROM L2 AS A CROSS JOIN L2 AS B)    -- 2^32
SELECT TOP 100000000 RAND(Checksum(NewId())) AS Val
  INTO #T1
  FROM L3;

WITH x AS (
    SELECT Val,COUNT(*) Cnt
     FROM #T1
    GROUP BY Val
)
SELECT x.Cnt,COUNT(*)*1.0/(SELECT COUNT(*)/100 FROM #T1) Pct
  FROM X
 GROUP BY x.Cnt;

RAND() alone is useless for set-based generation so generating the baseline for comparing randomness took over 6 hours and had to be restarted several times to finally get the right number of output rows.  It also seems that the randomness leaves a lot to be desired although it's better than using checksum(newid()) to reseed each row.

Cnt  Pct
---- ----
1    99.768020
2    00.115840
3    00.000100  -- at least there were comparitively few values returned 3 times

Because of the restarts, execution time could not be captured.

IF OBJECT_ID('tempdb..#T2') IS NOT NULL DROP TABLE #T2;
GO
CREATE TABLE #T2 (Val FLOAT);
GO
SET NOCOUNT ON;
GO
INSERT INTO #T2(Val) VALUES(RAND());
GO 100000000

WITH x AS (
    SELECT Val,COUNT(*) Cnt
     FROM #T2
    GROUP BY Val
)
SELECT x.Cnt,COUNT(*)*1.0/(SELECT COUNT(*)/100 FROM #T2) Pct
  FROM X
 GROUP BY x.Cnt;


问:
Format TimestampType in spark DataFrame- Scala
While I try to cast a string field to a TimestampType in Spark DataFrame, the output value is coming with microsecond precision( yyyy-MM-dd HH:mm:ss.S). But I need the format to be yyyy-MM-dd HH:mm:ss ie., excluding the microsecond precision. Also, I want to save this as a time stamp field while writing into a parquet file.
So the datatype of my field should be a timestamp of format yyyy-MM-dd HH:mm:ss

I tried using TimestampType as

```<code>col("column_A").cast(TimestampType)
or
col("column_A").cast("timestamp")
</code>```

to cast the field to timestamp. These are able to cast the field to timestamp but with the microsecond precision.

Can anyone help in saving the timestamp datatype to parquet file with the required format specification.

EDIT

Input:

```<code>val a = sc.parallelize(List(("a", "2017-01-01 12:02:00.0"), ("b", "2017-02-01 11:22:30"))).toDF("cola", "colb")
scala> a.withColumn("datetime", date_format(col("colb"), "yyyy-MM-dd HH:mm:ss")).show(false)
+----+---------------------+-------------------+
|cola|colb                 |datetime           |
+----+---------------------+-------------------+
|a   |2017-01-01 12:02:00.0|2017-01-01 12:02:00|
|b   |2017-02-01 11:22:30  |2017-02-01 11:22:30|
+----+---------------------+-------------------+

scala> a.withColumn("datetime", date_format(col("colb"), "yyyy-MM-dd HH:mm:ss")).printSchema
root
 |-- cola: string (nullable = true)
 |-- colb: string (nullable = true)
 |-- datetime: string (nullable = true)
</code>```

In the above, we are getting the right timestamp format, but when we print the Schema, the datetime field is of type String, but I need a timestamp type here.

Now,if I attempt to cast the field to timestamp, the format is set to microsecond precision, which is not intended.

```<code>scala> import org.apache.spark.sql.types._
import org.apache.spark.sql.types._

scala> val a = sc.parallelize(List(("a", "2017-01-01 12:02:00.0"), ("b", "2017-02-01 11:22:30"))).toDF("cola", "colb")
a: org.apache.spark.sql.DataFrame = [cola: string, colb: string]

scala> a.withColumn("datetime", date_format(col("colb").cast(TimestampType), "yyyy-MM-dd HH:mm:ss").cast(TimestampType)).show(false)
+----+---------------------+---------------------+
|cola|colb                 |datetime             |
+----+---------------------+---------------------+
|a   |2017-01-01 12:02:00.0|2017-01-01 12:02:00.0|
|b   |2017-02-01 11:22:30  |2017-02-01 11:22:30.0|
+----+---------------------+---------------------+

scala> a.withColumn("datetime", date_format(col("colb").cast(TimestampType), "yyyy-MM-dd HH:mm:ss").cast(TimestampType)).printSchema
root
 |-- cola: string (nullable = true)
 |-- colb: string (nullable = true)
 |-- datetime: timestamp (nullable = true)
</code>```

What I am expecting is for the format to be in yyyy-MM-dd HH:mm:ss and also the datatype of the field to be of timestamp
Thanks in advance

答:
You can use unix_timestamp to convert the string date time to timestamp.

unix_timestamp(Column s, String p) Convert time string with given
  pattern (see
  [http://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html ])
  to Unix time stamp (in seconds), return null if fail.

```<code>val format = "yyyy-MM-dd HH:mm:ss"
dataframe.withColumn("column_A", unix_timestamp($"date", format))
</code>```

Hope this helps!

Body:
While I try to cast a string field to a TimestampType in Spark DataFrame, the output value is coming with microsecond precision( yyyy-MM-dd HH:mm:ss.S). But I need the format to be yyyy-MM-dd HH:mm:ss ie., excluding the microsecond precision. Also, I want to save this as a time stamp field while writing into a parquet file.
So the datatype of my field should be a timestamp of format yyyy-MM-dd HH:mm:ss

I tried using TimestampType as

col("column_A").cast(TimestampType)
or
col("column_A").cast("timestamp")

to cast the field to timestamp. These are able to cast the field to timestamp but with the microsecond precision.

Can anyone help in saving the timestamp datatype to parquet file with the required format specification.

EDIT

Input:

val a = sc.parallelize(List(("a", "2017-01-01 12:02:00.0"), ("b", "2017-02-01 11:22:30"))).toDF("cola", "colb")
scala> a.withColumn("datetime", date_format(col("colb"), "yyyy-MM-dd HH:mm:ss")).show(false)
+----+---------------------+-------------------+
|cola|colb                 |datetime           |
+----+---------------------+-------------------+
|a   |2017-01-01 12:02:00.0|2017-01-01 12:02:00|
|b   |2017-02-01 11:22:30  |2017-02-01 11:22:30|
+----+---------------------+-------------------+

scala> a.withColumn("datetime", date_format(col("colb"), "yyyy-MM-dd HH:mm:ss")).printSchema
root
 |-- cola: string (nullable = true)
 |-- colb: string (nullable = true)
 |-- datetime: string (nullable = true)

In the above, we are getting the right timestamp format, but when we print the Schema, the datetime field is of type String, but I need a timestamp type here.

Now,if I attempt to cast the field to timestamp, the format is set to microsecond precision, which is not intended.

scala> import org.apache.spark.sql.types._
import org.apache.spark.sql.types._

scala> val a = sc.parallelize(List(("a", "2017-01-01 12:02:00.0"), ("b", "2017-02-01 11:22:30"))).toDF("cola", "colb")
a: org.apache.spark.sql.DataFrame = [cola: string, colb: string]

scala> a.withColumn("datetime", date_format(col("colb").cast(TimestampType), "yyyy-MM-dd HH:mm:ss").cast(TimestampType)).show(false)
+----+---------------------+---------------------+
|cola|colb                 |datetime             |
+----+---------------------+---------------------+
|a   |2017-01-01 12:02:00.0|2017-01-01 12:02:00.0|
|b   |2017-02-01 11:22:30  |2017-02-01 11:22:30.0|
+----+---------------------+---------------------+

scala> a.withColumn("datetime", date_format(col("colb").cast(TimestampType), "yyyy-MM-dd HH:mm:ss").cast(TimestampType)).printSchema
root
 |-- cola: string (nullable = true)
 |-- colb: string (nullable = true)
 |-- datetime: timestamp (nullable = true)

What I am expecting is for the format to be in yyyy-MM-dd HH:mm:ss and also the datatype of the field to be of timestamp
Thanks in advance

Body:
You can use unix_timestamp to convert the string date time to timestamp.

unix_timestamp(Column s, String p) Convert time string with given
  pattern (see
  [http://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html ])
  to Unix time stamp (in seconds), return null if fail.

val format = "yyyy-MM-dd HH:mm:ss"
dataframe.withColumn("column_A", unix_timestamp($"date", format))

Hope this helps!

ContentLicense: CC BY-SA 4.0


问:
Using resources with the same name in Xcode
Is there a way to add multiple resources with the same name to an Xcode project and have 1 of them take priority over the others?

Example:
I added 2 files, both called icon.png, to an Xcode project. They are on different folders in the file system (Folder1/icon.png and Folder2/icon.png) and on different groups in Xcode. Is there a way to tell Xcode to have Folder2/icon.png take priority over Folder1/icon.png? And if only 1 icon.png exists, then use that one.

Thanks.

EDIT (2010-12-23):

You can have multiple files with the same name in an Xcode project even if they are not in separate folder references, but they are in separate groups. Once compiled, the app bundle (which will be flat with no folders in it), will only have one copy of the file (icon.png). How do you pick which copy of the file to use?

I was told that you can do this for BlackBerry. It works something like this: The compiler will go down the list of files in the project and start adding them to the app bundle. If it sees a duplicate, it will overwrite it (or not), so the files at the bottom (or at the top) will have higher precedence and will be the final bundle.

答:
Wait a second, since you specifically mentioned icon.png, are you trying to supply different iDevices (iPad, iPhone4, iTouch3...) with different icon images?

If yes, check this out, http://d.pr/W2w0 , Apple has already provided a way for us to finish this task with convenience. All you need to do is following a specific naming convention.


问:
Swift 3 "Thread 1: signal SIGABRT" error
I am getting this aforementioned error. I've applied the following solution from this thread and that one with no avail. Is there some module or class I'm suppose to import? Any help will be appreciated.

Github: https://github.com/joeavargas/BMI-Calc/tree/master/BMI%20Calc

Swift 3 / Xcode 8.3.3

error

Error from Console:

2017-07-06 08:20:28.252 BMI Calc[61662:12276419] * Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key mass.'
* First throw call stack:
(
    0   CoreFoundation                      0x000000010df6eb0b exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010b2fe141 objc_exception_throw + 48
    2   CoreFoundation                      0x000000010df6ea59 -[NSException raise] + 9
    3   Foundation                          0x000000010ae1400b -[NSObject(NSKeyValueCoding) setValue:forKey:] + 292
    4   UIKit                               0x000000010b96b994 -[UIViewController setValue:forKey:] + 87
    5   UIKit                               0x000000010bbd8a09 -[UIRuntimeOutletConnection connect] + 109
    6   CoreFoundation                      0x000000010df14e8d -[NSArray makeObjectsPerformSelector:] + 269
    7   UIKit                               0x000000010bbd73bf -[UINib instantiateWithOwner:options:] + 1856
    8   UIKit                               0x000000010b971fc3 -[UIViewController _loadViewFromNibNamed:bundle:] + 381
    9   UIKit                               0x000000010b9728d9 -[UIViewController loadView] + 177
    10  UIKit                               0x000000010b972c0a -[UIViewController loadViewIfRequired] + 195
    11  UIKit                               0x000000010b97345a -[UIViewController view] + 27
    12  UIKit                               0x000000010b83b98a -[UIWindow addRootViewControllerViewIfPossible] + 65
    13  UIKit                               0x000000010b83c070 -[UIWindow _setHidden:forced:] + 294
    14  UIKit                               0x000000010b84eebe -[UIWindow makeKeyAndVisible] + 42
    15  UIKit                               0x000000010b7c837f -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4346
    16  UIKit                               0x000000010b7ce5e4 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1709
    17  UIKit                               0x000000010b7cb7f3 -[UIApplication workspaceDidEndTransaction:] + 182
    18  FrontBoardServices                  0x000000010f67e5f6 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK + 24
    19  FrontBoardServices                  0x000000010f67e46d -[FBSSerialQueue _performNext] + 186
    20  FrontBoardServices                  0x000000010f67e7f6 -[FBSSerialQueue _performNextFromRunLoopSource] + 45
    21  CoreFoundation                      0x000000010df14c01 CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 17
    22  CoreFoundation                      0x000000010defa0cf __CFRunLoopDoSources0 + 527
    23  CoreFoundation                      0x000000010def95ff __CFRunLoopRun + 911
    24  CoreFoundation                      0x000000010def9016 CFRunLoopRunSpecific + 406
    25  UIKit                               0x000000010b7ca08f -[UIApplication _run] + 468
    26  UIKit                               0x000000010b7d0134 UIApplicationMain + 159
    27  BMI Calc                            0x000000010ad246f7 main + 55
    28  libdyld.dylib                       0x000000010ef0e65d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

答:
The most significant information is

this class is not key value coding-compliant for the key mass.

Select the storyboard or xib file in the project navigator

Select the view controller

Open Connection Inspector (⌥⌘6)

Remove the connection to mass


问:
load the csv file into Big query auto detect schema using python API
I'm trying to load the CSV file with schema under auto detection but I am unable to load the file into Big query. Can any one help me on this.

Please find my code below:

```<code>def load_data_from_file(dataset_name, table_name, source_file_name):

    bigquery_client = bigquery.Client()
    dataset = bigquery_client.dataset(dataset_name)
    table = dataset.table(table_name)
    table.reload()
    with open(source_file_name, 'rb') as source_file:
        job = table.upload_from_file(
            source_file, source_format='text/csv')
    wait_for_job(job)
    print('Loaded {} rows into {}:{}.'.format(
        job.output_rows, dataset_name, table_name))
def wait_for_job(job):
    while True:
        job.reload()
        if job.state == 'DONE':
            if job.error_result:
                raise RuntimeError(job.errors)
            return
    time.sleep(1)
</code>```

答:
Based on the Google BigQuery python API documentation, you should set source_format to 'CSV' instead of 'text/csv':

```<code>source_format='CSV'
</code>```

Code Sample:

```<code>with open(csv_file.name, 'rb') as readable:
    table.upload_from_file(
        readable, source_format='CSV', skip_leading_rows=1)
</code>```

Source: https://googlecloudplatform.github.io/google-cloud-python/stable/bigquery-usage.html#datasets

If this does not solve your problem, please provide more specifics about the errors you are observing.

Body:
I'm trying to load the CSV file with schema under auto detection but I am unable to load the file into Big query. Can any one help me on this.

Please find my code below:

def load_data_from_file(dataset_name, table_name, source_file_name):

    bigquery_client = bigquery.Client()
    dataset = bigquery_client.dataset(dataset_name)
    table = dataset.table(table_name)
    table.reload()
    with open(source_file_name, 'rb') as source_file:
        job = table.upload_from_file(
            source_file, source_format='text/csv')
    wait_for_job(job)
    print('Loaded {} rows into {}:{}.'.format(
        job.output_rows, dataset_name, table_name))
def wait_for_job(job):
    while True:
        job.reload()
        if job.state == 'DONE':
            if job.error_result:
                raise RuntimeError(job.errors)
            return
    time.sleep(1)

Body:
Based on the Google BigQuery python API documentation, you should set source_format to 'CSV' instead of 'text/csv':

source_format='CSV'

Code Sample:

with open(csv_file.name, 'rb') as readable:
    table.upload_from_file(
        readable, source_format='CSV', skip_leading_rows=1)

Source: https://googlecloudplatform.github.io/google-cloud-python/stable/bigquery-usage.html#datasets

If this does not solve your problem, please provide more specifics about the errors you are observing.


问:
Can git tell me if a rebase will conflict without actually rebasing?
I would like to programmatically determine with of my feature branches would have rebase conflicts if I tried to rebase them.  Is there a way I can get git to tell me this information without actually performing the rebase?

Failing that, what is the simplest way to detect if a rebase failed before git rebase --aborting it?

My question is similar to these two, which are the same but for merge instead of rebase

Can git tell me if a merge will conflict without actually merging?

Is there a git-merge --dry-run option?

答:
The closest thing to a "dry run" of a rebase would be to run the rebase from detached HEAD state (so that no refs are actually modified).  So instead of

```<code>git rebase develop feature_X
</code>```

you might do

```<code>git rebase develop `git rev-parse feature_x`
</code>```

and check the exit status.  The problems with this approach are:

1) It's time consuming.  Basically for any branch that doesn't conflict, the entire rebase will run.  (And it's hard to imagine how you could do much less work and still accurately know whether the rebase would succeed anyway.)

2) It creates redundant objects (dangling commits and their dependencies), which won't be visible but will nonetheless hang around taking up space in your local repo until you either knock the dangling commits out of the reflog and run gc, or create a fresh clone.  If you do this often, the wasted space could really add up.

I'm also not sure how much utility this has.  Just because feature_X and feature_Y would each rebase cleanly onto develop, doesn't mean that the sequence of "rebase featureX then rebase featureY" will necessarily complete cleanly.  And while it doesn't seem like it should be the case, after some things I've seen recently I wouldn't be shocked to learn of some edge case where the order of rebases determines whether there's a conflict.

So at best you'll get the "low hanging fruit" - "I know for a fact these have conflicts".  But hey, you know, if that's the code you need, then that's the code you need.

Body:
The closest thing to a "dry run" of a rebase would be to run the rebase from detached HEAD state (so that no refs are actually modified).  So instead of

git rebase develop feature_X

you might do

git rebase develop `git rev-parse feature_x`

and check the exit status.  The problems with this approach are:

1) It's time consuming.  Basically for any branch that doesn't conflict, the entire rebase will run.  (And it's hard to imagine how you could do much less work and still accurately know whether the rebase would succeed anyway.)

2) It creates redundant objects (dangling commits and their dependencies), which won't be visible but will nonetheless hang around taking up space in your local repo until you either knock the dangling commits out of the reflog and run gc, or create a fresh clone.  If you do this often, the wasted space could really add up.

I'm also not sure how much utility this has.  Just because feature_X and feature_Y would each rebase cleanly onto develop, doesn't mean that the sequence of "rebase featureX then rebase featureY" will necessarily complete cleanly.  And while it doesn't seem like it should be the case, after some things I've seen recently I wouldn't be shocked to learn of some edge case where the order of rebases determines whether there's a conflict.

So at best you'll get the "low hanging fruit" - "I know for a fact these have conflicts".  But hey, you know, if that's the code you need, then that's the code you need.