问:
Evernote API Sandbox Rate Limit Duration greater than 15 seconds
The Evernote API (Python SDK) is supposed to implement rate limiting in sandbox exactly the same as production, but the rate limit only lasts for 15 seconds.

I have a test suite that tests the rate-limit by make API calls until an exception occurs.

After waiting 1 minute, the same error, EDAMSystemException(errorCode=19, rateLimitDuration=2651, _message='DuplicateNoteLimiter'), still occurs.

Code:

```<code>from evernote.api.client import EvernoteClient
from evernote.edam.error.ttypes import EDAMSystemException
import evernote.edam.type.ttypes as Types
import time

def getClient():
    return EvernoteClient(
            token=config.dev_token,
            sandbox=True
        )

def makeNote(client):
    note = Types.Note()
    note.title = 'spam'
    content = ''
    note.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
    note.content += '<en-note>'+ content + '</en-note>'
    return client.get_note_store().createNote(note)

def test_api_limit():
    client = getClient()

    try:
        while(True):
            makeNote(client)
    except EDAMSystemException as e:
           assert e.errorCode == 19
           print 'Caught Rate Limit Exception'
           time.sleep(60)
           makeNote(client) # still raise exception
           print 'No exception occurred!' # this statement is not executed.

test_api_limit()
</code>```

答:
In addition to errorCode=RATE_LIMIT_REACHED, the exception includes

message="DuplicateNoteLimiter"

This message indicates that Evernote service has detected a large number of note duplication via API call. Since it does not make sense to have so many notes with the same content in an account, it is limiting such a request to avoid wasting their computing resources.

If you try to create a note with unique content, you would not see this behavior.

For example :

you can try to include a system time in milliseconds in a new note in your code

```<code>from datetime import datetime

def makeNote(client):
    note = Types.Note()
    note.title = 'spam'
    content = str(datetime.now().microsecond)
    note.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
    note.content += '<en-note>'+ content + '</en-note>'
    return client.get_note_store().createNote(note)
</code>```

This modification will prevent the "duplication limiter" from getting triggered. According to my testing, the rate limit will be reset almost immediately after it is thrown.  Somehow the reset happens much sooner than 15 seconds as Evernote explains.

BTW, your code invokes client.get_note_store() every time you create a note.  You should just call once to get a NoteStore handler to reuse.  Since the function call will lead to an API call on UserStore, you will waste your allowance otherwise.

Body:
The Evernote API (Python SDK) is supposed to implement rate limiting in sandbox exactly the same as production, but the rate limit only lasts for 15 seconds.

I have a test suite that tests the rate-limit by make API calls until an exception occurs.

After waiting 1 minute, the same error, EDAMSystemException(errorCode=19, rateLimitDuration=2651, _message='DuplicateNoteLimiter'), still occurs.

Code:

from evernote.api.client import EvernoteClient
from evernote.edam.error.ttypes import EDAMSystemException
import evernote.edam.type.ttypes as Types
import time

def getClient():
    return EvernoteClient(
            token=config.dev_token,
            sandbox=True
        )

def makeNote(client):
    note = Types.Note()
    note.title = 'spam'
    content = ''
    note.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
    note.content += '<en-note>'+ content + '</en-note>'
    return client.get_note_store().createNote(note)

def test_api_limit():
    client = getClient()

    try:
        while(True):
            makeNote(client)
    except EDAMSystemException as e:
           assert e.errorCode == 19
           print 'Caught Rate Limit Exception'
           time.sleep(60)
           makeNote(client) # still raise exception
           print 'No exception occurred!' # this statement is not executed.

test_api_limit()

Body:
In addition to errorCode=RATE_LIMIT_REACHED, the exception includes

message="DuplicateNoteLimiter"

This message indicates that Evernote service has detected a large number of note duplication via API call. Since it does not make sense to have so many notes with the same content in an account, it is limiting such a request to avoid wasting their computing resources.

If you try to create a note with unique content, you would not see this behavior.

For example :

you can try to include a system time in milliseconds in a new note in your code

from datetime import datetime

def makeNote(client):
    note = Types.Note()
    note.title = 'spam'
    content = str(datetime.now().microsecond)
    note.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
    note.content += '<en-note>'+ content + '</en-note>'
    return client.get_note_store().createNote(note)

This modification will prevent the "duplication limiter" from getting triggered. According to my testing, the rate limit will be reset almost immediately after it is thrown.  Somehow the reset happens much sooner than 15 seconds as Evernote explains.

BTW, your code invokes client.get_note_store() every time you create a note.  You should just call once to get a NoteStore handler to reuse.  Since the function call will lead to an API call on UserStore, you will waste your allowance otherwise.


来源: stackexchange

问:
Python Speed Optimization
I am creating a program (to test a theory), and to get the data I need, I need a program to run as fast as possible.

Here's the problem - I have made it as fast as I could manage and it is still to slow. It is using a very small amount of my computer's RAM and CPU capacity. I am running the program with PyCharm 2017 Community Edition.

The code is below; How would I further optimize or change this to make it run faster?

Main:

```<code>from functions import *
from graphics import *
import time

Alpha = True

x = timestamp()

while Alpha:
    master = GraphWin(title="Image", width=512, height=512)

    build_image(master)

    getter(master, x)

    x = timestamp()

    time.sleep(3)

    master.close()
</code>```

Module "Functions":

```<code>from graphics import *
import random
from PIL import ImageGrab

def build_image(window):
    for i in range(513):
        for j in range(513):
            fig = Rectangle(Point(j, i), Point(j + 1, i + 1))
            color = random.randrange(256)
            fig.setFill(color_rgb(color, color, color))
            fig.setOutline(color_rgb(color, color, color))
            fig.draw(window)

def getter(widget, counter):
    x = widget.winfo_rootx()+widget.winfo_x()
    y = widget.winfo_rooty()+widget.winfo_y()
    x1 = x+widget.winfo_width()
    y1 = y+widget.winfo_height()
    ImageGrab.grab().crop((x, y, x1, y1)).save("{}.png".format(str(counter)))

def timestamp():
    timelist = time.gmtime()
    filename = ("Image" + "_" + str(timelist[0]) + "_" + str(timelist[1]) + "_" + str(timelist[2]) + "_" +
                str(timelist[3]) + "_" + str(timelist[4]) + "_" + str(timelist[5]) + "_UTC")
    return filename
</code>```

Note: Module "Graphics" is a module that allows for easy manipulation of Tkinter.

答:
Use a profiler to see where your program is fast/slow. Here is a profile wrapper you can use on your functions to see what is taking too long in your program.

```<code>def line_profiler(view=None, extra_view=None):
import line_profiler

def wrapper(view):
    def wrapped(*args, **kwargs):
        prof = line_profiler.LineProfiler()
        prof.add_function(view)
        if extra_view:
            [prof.add_function(v) for v in extra_view]
        with prof:
            resp = view(*args, **kwargs)
        prof.print_stats()
        return resp
    return wrapped
if view:
    return wrapper(view)
return wrapper
</code>```

Now how to use it

```<code>@line_profiler
def simple():
    print("Hello")
    print("World")
</code>```

Now when you run your function, you will get a printout of how long everything takes.

You might need to do pip install line_profiler

ContentLicense: CC BY-SA 3.0

Title: Python Speed Optimization

Body:
I am creating a program (to test a theory), and to get the data I need, I need a program to run as fast as possible.

Here's the problem - I have made it as fast as I could manage and it is still to slow. It is using a very small amount of my computer's RAM and CPU capacity. I am running the program with PyCharm 2017 Community Edition.

The code is below; How would I further optimize or change this to make it run faster?

Main:

from functions import *
from graphics import *
import time

Alpha = True

x = timestamp()

while Alpha:
    master = GraphWin(title="Image", width=512, height=512)

    build_image(master)

    getter(master, x)

    x = timestamp()

    time.sleep(3)

    master.close()

Module "Functions":

from graphics import *
import random
from PIL import ImageGrab

def build_image(window):
    for i in range(513):
        for j in range(513):
            fig = Rectangle(Point(j, i), Point(j + 1, i + 1))
            color = random.randrange(256)
            fig.setFill(color_rgb(color, color, color))
            fig.setOutline(color_rgb(color, color, color))
            fig.draw(window)

def getter(widget, counter):
    x = widget.winfo_rootx()+widget.winfo_x()
    y = widget.winfo_rooty()+widget.winfo_y()
    x1 = x+widget.winfo_width()
    y1 = y+widget.winfo_height()
    ImageGrab.grab().crop((x, y, x1, y1)).save("{}.png".format(str(counter)))

def timestamp():
    timelist = time.gmtime()
    filename = ("Image" + "_" + str(timelist[0]) + "_" + str(timelist[1]) + "_" + str(timelist[2]) + "_" +
                str(timelist[3]) + "_" + str(timelist[4]) + "_" + str(timelist[5]) + "_UTC")
    return filename

Note: Module "Graphics" is a module that allows for easy manipulation of Tkinter.

Body:
Use a profiler to see where your program is fast/slow. Here is a profile wrapper you can use on your functions to see what is taking too long in your program.

def line_profiler(view=None, extra_view=None):
import line_profiler

def wrapper(view):
    def wrapped(*args, **kwargs):
        prof = line_profiler.LineProfiler()
        prof.add_function(view)
        if extra_view:
            [prof.add_function(v) for v in extra_view]
        with prof:
            resp = view(*args, **kwargs)
        prof.print_stats()
        return resp
    return wrapped
if view:
    return wrapper(view)
return wrapper

Now how to use it

@line_profiler
def simple():
    print("Hello")
    print("World")

Now when you run your function, you will get a printout of how long everything takes.

You might need to do pip install line_profiler


问:
Btrieve GetNextExtended Status 62
I'm having trouble getting the GetNextExtended(36) operation working
in Btrieve. Here is the call which returns the status code 62 :

```<code>    intStatus = BTRCALL(B_GETNEXTEXTENDED, _
                        m_byteFilePosBlk, _
                        m_byteRecordBuffer(0), _
                        lngDataBufferLen, _
                        ByVal strKeyBuffer, _
                        intKeyBufferLen, _
                        m_intKeyNum)
</code>```

After doing a search for the code I found numerous site stating that the
code indicates an error in the databuffer, stored in m_byteRecordBuffer.
Here are the values stored in that variable :

```<code>m_byteRecordBuffer(0)    16    'These two bytes indicate the total size of'
m_byteRecordBuffer(1)    0     'data buffer'

m_byteRecordBuffer(2)    67    'These two bytes indicate the characters 'UC''
m_byteRecordBuffer(3)    85

m_byteRecordBuffer(4)    0     'These two bytes indicate the maximum reject'
m_byteRecordBuffer(5)    0     'count, which if set to 0 defaults to 4,095'

m_byteRecordBuffer(6)    0     'These two bytes indicate the number of terms'
m_byteRecordBuffer(7)    0     'which has been set to zero'

m_byteRecordBuffer(8)    1     'These two bytes indicate the number of'
m_byteRecordBuffer(9)    0     'records to return'

m_byteRecordBuffer(10)  1     'These two bytes indicate the number of fields'
m_byteRecordBuffer(11)  0     'to extract'

m_byteRecordBuffer(12)  2     'These two bytes indicate the length of the'
m_byteRecordBuffer(13)  0     'field to extract'

m_byteRecordBuffer(14)  1     'These two bytes indicate the field offset'
m_byteRecordBuffer(15)  0
</code>```

I hope I am just missing something simple. Any help would be greatly appreciated.

答:
In the record buffer, try swapping the position of the UC characters.

Put 'U' (85) in position 2 and 'C' (67) in position 3.

ContentLicense: CC BY-SA 2.5

Title: Btrieve GetNextExtended Status 62

Body:
I'm having trouble getting the GetNextExtended(36) operation working
in Btrieve. Here is the call which returns the status code 62 :

    intStatus = BTRCALL(B_GETNEXTEXTENDED, _
                        m_byteFilePosBlk, _
                        m_byteRecordBuffer(0), _
                        lngDataBufferLen, _
                        ByVal strKeyBuffer, _
                        intKeyBufferLen, _
                        m_intKeyNum)

After doing a search for the code I found numerous site stating that the
code indicates an error in the databuffer, stored in m_byteRecordBuffer.
Here are the values stored in that variable :

m_byteRecordBuffer(0)    16    'These two bytes indicate the total size of'
m_byteRecordBuffer(1)    0     'data buffer'

m_byteRecordBuffer(2)    67    'These two bytes indicate the characters 'UC''
m_byteRecordBuffer(3)    85

m_byteRecordBuffer(4)    0     'These two bytes indicate the maximum reject'
m_byteRecordBuffer(5)    0     'count, which if set to 0 defaults to 4,095'

m_byteRecordBuffer(6)    0     'These two bytes indicate the number of terms'
m_byteRecordBuffer(7)    0     'which has been set to zero'

m_byteRecordBuffer(8)    1     'These two bytes indicate the number of'
m_byteRecordBuffer(9)    0     'records to return'

m_byteRecordBuffer(10)  1     'These two bytes indicate the number of fields'
m_byteRecordBuffer(11)  0     'to extract'

m_byteRecordBuffer(12)  2     'These two bytes indicate the length of the'
m_byteRecordBuffer(13)  0     'field to extract'

m_byteRecordBuffer(14)  1     'These two bytes indicate the field offset'
m_byteRecordBuffer(15)  0

I hope I am just missing something simple. Any help would be greatly appreciated.


问:
List of invhist_transtypes from xtuple
I am in need the of meaning behind the 2 letter codes in the following column in xtuple:

```<code>public.invhist.invhist_transtypes
</code>```

some examples in records are IM AD and CC.

答:
It took me a while, but I found this link which should have everything I need and I want to document it for the world because it was a bit hard to find.

This is the list as of 12/31/2019

https://manuals.xtuple.com/refguide/current/Section461282.html

Title: List of invhist_transtypes from xtuple

Body:
I am in need the of meaning behind the 2 letter codes in the following column in xtuple:

public.invhist.invhist_transtypes

some examples in records are IM AD and CC.

ContentLicense: CC BY-SA 4.0


问:
create new array of objects from existing array
I have an existing array that I would like to reformat in JS. Here is the existing array where each item is an object:

```<code>[
 {
  end_time:"7.14",
  pk:45065,
  start_time:"4.51",
  text:"Lorem Ipsum"
 },
 {
  end_time:"9.00",
  pk:45066,
  start_time:"7.14",
  text:"Lorem Ipsum Something"
 },
 {
  end_time:"13.09",
  pk:450667 ,
  start_time:"9.00",
  text:"Lorem Ipsum Something"
 },
 {
  end_time:"17.01",
  pk:45068,
  start_time:"13.09",
  text:"Lorem Ipsum"
 },
 {
  end_time:"25.10",
  pk:45069,
  start_time:"17.01",
  text:"Lorem Ipsum Something"
 },
 {
  end_time:"28.06",
  pk:450670 ,
  start_time:"25.10",
  text:"Lorem Ipsum Something"
 },
]
</code>```

I would like to create a new array of objects where for every three objects in old array becomes one object in the new array like so:

```<code> [
  segment: {
    phrase: {
      end_time:"7.14",
      pk:45065,
      start_time:"4.51",
      text:"Lorem Ipsum"
    },
    phrase: {
      end_time:"9.00",
      pk:45066,
      start_time:"7.14",
      text:"Lorem Ipsum Something"
     },
     phrase: {
      end_time:"13.09",
      pk:450667 ,
      start_time:"9.00",
      text:"Lorem Ipsum Something"
     }
  },
  segment {
    phrase: {
      end_time:"17.01",
      pk:45068,
      start_time:"13.09",
      text:"Lorem Ipsum"
    },
    phrase: {
      end_time:"25.10",
      pk:45069,
      start_time:"17.01",
      text:"Lorem Ipsum Something"
    },
    phrase: {
      end_time:"28.06",
      pk:450670 ,
      start_time:"25.10",
      text:"Lorem Ipsum Something"
    },
  }
]
</code>```

What I am struggling with most is how to pull out every three items and push to the new segment object inside a map or loop I guess. I am not sure the most efficient way to go about this. Any help is much appreciated.

答:
Your wanted result should be object as arrays have no string keys.

Objects should have unique keys, so the proposed solution appends number suffixes to 'segment' and 'phrase' keys.

The code:

var arr = [
  {
    end_time:"7.14",
    pk:45065,
    start_time:"4.51",
    text:"Lorem Ipsum"
  },
  {
    end_time:"9.00",
    pk:45066,
    start_time:"7.14",
    text:"Lorem Ipsum Something"
  },
  {
    end_time:"13.09",
    pk:450667 ,
    start_time:"9.00",
    text:"Lorem Ipsum Something"
  },
  {
    end_time:"17.01",
    pk:45068,
    start_time:"13.09",
    text:"Lorem Ipsum"
  },
  {
    end_time:"25.10",
    pk:45069,
    start_time:"17.01",
    text:"Lorem Ipsum Something"
  },
  {
    end_time:"28.06",
    pk:450670 ,
    start_time:"25.10",
    text:"Lorem Ipsum Something"
  },
];
var obj = {};
arr.forEach(arrayTransformClosure(obj));
document.getElementById('output').innerHTML = JSON.stringify(obj, null, 2);
// Functions
function arrayTransformClosure(obj) {
  var phrase = 0;
  var segment = 1;
  return function (elem) {
    ++phrase;
    if (phrase == 1) {
      obj['segment_' + segment] = {
        ['phrase_' + phrase]: elem
      };
    } else if (phrase <= 3) {
      obj['segment_' + segment]['phrase_' + phrase] = elem;
    } else {
      phrase = 1;
      ++segment;
      obj['segment_' + segment] = {
        ['phrase_' + phrase]: elem
      };
    }
  };
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id="output">``````

Body:
I have an existing array that I would like to reformat in JS. Here is the existing array where each item is an object:

[
 {
  end_time:"7.14",
  pk:45065,
  start_time:"4.51",
  text:"Lorem Ipsum"
 },
 {
  end_time:"9.00",
  pk:45066,
  start_time:"7.14",
  text:"Lorem Ipsum Something"
 },
 {
  end_time:"13.09",
  pk:450667 ,
  start_time:"9.00",
  text:"Lorem Ipsum Something"
 },
 {
  end_time:"17.01",
  pk:45068,
  start_time:"13.09",
  text:"Lorem Ipsum"
 },
 {
  end_time:"25.10",
  pk:45069,
  start_time:"17.01",
  text:"Lorem Ipsum Something"
 },
 {
  end_time:"28.06",
  pk:450670 ,
  start_time:"25.10",
  text:"Lorem Ipsum Something"
 },
]

I would like to create a new array of objects where for every three objects in old array becomes one object in the new array like so:

 [
  segment: {
    phrase: {
      end_time:"7.14",
      pk:45065,
      start_time:"4.51",
      text:"Lorem Ipsum"
    },
    phrase: {
      end_time:"9.00",
      pk:45066,
      start_time:"7.14",
      text:"Lorem Ipsum Something"
     },
     phrase: {
      end_time:"13.09",
      pk:450667 ,
      start_time:"9.00",
      text:"Lorem Ipsum Something"
     }
  },
  segment {
    phrase: {
      end_time:"17.01",
      pk:45068,
      start_time:"13.09",
      text:"Lorem Ipsum"
    },
    phrase: {
      end_time:"25.10",
      pk:45069,
      start_time:"17.01",
      text:"Lorem Ipsum Something"
    },
    phrase: {
      end_time:"28.06",
      pk:450670 ,
      start_time:"25.10",
      text:"Lorem Ipsum Something"
    },
  }
]

What I am struggling with most is how to pull out every three items and push to the new segment object inside a map or loop I guess. I am not sure the most efficient way to go about this. Any help is much appreciated.

Body:
Your wanted result should be object as arrays have no string keys.

Objects should have unique keys, so the proposed solution appends number suffixes to 'segment' and 'phrase' keys.

The code:

var arr = [
  {
    end_time:"7.14",
    pk:45065,
    start_time:"4.51",
    text:"Lorem Ipsum"
  },
  {
    end_time:"9.00",
    pk:45066,
    start_time:"7.14",
    text:"Lorem Ipsum Something"
  },
  {
    end_time:"13.09",
    pk:450667 ,
    start_time:"9.00",
    text:"Lorem Ipsum Something"
  },
  {
    end_time:"17.01",
    pk:45068,
    start_time:"13.09",
    text:"Lorem Ipsum"
  },
  {
    end_time:"25.10",
    pk:45069,
    start_time:"17.01",
    text:"Lorem Ipsum Something"
  },
  {
    end_time:"28.06",
    pk:450670 ,
    start_time:"25.10",
    text:"Lorem Ipsum Something"
  },
];
var obj = {};
arr.forEach(arrayTransformClosure(obj));
document.getElementById('output').innerHTML = JSON.stringify(obj, null, 2);
// Functions
function arrayTransformClosure(obj) {
  var phrase = 0;
  var segment = 1;
  return function (elem) {
    ++phrase;
    if (phrase == 1) {
      obj['segment_' + segment] = {
        ['phrase_' + phrase]: elem
      };
    } else if (phrase <= 3) {
      obj['segment_' + segment]['phrase_' + phrase] = elem;
    } else {
      phrase = 1;
      ++segment;
      obj['segment_' + segment] = {
        ['phrase_' + phrase]: elem
      };
    }
  };
}

<pre id="output"></pre>


答:
Your slowness is probably from treating the pixels as rectangles in your window.

If all you want to do is generate random images, you can skip the window part. I found this code laying about, after not too much ducking:

```<code>from PIL import Image
import random

def drawImage():
    testImage = Image.new("RGB", (600,600), (255,255,255))
    pixel = testImage.load()

    for x in range(600):
        for y in range(600):
            red = random.randrange(0,255)
            blue = random.randrange(0,255)
            green = random.randrange(0,255)
            pixel[x,y]=(red,blue,green)
    return testImage

def main():
    finalImage = drawImage()
    finalImage.save("finalImage.jpg")
</code>```

Title: Python Speed Optimization

Body:
Your slowness is probably from treating the pixels as rectangles in your window.

If all you want to do is generate random images, you can skip the window part. I found this code laying about, after not too much ducking:

from PIL import Image
import random

def drawImage():
    testImage = Image.new("RGB", (600,600), (255,255,255))
    pixel = testImage.load()

    for x in range(600):
        for y in range(600):
            red = random.randrange(0,255)
            blue = random.randrange(0,255)
            green = random.randrange(0,255)
            pixel[x,y]=(red,blue,green)
    return testImage

def main():
    finalImage = drawImage()
    finalImage.save("finalImage.jpg")


问:
Integrator key review is getting failed, due to api limit not reching 20 days per day
I am using docusign sandbox environment, and want to move Integrator Key to live production, but after submitting To review, it getting failed every time.

I have done many api calls via my end system to docusign, which is using that Integrator Key. Not sure why its happening.
Can someone help me to get , where I can see my api limits of Integrator key. and how to make Review successful.

I am talking about below step.

答:
You can go to https://demo.docusign.net/ and enable API Request logging. Instructions here.

Also checkout this DocuSign blog post to troubleshoot issues with your API calls.


问:
Creating a sub subclass with java

I was directed to create a class Vehicle with three subclasses [RaceCar, Car and Truck] and then put a subclass into Car, like shown in the UML.

But when I try to do this by saying

```<code>public class HybridCar extends Car
</code>```

I get an error. I know that in java I can't double inherit so how do I format the HybridCar Constructor?

here is my Car class.

```<code>public class Car extends Vehicle{
   double luggageCap;
   double passengerCap;

   public Car(String make, String model, double engSz, String id, String year, String color, double lugCap, double passCap){
      super(make, model, engSz, id, year, color);
      luggageCap = lugCap;
      passengerCap = passCap;
   }

   public double getLuggageCap(){
      return luggageCap;
   }

   public double getPassengerCap(){
      return passengerCap;
   }

   public String toString(){
      return super.toString()+", "+luggageCap+", "+passengerCap;
   }
}
</code>```

here is my HybridCar class:

```<code>public class HybridCar extends Car{
   double luggageCap;
   double passengerCap;
   double batteryCap;

   public HybridCar(String make, String model, double engSz, String id,    String year, String color, double lugCap, double passCap, double batCap){
      super(make, model, engSz, id, year, color);
      luggageCap = lugCap;
      passengerCap = passCap;
      batteryCap = batCap;
   }

   public String toString(){
      return super.toString()+", "+luggageCap+", "+passengerCap+", "+batteryCap;
   }

}
</code>```

here is the error log:

HybridCar.java:9: error: constructor Car in class Car cannot be
  applied to given types; super(make, model, engSz, id, year, color); ^
  required: String,String,double,String,String,String,double,double
  found: String,String,double,String,String,String reason: actual and
  formal argument lists differ in length 1 error –

答:
error: constructor Car in class Car cannot be applied to given types;
  super(make, model, engSz, id, year, color); ^ required:
  String,String,double,String,String,String,double,double found:
  String,String,double,String,String,String reason: actual and formal
  argument lists differ in length 1 error

if you look carefully at the Car constructor there are 8 parameters of certain types:

```<code>Car(String make, String model, double engSz, String id, String year, String color, double lugCap, double passCap)
</code>```

However, you're only passing in 6 parameters:

```<code>super(make, model, engSz, id, year, color);
</code>```

The issue seems to be that you're not passing in the required parameters to the Car constructor.

change your HybribCar constructor to this:

```<code>super(make, model, engSz, id, year, color,lugCap, passCap);
</code>```

side note -  ensure that you're passing the right number of parameters to each class constructor and also ensure the types for each parameter match.

Title: Creating a sub subclass with java

Body:
I was directed to create a class Vehicle with three subclasses [RaceCar, Car and Truck] and then put a subclass into Car, like shown in the UML.

But when I try to do this by saying

public class HybridCar extends Car

I get an error. I know that in java I can't double inherit so how do I format the HybridCar Constructor?

here is my Car class.

public class Car extends Vehicle{
   double luggageCap;
   double passengerCap;

   public Car(String make, String model, double engSz, String id, String year, String color, double lugCap, double passCap){
      super(make, model, engSz, id, year, color);
      luggageCap = lugCap;
      passengerCap = passCap;
   }

   public double getLuggageCap(){
      return luggageCap;
   }

   public double getPassengerCap(){
      return passengerCap;
   }

   public String toString(){
      return super.toString()+", "+luggageCap+", "+passengerCap;
   }
}

here is my HybridCar class:

public class HybridCar extends Car{
   double luggageCap;
   double passengerCap;
   double batteryCap;

   public HybridCar(String make, String model, double engSz, String id,    String year, String color, double lugCap, double passCap, double batCap){
      super(make, model, engSz, id, year, color);
      luggageCap = lugCap;
      passengerCap = passCap;
      batteryCap = batCap;
   }

   public String toString(){
      return super.toString()+", "+luggageCap+", "+passengerCap+", "+batteryCap;
   }

}

here is the error log:

HybridCar.java:9: error: constructor Car in class Car cannot be
  applied to given types; super(make, model, engSz, id, year, color); ^
  required: String,String,double,String,String,String,double,double
  found: String,String,double,String,String,String reason: actual and
  formal argument lists differ in length 1 error –

Body:
error: constructor Car in class Car cannot be applied to given types;
  super(make, model, engSz, id, year, color); ^ required:
  String,String,double,String,String,String,double,double found:
  String,String,double,String,String,String reason: actual and formal
  argument lists differ in length 1 error

if you look carefully at the Car constructor there are 8 parameters of certain types:

Car(String make, String model, double engSz, String id, String year, String color, double lugCap, double passCap)

However, you're only passing in 6 parameters:

super(make, model, engSz, id, year, color);

The issue seems to be that you're not passing in the required parameters to the Car constructor.

change your HybribCar constructor to this:

super(make, model, engSz, id, year, color,lugCap, passCap);

side note -  ensure that you're passing the right number of parameters to each class constructor and also ensure the types for each parameter match.


问:
Running .jar file using Apache POI in Maven project
I'm struggling to run a simple program that uses Apache POI to create an Excel document. This is also my first time with a Maven project, so that might have something to do with it:

My pom.xml looks like this:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>calendar</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>calendar</name>
  <url>http://maven.apache.org</url>

    <dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>

    <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi</artifactId>
          <version>3.10-FINAL</version>
    </dependency>

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.10-FINAL</version>
    </dependency>

  </dependencies>
</project>
</code>```

From what I can tell, my dependencies are alright.

This is my java code, I skipped over import statements but they are all there, no errors in this code from what I can tell:

```<code>public class App
{

    private static final String FILE_NAME = "/tmp/MyFirstExcel.xlsx";

    public static void main( String[] args ) throws IOException
    {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Datatypes in Java");

        Object[][] datatypes = {
            {"Datatype", "Type", "Size(in bytes)"},
            {"int", "Primitive", 2},
            {"float", "Primitive", 4},
            {"double", "Primitive", 8},
            {"char", "Primitive", 1},
            {"String", "Non-Primitive", "No fixed size"}
        };

        int rowNum = 0;
        System.out.println("Creating excel");
        for(Object[] datatype : datatypes) {
            Row row = sheet.createRow(rowNum++);
            int colNum = 0;
            for(Object field : datatype) {
                Cell cell = row.createCell(colNum++);
                if(field instanceof String) {
                    cell.setCellValue((String) field);
                }
                else if(field instanceof Integer) {
                    cell.setCellValue((Integer) field);
                }
            }
        }

        try {
            FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
            workbook.write(outputStream);
            //workbook.close()
        } catch (FileNotFoundException e) {
            System.out.println("Couldn't find file to write out to");
        } catch (IOException e) {
            System.out.println("IO Exception in printing");
        }

    }
}
</code>```

I have workbook.close() commented out since this caused an error (deprecated method?).

With the above code in my source folder, I can run mvn package which builds successfully and generates the .jar file calendar-1.0-SNAPSHOT.jar in the target folder.

I am attempting to run this file using

```<code>java -cp target/calendar-1.0-SNAPSHOT.jar com.mycompany.app.App
</code>```

...and I get the following error message

```<code>Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Workbook
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
        at java.lang.Class.privateGetMethodRecursive(Unknown Source)
        at java.lang.Class.getMethod0(Unknown Source)
        at java.lang.Class.getMethod(Unknown Source)
        at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.apache.poi.ss.usermodel.Workbook
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 7 more
</code>```

If this question requires any more information let me know. I'm at a loss here.

答:
The problem is that at compile time POI libraries are available but not at run time. The reason why they are available is that they are in Maven Dependency. Also I don't see any build wrapper in your pom file. You will need to add a build wrapper to build jar file that you can run outside of your IDE.

Now coming back to your problem, either you need to add POI jar in your CLASSPATH environment variable so that java run-time can access it or build a fat jar including dependencies.

You can use this template to add a build wrapper in pom file to build jar with dependencies.

```<code><build>
    <plugins>
      <plugin>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
          <execution>
            <phase>install</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <outputDirectory>${project.build.directory}/lib</outputDirectory>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</code>```

Body:
I'm struggling to run a simple program that uses Apache POI to create an Excel document. This is also my first time with a Maven project, so that might have something to do with it:

My pom.xml looks like this:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>calendar</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>calendar</name>
  <url>http://maven.apache.org</url>

    <dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>

    <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi</artifactId>
          <version>3.10-FINAL</version>
    </dependency>

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.10-FINAL</version>
    </dependency>

  </dependencies>
</project>

From what I can tell, my dependencies are alright.

This is my java code, I skipped over import statements but they are all there, no errors in this code from what I can tell:

public class App
{

    private static final String FILE_NAME = "/tmp/MyFirstExcel.xlsx";

    public static void main( String[] args ) throws IOException
    {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Datatypes in Java");

        Object[][] datatypes = {
            {"Datatype", "Type", "Size(in bytes)"},
            {"int", "Primitive", 2},
            {"float", "Primitive", 4},
            {"double", "Primitive", 8},
            {"char", "Primitive", 1},
            {"String", "Non-Primitive", "No fixed size"}
        };

        int rowNum = 0;
        System.out.println("Creating excel");
        for(Object[] datatype : datatypes) {
            Row row = sheet.createRow(rowNum++);
            int colNum = 0;
            for(Object field : datatype) {
                Cell cell = row.createCell(colNum++);
                if(field instanceof String) {
                    cell.setCellValue((String) field);
                }
                else if(field instanceof Integer) {
                    cell.setCellValue((Integer) field);
                }
            }
        }

        try {
            FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
            workbook.write(outputStream);
            //workbook.close()
        } catch (FileNotFoundException e) {
            System.out.println("Couldn't find file to write out to");
        } catch (IOException e) {
            System.out.println("IO Exception in printing");
        }

    }
}

I have workbook.close() commented out since this caused an error (deprecated method?).

With the above code in my source folder, I can run mvn package which builds successfully and generates the .jar file calendar-1.0-SNAPSHOT.jar in the target folder.

I am attempting to run this file using

java -cp target/calendar-1.0-SNAPSHOT.jar com.mycompany.app.App

...and I get the following error message

Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Workbook
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
        at java.lang.Class.privateGetMethodRecursive(Unknown Source)
        at java.lang.Class.getMethod0(Unknown Source)
        at java.lang.Class.getMethod(Unknown Source)
        at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.apache.poi.ss.usermodel.Workbook
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 7 more

If this question requires any more information let me know. I'm at a loss here.

Body:
The problem is that at compile time POI libraries are available but not at run time. The reason why they are available is that they are in Maven Dependency. Also I don't see any build wrapper in your pom file. You will need to add a build wrapper to build jar file that you can run outside of your IDE.

Now coming back to your problem, either you need to add POI jar in your CLASSPATH environment variable so that java run-time can access it or build a fat jar including dependencies.

You can use this template to add a build wrapper in pom file to build jar with dependencies.

<build>
    <plugins>
      <plugin>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
          <execution>
            <phase>install</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <outputDirectory>${project.build.directory}/lib</outputDirectory>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>


问:
separators of thousands in angular 2
i have tried this one in my proyect:

```<code><div padding *ngIf="TotalAPagar">
    $ {{TotalAPagar | number }}
</div>
</code>```

my variable is called TotalAPagar, and I'm using number pipe, but it shows the value like this 1,000,500.

I need that to change the numbering convention to dots. Eg. 1.000.000

I have been reading about in the docs in angular but doesn't have any example.

答:
After reading in forums and docs about angular js y javascript i found a method that puts the numbers in format and currency, that method is toLocaleString(), is a method from javascript that helps to put it in the currency or languaje that you need.

i search the name of the country that i need with the method and show me the info that need about. (http://www.localeplanet.com/icu/es-CO/), In my case was colombia.

in my functions i just have to add the .toLocaleString('es-CO') to the result and put the value with the specified currency.

for example:

this.TotalAPagar =
  (this.calcularDescuentosLiquidacion(this.TotalDevengadoValor,
  this.sueldoPendientePorCancelarValor, this.item.libranza,
  this.item.prestamo_empleado)+
  this.calcularIndemnizacion(this.item.promedio_salario,
  this.item.fecha_fin_contrato,
  this.item.fecha_inicio_contrato)).toLocaleString('es-CO');

Title: separators of thousands in angular 2

Body:
i have tried this one in my proyect:

    $ {{TotalAPagar | number }}

my variable is called TotalAPagar, and I'm using number pipe, but it shows the value like this 1,000,500.

I need that to change the numbering convention to dots. Eg. 1.000.000

I have been reading about in the docs in angular but doesn't have any example.


问:
Combining to tables and sorting by latest latest date
I am real beginner to php-mysql and am trying to figure this out.

I have two tables, as shown: a topic table and a conversation table.

I'm trying to merge the tables to:

1) display the titles that belong to a specific category (for example, if category=color, display the titles: 'Color of orange' and 'Color of banana'.)

2) display the date of the last comment made associated with each title (for, example, the latest date for 'Color of orange' is 2009

3) Sort the titles by the latest date - descending

I can manage doing part I, but I'm lost with part 2 and 3. Any help is appreciated.

答:
All you need is a join:</p>

```<code>SELECT `topic`.`title`, `conversation`.`year`
FROM `conversation`
INNER JOIN `topic` on `topic`.`ID` = `conversation`.`topic_id`
</code>```

Body:
All you need is a join:

SELECT `topic`.`title`, `conversation`.`year`
FROM `conversation`
INNER JOIN `topic` on `topic`.`ID` = `conversation`.`topic_id`


问:
CSS animation is not working
Why css animation is not working in my code. When i want to hover my link.</p>

```<code>.floridabt-nav .dropdown-menu>li>a:focus, .dropdown-menu>li>a:hover{
    background-color: transparent;
    color: #f9dd04;
    transition: all 0.3s ease;
}
.floridabt-nav .dropdown-menu>li>a:focus:before, .dropdown-menu>li>a:hover:before{
    content: "\2192";
    color: #222222;
    padding-right: 10px;
    -moz-transition: padding-right .3s ease-in;
    -o-transition: padding-right  .3s ease-in;
    -webkit-transition: padding-right  .3s ease-in;
    transition: padding-right  .3s ease-in;
}
</code>```

答:
Look at the snippet. Now the transition works.

ul was missing in the selector

first css rule need of any declaration of padding

you have to put the transition declaration into the first rule (not under hover or focus)

in the second css rule you have to use padding and not padding-right

in the second css rule you don't need of transition declaration

I hope I was of any help.

.floridabt-nav .dropdown-menu>ul>li>a, .dropdown-menu>ul>li>a{
 background-color: transparent;
 color: #f9dd04;
 -moz-transition: padding 0.3s ease-in;
 -o-transition: padding 0.3s ease-in;
 -webkit-transition: padding 0.3s ease-in;
 transition: padding 0.3s ease-in;
 padding: inherit;
}
.floridabt-nav .dropdown-menu>ul>li>a:focus, .dropdown-menu>ul>li>a:hover{
 color: #222222;
 padding: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="floridabt-nav">
 <div class="dropdown-menu">
  <ul>
   <li>
    PADDING TRANSITION
   </li>
  </ul>
 </div>
</div></code>```

Title: CSS animation is not working

Body:
Why css animation is not working in my code. When i want to hover my link.

.floridabt-nav .dropdown-menu>li>a:focus, .dropdown-menu>li>a:hover{
    background-color: transparent;
    color: #f9dd04;
    transition: all 0.3s ease;
}
.floridabt-nav .dropdown-menu>li>a:focus:before, .dropdown-menu>li>a:hover:before{
    content: "\2192";
    color: #222222;
    padding-right: 10px;
    -moz-transition: padding-right .3s ease-in;
    -o-transition: padding-right  .3s ease-in;
    -webkit-transition: padding-right  .3s ease-in;
    transition: padding-right  .3s ease-in;
}

Body:
Look at the snippet. Now the transition works.

ul was missing in the selector

first css rule need of any declaration of padding

you have to put the transition declaration into the first rule (not under hover or focus)

in the second css rule you have to use padding and not padding-right

in the second css rule you don't need of transition declaration

I hope I was of any help.

.floridabt-nav .dropdown-menu>ul>li>a, .dropdown-menu>ul>li>a{
 background-color: transparent;
 color: #f9dd04;
 -moz-transition: padding 0.3s ease-in;
 -o-transition: padding 0.3s ease-in;
 -webkit-transition: padding 0.3s ease-in;
 transition: padding 0.3s ease-in;
 padding: inherit;
}
.floridabt-nav .dropdown-menu>ul>li>a:focus, .dropdown-menu>ul>li>a:hover{
 color: #222222;
 padding: 10px;
}

<div class="floridabt-nav">
 <div class="dropdown-menu">
  <ul>
   <li>
    <a href="#">PADDING TRANSITION</a>
   </li>
  </ul>
 </div>
</div>


问:
Lua include external resource like: mysql = require "http://myServer.com/luasql.mysql"
Is there a way to use something like this in LUA

```<code>mysql = require "http://myServer.com/luasql.mysql"
</code>```

to get the same result as using

```<code>mysql = require "luasql.mysql"
</code>```

I can't access the webserver, just run lua scripts on it so is this possible in any kind of way?

答:
I would like to explain the situation

When you use

```<code>mysql = require "luasql.mysql"
</code>```

It referering a Driver that allow the connection, It does not have the information of your remote server.

In case your mysql database is remote, you can add host as another optional parameter to connect. Port can follow host as well:

```<code>mysql = require "luasql.mysql"
local env  = mysql.mysql()
local conn = env:connect('test','root','123456','myserver.com','port')
</code>```

luasql.mysql Is only a type of class

Body:
Is there a way to use something like this in LUA

mysql = require "http://myServer.com/luasql.mysql"

to get the same result as using

mysql = require "luasql.mysql"

I can't access the webserver, just run lua scripts on it so is this possible in any kind of way?

Body:
I would like to explain the situation

When you use

mysql = require "luasql.mysql"

It referering a Driver that allow the connection, It does not have the information of your remote server.

In case your mysql database is remote, you can add host as another optional parameter to connect. Port can follow host as well:

mysql = require "luasql.mysql"
local env  = mysql.mysql()
local conn = env:connect('test','root','123456','myserver.com','port')

luasql.mysql Is only a type of class


问:
How I can keep the selected value in the select option after loading the page based on selected value
I couldn't keep the selected value after loading the page, that's why I couldn't take the selected value from the select  option  in Database after done some function..
Here is my code

```<code><select name='courseID' class="mySelect" id='courseID'>
    <?php while ($row1 =mysqli_fetch_array($result1)):;?>
    <option value="<?php echo $row1['CourseID'];?>"><?php echo $row1['CourseID'];?></option><?php endwhile; ?></select>
<script type="text/javascript">document.getElementById('courseID').value="<?php echo $_GET['courseID'];?>";</script>
</code>```

Did JS can add in a HTML in this way??

答:
You have add condition to check if the course id is in the result.</p>

```<code><?php while ($row1 =mysqli_fetch_array($result1)):;
    $selected = ($_GET['courseID'] == $row1['CourseID']) ? 'selected' : '';
    ?>
        <option value="<?php echo $row1['CourseID'];?>" <?php echo $selected;?>><?php echo $row1['CourseID'];?></option>
    <?php endwhile; ?>
</code>```

Body:
I couldn't keep the selected value after loading the page, that's why I couldn't take the selected value from the select  option  in Database after done some function..
Here is my code

<select name='courseID' class="mySelect" id='courseID'>
    <?php while ($row1 =mysqli_fetch_array($result1)):;?>
    <option value="<?php echo $row1['CourseID'];?>"><?php echo $row1['CourseID'];?></option><?php endwhile; ?></select>

Did JS can add in a HTML in this way??

Body:
You have add condition to check if the course id is in the result.

<?php while ($row1 =mysqli_fetch_array($result1)):;
    $selected = ($_GET['courseID'] == $row1['CourseID']) ? 'selected' : '';
    ?>
        <option value="<?php echo $row1['CourseID'];?>" <?php echo $selected;?>><?php echo $row1['CourseID'];?></option>
    <?php endwhile; ?>


问:
How to modify Keras Siamese Network example?
I've tried to change code from Keras example about siamese network. But the weird thing is that the accuracy is always be 0.5000, regardless of the loss decrement. My hypothesis for now is that i was wrongly modify the create_pair function, i wanna try to change the number of classes into 4:

Original:

```<code>def create_pairs(x, digit_indices):
'''Positive and negative pair creation.
Alternates between positive and negative pairs.
'''
pairs = []
labels = []
n = min([len(digit_indices[d]) for d in range(10)]) - 1
for d in range(10):
    for i in range(n):
        z1, z2 = digit_indices[d][i], digit_indices[d][i + 1]
        pairs += [[x[z1], x[z2]]]
        inc = random.randrange(1, 10)
        dn = (d + inc) % 10
        z1, z2 = digit_indices[d][i], digit_indices[dn][i]
        pairs += [[x[z1], x[z2]]]
        labels += [1, 0]
return np.array(pairs), np.array(labels)
</code>```

and, in line 93-97:

```<code>digit_indices = [np.where(y_train == i)[0] for i in range(10)]
tr_pairs, tr_y = create_pairs(x_train, digit_indices)

digit_indices = [np.where(y_test == i)[0] for i in range(10)]
te_pairs, te_y = create_pairs(x_test, digit_indices)
</code>```

This is my code :

```<code>def create_pairs(x, digit_indices):
'''Positive and negative pair creation.
Alternates between positive and negative pairs.
'''
pairs = []
labels = []
n = min([len(digit_indices[d]) for d in range(4)]) - 1
for d in range(4):
    for i in range(n):
        z1, z2 = digit_indices[d][i], digit_indices[d][i + 1]
        pairs += [[x[z1], x[z2]]]
        inc = random.randrange(1, 4)
        dn = (d + inc) % 4
        z1, z2 = digit_indices[d][i], digit_indices[dn][i]
        pairs += [[x[z1], x[z2]]]
        labels += [1, 0]
return np.array(pairs), np.array(labels)
</code>```

and, in line 93-97:

```<code>digit_indices = [np.where(y_train == i)[0] for i in range(4)]
tr_pairs, tr_y = create_pairs(x_train, digit_indices)

digit_indices = [np.where(y_test == i)[0] for i in range(4)]
te_pairs, te_y = create_pairs(x_test, digit_indices)
</code>```

And here's my base_network (the one that use RNN, not the conv net i've talked about in the comment reply, both give the same result, 50% of accuracy):

```<code>def create_base_network(embedding_layer):
    seq = Sequential()
    seq.add(embedding_layer)
    seq.add(GRU(512, use_bias=True, dropout=0.5, recurrent_dropout=0.5, return_sequences=True))
    seq.add(GRU(512, use_bias=True, dropout=0.5, recurrent_dropout=0.5))
    seq.add(Dense(512, activation='relu'))
    seq.add(Dropout(0.1))
    seq.add(Dense(512, activation='relu'))
    return seq
</code>```

The embedding layer is just a simple glove matrix. And i also add another dense layer using sigmoid activation function after the merging.

Anything missing? Or that is not how i should change it? Thanks in advance

答:
The Siamese code is wrong and not yet fixed. The problem is the loss function that is not symmetric in switching 0 and 1, but the keras code assume that it is.
Change this line

```<code>return K.mean(y_true * K.square(y_pred) + (1 - y_true) * K.square(K.maximum(margin - y_pred, 0)))
</code>```

into

```<code>return K.mean((1 - y_true) * K.square(y_pred) + y_true * K.square(K.maximum(margin - y_pred, 0)))
</code>```

and

```<code>labels += [1, 0]
</code>```

into

```<code>labels += [0, 1]
</code>```

Body:
I've tried to change code from Keras example about siamese network. But the weird thing is that the accuracy is always be 0.5000, regardless of the loss decrement. My hypothesis for now is that i was wrongly modify the create_pair function, i wanna try to change the number of classes into 4:

Original:

def create_pairs(x, digit_indices):
'''Positive and negative pair creation.
Alternates between positive and negative pairs.
'''
pairs = []
labels = []
n = min([len(digit_indices[d]) for d in range(10)]) - 1
for d in range(10):
    for i in range(n):
        z1, z2 = digit_indices[d][i], digit_indices[d][i + 1]
        pairs += [[x[z1], x[z2]]]
        inc = random.randrange(1, 10)
        dn = (d + inc) % 10
        z1, z2 = digit_indices[d][i], digit_indices[dn][i]
        pairs += [[x[z1], x[z2]]]
        labels += [1, 0]
return np.array(pairs), np.array(labels)

and, in line 93-97:

digit_indices = [np.where(y_train == i)[0] for i in range(10)]
tr_pairs, tr_y = create_pairs(x_train, digit_indices)

digit_indices = [np.where(y_test == i)[0] for i in range(10)]
te_pairs, te_y = create_pairs(x_test, digit_indices)

This is my code :

def create_pairs(x, digit_indices):
'''Positive and negative pair creation.
Alternates between positive and negative pairs.
'''
pairs = []
labels = []
n = min([len(digit_indices[d]) for d in range(4)]) - 1
for d in range(4):
    for i in range(n):
        z1, z2 = digit_indices[d][i], digit_indices[d][i + 1]
        pairs += [[x[z1], x[z2]]]
        inc = random.randrange(1, 4)
        dn = (d + inc) % 4
        z1, z2 = digit_indices[d][i], digit_indices[dn][i]
        pairs += [[x[z1], x[z2]]]
        labels += [1, 0]
return np.array(pairs), np.array(labels)

and, in line 93-97:

digit_indices = [np.where(y_train == i)[0] for i in range(4)]
tr_pairs, tr_y = create_pairs(x_train, digit_indices)

digit_indices = [np.where(y_test == i)[0] for i in range(4)]
te_pairs, te_y = create_pairs(x_test, digit_indices)

And here's my base_network (the one that use RNN, not the conv net i've talked about in the comment reply, both give the same result, 50% of accuracy):

def create_base_network(embedding_layer):
    seq = Sequential()
    seq.add(embedding_layer)
    seq.add(GRU(512, use_bias=True, dropout=0.5, recurrent_dropout=0.5, return_sequences=True))
    seq.add(GRU(512, use_bias=True, dropout=0.5, recurrent_dropout=0.5))
    seq.add(Dense(512, activation='relu'))
    seq.add(Dropout(0.1))
    seq.add(Dense(512, activation='relu'))
    return seq

The embedding layer is just a simple glove matrix. And i also add another dense layer using sigmoid activation function after the merging.

Anything missing? Or that is not how i should change it? Thanks in advance

Body:
The Siamese code is wrong and not yet fixed. The problem is the loss function that is not symmetric in switching 0 and 1, but the keras code assume that it is.
Change this line

return K.mean(y_true * K.square(y_pred) + (1 - y_true) * K.square(K.maximum(margin - y_pred, 0)))

into

return K.mean((1 - y_true) * K.square(y_pred) + y_true * K.square(K.maximum(margin - y_pred, 0)))

and

labels += [1, 0]

into

labels += [0, 1]


问:
Go directly to fragment in Navigation Drawer Android
I have a navigation drawer activity with fragments in it. Now how can I make the app to go directly to a fragment when that activity is opened? I don't want to show the content_main.xml (which is blank):

答:
You have some options.

1) Open activity_main.xml

And replace a line that includes layout=content_main with the layout that you actually want instead.

2) Just load the Fragment in onCreate like you would when you do click on the Navigation Drawer.


问:
how to show objects in TableColumn
Hey everyone am trying to display an attribute of an object inside an another to make it more clear i have a class Produit defined like this :

```<code>public class Produit {
private int idproduit;
private float prixunitaire;
private String designation;
private String description;
private boolean etatp;
private Bondereduction bondereductions;
private String lienimg;
private Categorie categories;
</code>```

}

With it getters and setters and ....

and am trying to display these data inside a TableView i use to make it like this

```<code>public class UpdateProdController implements Initializable {

@FXML
private TableColumn prixunitaire;
@FXML
private TableColumn description;
@FXML
private TableColumn designation;
@FXML
private TableColumn<Categorie,String> categorie;
@FXML
private TableColumn<Bondereduction, String> sommereduction;
@FXML
private TableColumn img;

ObservableList<Produit> prodList = FXCollections.observableArrayList();
@FXML
private TableView<Produit> updatetable;
String xx="";
/**
 * Initializes the controller class.
 */
@Override
public void initialize(URL url, ResourceBundle rb) {

  ProduitService pss = new ProduitService();
    prodList = pss.SelectProduits();
    //String des =prodList.get(0).getCategories().getDesignation().;
    System.out.println("sqsdqsdqsd   " + prodList);

    updatetable.setItems(prodList);
    prixunitaire.setCellValueFactory(new PropertyValueFactory<>("prixunitaire"));
    description.setCellValueFactory(new PropertyValueFactory<>("description"));
    designation.setCellValueFactory(new PropertyValueFactory<>("designation"));
   sommereduction.setCellValueFactory(new PropertyValueFactory<>("Bondereduction.sommereduction"));
   categorie.setCellValueFactory(new PropertyValueFactory<>("Categorie.designation"));

    img.setCellValueFactory(new PropertyValueFactory<>("lienimg"));
}
</code>```

when i execute this code i get only categorie and sommereduction TableColumn empty and the problem is in these 2 lines

```<code>   sommereduction.setCellValueFactory(new PropertyValueFactory<>("Bondereduction.sommereduction"));
   categorie.setCellValueFactory(new PropertyValueFactory<>("Categorie.designation"));
</code>```

can anyone help me how to change PropertyValueFactory<> to get an object and not string so it would understand that am trying to display a field inside an object. Thanks to any help.

答:
You will have to go a little further in depth with your PropertyValueFactory<> something like this:

```<code>sommereduction.setCellValueFactory(
        Produit -> {
            SimpleObjectProperty property = new SimpleObjectProperty();
            property.setValue(Produit.getValue().getBondereduction().getSommereduction()));
            return property;
        }
);
</code>```

This should do what you need. It is basically what you did, except it took it a step further.

It creates a new SimpleObjectProperty and then uses the Produit class to grab the Bondereduction and it uses that value to return the sommereduction.

I also suggest changing the

```<code>@FXML
private TableColumn<Categorie,String> categorie;
@FXML
private TableColumn<Bondereduction, String> sommereduction;
</code>```

to be

```<code>@FXML
private TableColumn<Produit,String> categorie;
@FXML
private TableColumn<Produit, String> sommereduction;
</code>```

Since that is the class you are attempting to display.

Title: how to show objects in TableColumn

Body:
Hey everyone am trying to display an attribute of an object inside an another to make it more clear i have a class Produit defined like this :

public class Produit {
private int idproduit;
private float prixunitaire;
private String designation;
private String description;
private boolean etatp;
private Bondereduction bondereductions;
private String lienimg;
private Categorie categories;

}

With it getters and setters and ....

and am trying to display these data inside a TableView i use to make it like this

public class UpdateProdController implements Initializable {

@FXML
private TableColumn prixunitaire;
@FXML
private TableColumn description;
@FXML
private TableColumn designation;
@FXML
private TableColumn<Categorie,String> categorie;
@FXML
private TableColumn<Bondereduction, String> sommereduction;
@FXML
private TableColumn img;

ObservableList<Produit> prodList = FXCollections.observableArrayList();
@FXML
private TableView<Produit> updatetable;
String xx="";
/**
 * Initializes the controller class.
 */
@Override
public void initialize(URL url, ResourceBundle rb) {

  ProduitService pss = new ProduitService();
    prodList = pss.SelectProduits();
    //String des =prodList.get(0).getCategories().getDesignation().;
    System.out.println("sqsdqsdqsd   " + prodList);

    updatetable.setItems(prodList);
    prixunitaire.setCellValueFactory(new PropertyValueFactory<>("prixunitaire"));
    description.setCellValueFactory(new PropertyValueFactory<>("description"));
    designation.setCellValueFactory(new PropertyValueFactory<>("designation"));
   sommereduction.setCellValueFactory(new PropertyValueFactory<>("Bondereduction.sommereduction"));
   categorie.setCellValueFactory(new PropertyValueFactory<>("Categorie.designation"));

    img.setCellValueFactory(new PropertyValueFactory<>("lienimg"));
}

when i execute this code i get only categorie and sommereduction TableColumn empty and the problem is in these 2 lines

   sommereduction.setCellValueFactory(new PropertyValueFactory<>("Bondereduction.sommereduction"));
   categorie.setCellValueFactory(new PropertyValueFactory<>("Categorie.designation"));

can anyone help me how to change PropertyValueFactory<> to get an object and not string so it would understand that am trying to display a field inside an object. Thanks to any help.

Body:
You will have to go a little further in depth with your PropertyValueFactory<> something like this:

sommereduction.setCellValueFactory(
        Produit -> {
            SimpleObjectProperty property = new SimpleObjectProperty();
            property.setValue(Produit.getValue().getBondereduction().getSommereduction()));
            return property;
        }
);

This should do what you need. It is basically what you did, except it took it a step further.

It creates a new SimpleObjectProperty and then uses the Produit class to grab the Bondereduction and it uses that value to return the sommereduction.

I also suggest changing the

@FXML
private TableColumn<Categorie,String> categorie;
@FXML
private TableColumn<Bondereduction, String> sommereduction;

to be

@FXML
private TableColumn<Produit,String> categorie;
@FXML
private TableColumn<Produit, String> sommereduction;

Since that is the class you are attempting to display.


答:
Maven package task just packs compiled classes of your project into a single jar file. All 3rd party libraries are not included, that's why you're getting error - POI class is not found.

You should build a runnable jar file that includes all dependencies. Please, refer to this question - you should use some additional maven plugins to achieve that

Title: Running .jar file using Apache POI in Maven project


问:
How to remove columns of data from a data frame using a vector with a regular expression
I am trying to remove columns from a dataframe using a vector of numbers, with those numbers being just a part of the whole column header. What I'm looking to use is something like the wildcard "*" in unix, so that I can say that I want to remove columns with labels xxxx, xxkx, etc... To illustrate what I mean, if I have the following data:

```<code>data_test_read <- read.table("batch_1_8c9.structure-edit.tsv",sep="\t", header=TRUE)
data_test_read[1:5,1:5]
samp pop X12706_10 X14223_16 X14481_7
1 BayOfIslands_s088.fq   1         4         1        3
2 BayOfIslands_s088.fq   1         4         1        3
3 BayOfIslands_s089.fq   1         4         1        3
4 BayOfIslands_s089.fq   1         4         3        3
5 BayOfIslands_s090.fq   1         4         1        3
</code>```

And I want to take out, for example, columns with headers (X12706_10, X14481_7), the following works

```<code>data_subs1=subset(data_test_read, select = -c(X12706_10, X14481_7))
data_subs1[1:4,1:4]
samp pop X14223_16 X15213_19
1 BayOfIslands_s088.fq   1         1         3
2 BayOfIslands_s088.fq   1         1         3
3 BayOfIslands_s089.fq   1         1         3
4 BayOfIslands_s089.fq   1         3         3
</code>```

However, what I need is to be able to identify these columns by only the numbers, so, using (12706,14481). But, if I try this, I get the following

```<code>data_subs2=subset(data_test_read, select = -c(12706,14481))
data_subs2[1:4,1:4]
samp pop X12706_10 X14223_16
1 BayOfIslands_s088.fq   1         4         1
2 BayOfIslands_s088.fq   1         4         1
3 BayOfIslands_s089.fq   1         4         1
4 BayOfIslands_s089.fq   1         4         3
</code>```

This is clearly because I haven't specified anything to do with the "x", or the "_" or what is after the underscore. I've read so many answers on using regular expressions, and I just can't seem to sort it out. Any thoughts, or pointers to what I might turn to would be appreciated.

答:
First you can just extract the numbers from the headers

```<code># for testing
col_names <- c("X12706_10","X14223_16","X14481_7")
# in practice, use
# col_names <- names(data_test_read)
samples <- gsub("X(\\d+)_.*","\\1",col_names)
</code>```

The find the indexes of the samples you want to drop.

```<code>samples_to_drop  <- c(12706, 14481)
cols_to_drop <- match(samples_to_drop, samples)
</code>```

Then you can use

```<code>data_subs2 <- subset(data_test_read, select = -cols_to_drop)
</code>```

to actually get rid of those columns.

Perhaps put this all in a function to make it easier to use

```<code>sample_subset <- function(x, drop) {
    samples <- gsub("X(\\d+)_.*","\\1", names(x))
    subset(x, select = -match(drop, samples))
}
sample_subset(data_test_read, c(12706, 14481))
</code>```

Body:
I am trying to remove columns from a dataframe using a vector of numbers, with those numbers being just a part of the whole column header. What I'm looking to use is something like the wildcard "*" in unix, so that I can say that I want to remove columns with labels xxxx, xxkx, etc... To illustrate what I mean, if I have the following data:

data_test_read <- read.table("batch_1_8c9.structure-edit.tsv",sep="\t", header=TRUE)
data_test_read[1:5,1:5]
samp pop X12706_10 X14223_16 X14481_7
1 BayOfIslands_s088.fq   1         4         1        3
2 BayOfIslands_s088.fq   1         4         1        3
3 BayOfIslands_s089.fq   1         4         1        3
4 BayOfIslands_s089.fq   1         4         3        3
5 BayOfIslands_s090.fq   1         4         1        3

And I want to take out, for example, columns with headers (X12706_10, X14481_7), the following works

data_subs1=subset(data_test_read, select = -c(X12706_10, X14481_7))
data_subs1[1:4,1:4]
samp pop X14223_16 X15213_19
1 BayOfIslands_s088.fq   1         1         3
2 BayOfIslands_s088.fq   1         1         3
3 BayOfIslands_s089.fq   1         1         3
4 BayOfIslands_s089.fq   1         3         3

However, what I need is to be able to identify these columns by only the numbers, so, using (12706,14481). But, if I try this, I get the following

data_subs2=subset(data_test_read, select = -c(12706,14481))
data_subs2[1:4,1:4]
samp pop X12706_10 X14223_16
1 BayOfIslands_s088.fq   1         4         1
2 BayOfIslands_s088.fq   1         4         1
3 BayOfIslands_s089.fq   1         4         1
4 BayOfIslands_s089.fq   1         4         3

This is clearly because I haven't specified anything to do with the "x", or the "_" or what is after the underscore. I've read so many answers on using regular expressions, and I just can't seem to sort it out. Any thoughts, or pointers to what I might turn to would be appreciated.

Body:
First you can just extract the numbers from the headers

# for testing
col_names <- c("X12706_10","X14223_16","X14481_7")
# in practice, use
# col_names <- names(data_test_read)
samples <- gsub("X(\\d+)_.*","\\1",col_names)

The find the indexes of the samples you want to drop.

samples_to_drop  <- c(12706, 14481)
cols_to_drop <- match(samples_to_drop, samples)

Then you can use

data_subs2 <- subset(data_test_read, select = -cols_to_drop)

to actually get rid of those columns.

Perhaps put this all in a function to make it easier to use

sample_subset <- function(x, drop) {
    samples <- gsub("X(\\d+)_.*","\\1", names(x))
    subset(x, select = -match(drop, samples))
}
sample_subset(data_test_read, c(12706, 14481))


问:
populate html table with PHP via ajax in the same file
I'm using PHP to populate an HTML table with random numbers on page load. When button is clicked, I want to re-populate the table with new numbers by calling PHP via an ajax request. Problem is I can't use (or at least really want to avoid using) external files : PHP must be called via ajax request in the same file.

File is index.php and contains following simplified PHP code :

```<code><?php
    //code to be executed via ajax call should be placed here ?
?>
<!DOCTYPE html>

<HTML>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width">
<HEAD>
    <title>PHP test</title>
</HEAD>

<BODY>
  <table id="table">
    <?php //problem : only works once in page load
      $howMany = 10;

      $values = array();

      echo '<tr>';
      for ($v = 0; $v < $howMany; $v++) {
        $values[$v] = mt_rand(-10, 10);
        echo '<td>'. $values[$v] .'</td>';
      }
      echo '</tr>';
   ?>
  </table>

  <button id="btn">Generate new numbers</button>
<BODY>
</code>```

Here is my current ajax request :

```<code><script type="text/javascript">
function send_ajax() {
  console.log('btn clicked');
  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest(); //code for IE7+, Firefox, Chrome, Opera, Safari
  }
  else {
    xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); //code for IE6, IE5
  }
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log('data sent');
    }
  }
  xmlhttp.open('POST', 'index.php', true);
  //xmlhttp.send(document.getElementById('input').value);
}

document.getElementById('btn').addEventListener('click', send_ajax, false);
</script>
</code>```

I'm sure I'm missing something obvious, but I have no idea how I should adapt my php code and ajax request to repopulate the table when receiving ajax call in the same file.

(Note : I know it would be very easy using external files, but this scenario is a typical example of what I need to do with ajax and PHP for more complex tasks over dozens of different files).

答:
How about something like this ...

```<code><?php
    if($_GET['load']) {

          $howMany = 10;

          $values = array();

          echo '<tr>';
          for ($v = 0; $v < $howMany; $v++) {
            $values[$v] = mt_rand(-10, 10);
            echo '<td>'. $values[$v] .'</td>';
          }
          echo '</tr>';

    } else {
?>
<!DOCTYPE html>

<HTML>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width">
<HEAD>
    <title>PHP test</title>
</HEAD>

<BODY>
  <table id="table">
    <?php //problem : only works once in page load
      $howMany = 10;

      $values = array();

      echo '<tr>';
      for ($v = 0; $v < $howMany; $v++) {
        $values[$v] = mt_rand(-10, 10);
        echo '<td>'. $values[$v] .'</td>';
      }
      echo '</tr>';
   ?>
  </table>

  <button id="btn">Generate new numbers</button>
</BODY>
<?php } ?>
</code>```

And then ...

```<code>xmlhttp.open('GET', 'index.php?load=1', true);
</code>```

This could definitely be improved but the concept I've outlined is how I would approach your challenge.

Body:
I'm using PHP to populate an HTML table with random numbers on page load. When button is clicked, I want to re-populate the table with new numbers by calling PHP via an ajax request. Problem is I can't use (or at least really want to avoid using) external files : PHP must be called via ajax request in the same file.

File is index.php and contains following simplified PHP code :

<?php
    //code to be executed via ajax call should be placed here ?
?>
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width">

    <title>PHP test</title>

    <?php //problem : only works once in page load
      $howMany = 10;

      $values = array();

      echo '
';
      for ($v = 0; $v < $howMany; $v++) {
        $values[$v] = mt_rand(-10, 10);
        echo ''. $values[$v] .'	';
      }
      echo '
';
   ?>

  <button id="btn">Generate new numbers</button>

Here is my current ajax request :

I'm sure I'm missing something obvious, but I have no idea how I should adapt my php code and ajax request to repopulate the table when receiving ajax call in the same file.

(Note : I know it would be very easy using external files, but this scenario is a typical example of what I need to do with ajax and PHP for more complex tasks over dozens of different files).

Body:
How about something like this ...

<?php
    if($_GET['load']) {

          $howMany = 10;

          $values = array();

          echo '<tr>';
          for ($v = 0; $v < $howMany; $v++) {
            $values[$v] = mt_rand(-10, 10);
            echo '<td>'. $values[$v] .'</td>';
          }
          echo '</tr>';

    } else {
?>
<!DOCTYPE html>

<HTML>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width">
<HEAD>
    <title>PHP test</title>
</HEAD>

<BODY>
  <table id="table">
    <?php //problem : only works once in page load
      $howMany = 10;

      $values = array();

      echo '<tr>';
      for ($v = 0; $v < $howMany; $v++) {
        $values[$v] = mt_rand(-10, 10);
        echo '<td>'. $values[$v] .'</td>';
      }
      echo '</tr>';
   ?>
  </table>

  <button id="btn">Generate new numbers</button>
</BODY>
<?php } ?>

And then ...

xmlhttp.open('GET', 'index.php?load=1', true);

This could definitely be improved but the concept I've outlined is how I would approach your challenge.


问:
How to use substring when using powershell select-object
I'm wondering if there is a way to use do a substring when using powershell's select-object cmdlet

Here is an example of what i'm trying to do

```<code>$sapFile = "C:\MyFile*.XML"

# Get the newest xml file
$newestFile = Get-ChildItem -Path $sapFile | Sort CreationTime | Select -Last 1

# get the contents of the xml file
[XML]$sapContent = Get-Content -Path $newestFile.FullName

$sapContent.DATA.CP | Select -Property CP_NO,MEN.Substring(0,4)
</code>```

This however doesn't work.

Thanks

答:
You can create a property on the fly using Select that has a calculated value by using a hashtable. In the following example I select the 'CP_NO' property, and create the 'MENSubString' property with a hashtable.

```<code>Select -Property CP_NO,@{label='MENSubString';expression={$_.MEN.Substring(0,4)}}
</code>```

Label can be shortened to just 'l' and Expression can be shortened to just 'e', which would look like:

```<code>Select -Property CP_NO,@{l='MENSubString';e={$_.MEN.Substring(0,4)}}
</code>```

Body:
I'm wondering if there is a way to use do a substring when using powershell's select-object cmdlet

Here is an example of what i'm trying to do

$sapFile = "C:\MyFile*.XML"

# Get the newest xml file
$newestFile = Get-ChildItem -Path $sapFile | Sort CreationTime | Select -Last 1

# get the contents of the xml file
[XML]$sapContent = Get-Content -Path $newestFile.FullName

$sapContent.DATA.CP | Select -Property CP_NO,MEN.Substring(0,4)

This however doesn't work.

Thanks

Body:
You can create a property on the fly using Select that has a calculated value by using a hashtable. In the following example I select the 'CP_NO' property, and create the 'MENSubString' property with a hashtable.

Select -Property CP_NO,@{label='MENSubString';expression={$_.MEN.Substring(0,4)}}

Label can be shortened to just 'l' and Expression can be shortened to just 'e', which would look like:

Select -Property CP_NO,@{l='MENSubString';e={$_.MEN.Substring(0,4)}}


答:
go to Activity onCreate method  and  put this </p>

```<code> FragmentManager fm =getFragmentManager();
 FragmentTransaction ft= fm.beginTransaction();
 // the Second paramter is Object from your Fragment that you want to add it
ft.replace(R.id.activity_main ,fragmentObject  );
ft.commit();
</code>```

Title: Go directly to fragment in Navigation Drawer Android

Body: I have a navigation drawer activity with fragments in it. Now how can I make the app to go directly to a fragment when that activity is opened? I don't want to show the content_main.xml (which is blank):

Body:
go to Activity onCreate method  and  put this

 FragmentManager fm =getFragmentManager();
 FragmentTransaction ft= fm.beginTransaction();
 // the Second paramter is Object from your Fragment that you want to add it
ft.replace(R.id.activity_main ,fragmentObject  );
ft.commit();


问:
All embeded components in Tapestry
I'm using Tapestry 5.3.8. I wanted to find a method that will tell me if there is some specific element in given container or not. I have found something like this:

```<code>containerResources.getEmbeddedComponent(elementId)
</code>```

But problem with this method is that when there is not, it throws exception. I could not see any other method regarding this.

Question: is there any other method to check if some element is inside given container OR is there any method that e.q. list all avaible componenets in given container?

Title: All embeded components in Tapestry

Body:
I'm using Tapestry 5.3.8. I wanted to find a method that will tell me if there is some specific element in given container or not. I have found something like this:

containerResources.getEmbeddedComponent(elementId)

But problem with this method is that when there is not, it throws exception. I could not see any other method regarding this.

Question: is there any other method to check if some element is inside given container OR is there any method that e.q. list all avaible componenets in given container?

Body: How about ComponentResources#getComponentModel()#getEmbeddedComponentIds()?


问:
Weird UINavigationController behavior
I am having a bit of trouble with my navigationController in my app. I am using the Kal Calendar component - https://github.com/klazuka/Kal.

I have created the view controller and have go it to appear in the correct position within in my app i.e. Click on a new tab and init the rootviewcontroller as the KalViewController and it sort of loads correctly but the back button is visible on the navBar when it should be the rootView and it is clickable 5 times before going to the true root, it's hard to explain but I have no idea what is wrong.

i have tried it with a table view and clicking on the first element in the tableView takes you to the calendar which works perfectly but this is not what I want/need in the app.

Thanks.

答: It sounds like you have both a UINavigationController and a UITabBarController. Make sure that the tab bar controller is your “main” view and that there are separate UINavigationControllers for each view controller in the tab bar. The different tabs’ view controllers should not be in the same navigation controller’s view heirarchy.

Title: Weird UINavigationController behavior


问:
Swift Binary Search Tree Search
I am trying to implement a BST that stores a list of words. I know that my tree structure is correct because when I try to traverse and print in order, the list prints alphabetically. However, my search function for looking for an element in a tree returns false each time.

```<code>func search(searchValue: String) -> Bool? {
    if searchValue == value as! String{
        return true
    }

    if searchValue < value as! String {
        return left?.search(searchValue: searchValue)
    }
    if searchValue > value as! String{
        return right?.search(searchValue: searchValue)
    }

    return false

}
</code>```

The function is called in this loop. Every word not in the BST should be appended to an array misspelled. Currently no words are appended to the array. Input array is an array of all the words to be checked against the BST.

```<code> for item in arrayInput
        {
            let target = item.lowercased()//reversed
            let inTree = tree.search(searchValue: target)
            if inTree == false
            {
                misspelled.append(item)
            }
        }
</code>```

More BST class for context:

```<code>  public class BinarySearchTree<T: Comparable> {
        fileprivate(set) public var value: T
        fileprivate(set) public var parent: BinarySearchTree?
        fileprivate(set) public var left: BinarySearchTree?
        fileprivate(set) public var right: BinarySearchTree?

        public init(value: T) {
            self.value = value
        }

        public convenience init(array: [T]) {
            precondition(array.count > 0)
            self.init(value: array.first!)
            for v in array.dropFirst() {
                insert(value: v)
            }
        }

        }
     public func insert(value: T) {
            if value < self.value {
                if let left = left {
                    left.insert(value: value)
                } else {
                    left = BinarySearchTree(value: value)
                    left?.parent = self
                }
            } else {
                if let right = right {
                    right.insert(value: value)
                } else {
                    right = BinarySearchTree(value: value)
                    right?.parent = self
                }
            }
        }
</code>```

答:
I believe the issue is that you are reaching the leaf node of your binary search tree and then returning nil. The misspelled word is either less than or greater than the stored value of the leaf, so you are looking for the left or right child and those values are nil so the function is returning nil. </p>

<p>There are several ways you could go about fixing this, but the simplest change would be to nil coalesce to false when the left or right is nil.  </p>

```<code>func search(searchValue: String) -> Bool {
    if searchValue == value as! String {
        return true
    }

    if searchValue < value as! String {
        return left?.search(searchValue: searchValue) ?? false
    }
    if searchValue > value as! String {
        return right?.search(searchValue: searchValue) ?? false
    }

    return false
}
</code>```

Title: Swift Binary Search Tree Search

Body:
I am trying to implement a BST that stores a list of words. I know that my tree structure is correct because when I try to traverse and print in order, the list prints alphabetically. However, my search function for looking for an element in a tree returns false each time.

func search(searchValue: String) -> Bool? {
    if searchValue == value as! String{
        return true
    }

    if searchValue < value as! String {
        return left?.search(searchValue: searchValue)
    }
    if searchValue > value as! String{
        return right?.search(searchValue: searchValue)
    }

    return false

}

The function is called in this loop. Every word not in the BST should be appended to an array misspelled. Currently no words are appended to the array. Input array is an array of all the words to be checked against the BST.

 for item in arrayInput
        {
            let target = item.lowercased()//reversed
            let inTree = tree.search(searchValue: target)
            if inTree == false
            {
                misspelled.append(item)
            }
        }

More BST class for context:

  public class BinarySearchTree<T: Comparable> {
        fileprivate(set) public var value: T
        fileprivate(set) public var parent: BinarySearchTree?
        fileprivate(set) public var left: BinarySearchTree?
        fileprivate(set) public var right: BinarySearchTree?

        public init(value: T) {
            self.value = value
        }

        public convenience init(array: [T]) {
            precondition(array.count > 0)
            self.init(value: array.first!)
            for v in array.dropFirst() {
                insert(value: v)
            }
        }

        }
     public func insert(value: T) {
            if value < self.value {
                if let left = left {
                    left.insert(value: value)
                } else {
                    left = BinarySearchTree(value: value)
                    left?.parent = self
                }
            } else {
                if let right = right {
                    right.insert(value: value)
                } else {
                    right = BinarySearchTree(value: value)
                    right?.parent = self
                }
            }
        }

Body:
I believe the issue is that you are reaching the leaf node of your binary search tree and then returning nil. The misspelled word is either less than or greater than the stored value of the leaf, so you are looking for the left or right child and those values are nil so the function is returning nil.

There are several ways you could go about fixing this, but the simplest change would be to nil coalesce to false when the left or right is nil.

func search(searchValue: String) -> Bool {
    if searchValue == value as! String {
        return true
    }

    if searchValue < value as! String {
        return left?.search(searchValue: searchValue) ?? false
    }
    if searchValue > value as! String {
        return right?.search(searchValue: searchValue) ?? false
    }

    return false
}


问:
How to get read external storage permissions?
I'm developing an mp3 player application for android and I'm getting an error related to user permissions(READ_EXTERNAL_STORAGE)

This is my code where I ask for permissions:

```<code>int permissionCheck = ContextCompat.checkSelfPermission(PlayListActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE);

        if (ContextCompat.checkSelfPermission(PlayListActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            // OPCIONAL(explicaciones de poque pedimos los permisos)
            if (ActivityCompat.shouldShowRequestPermissionRationale(PlayListActivity.this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {

            } else {
                //pedir permisos
                ActivityCompat.requestPermissions(PlayListActivity.this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        permissionCheck);
</code>```

and this is the rest of the code:

```<code>ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();

    SongsManager plm = new SongsManager(PlayListActivity.this);
    // get all songs from sdcard
    this.songsList = plm.getPlayList();

    // looping through playlist
    for (int i = 0; i < songsList.size(); i++) {
        // creating new HashMap
        HashMap<String, String> song = songsList.get(i);

        // adding HashList to ArrayList
        songsListData.add(song);
    }

    // se añaden las canciones a la ListView mediante un adapter utilizando el layout playlist_item
    ListAdapter adapter = new SimpleAdapter(this, songsListData,
            R.layout.playlist_item, new String[] { "songTitle" }, new int[] {
            R.id.songTitle });

    setListAdapter(adapter);
</code>```

this is the error:

```<code>03-31 22:09:16.159 2258-2258/com.androidchatapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.androidchatapp, PID: 2258
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidchatapp/com.androidchatapp.PlayListActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=2258, uid=10184 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2434)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:153)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5451)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=2258, uid=10184 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
    at android.os.Parcel.readException(Parcel.java:1620)
    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
    at android.content.ContentProviderProxy.query(ContentProviderNative.java:421)
    at android.content.ContentResolver.query(ContentResolver.java:493)
    at android.content.ContentResolver.query(ContentResolver.java:435)
    at com.androidchatapp.SongsManager.getPlayList(SongsManager.java:48)
    at com.androidchatapp.PlayListActivity.onCreate(PlayListActivity.java:65)
    at android.app.Activity.performCreate(Activity.java:6323)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2387)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:153)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5451)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
You have asked the permission from the code , but you are probably forgetting to add this permission tag in the manifest file</p>

```<code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
</code>```

Body:
I'm developing an mp3 player application for android and I'm getting an error related to user permissions(READ_EXTERNAL_STORAGE)

This is my code where I ask for permissions:

int permissionCheck = ContextCompat.checkSelfPermission(PlayListActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE);

        if (ContextCompat.checkSelfPermission(PlayListActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            // OPCIONAL(explicaciones de poque pedimos los permisos)
            if (ActivityCompat.shouldShowRequestPermissionRationale(PlayListActivity.this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {

            } else {
                //pedir permisos
                ActivityCompat.requestPermissions(PlayListActivity.this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        permissionCheck);

and this is the rest of the code:

ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();

    SongsManager plm = new SongsManager(PlayListActivity.this);
    // get all songs from sdcard
    this.songsList = plm.getPlayList();

    // looping through playlist
    for (int i = 0; i < songsList.size(); i++) {
        // creating new HashMap
        HashMap<String, String> song = songsList.get(i);

        // adding HashList to ArrayList
        songsListData.add(song);
    }

    // se añaden las canciones a la ListView mediante un adapter utilizando el layout playlist_item
    ListAdapter adapter = new SimpleAdapter(this, songsListData,
            R.layout.playlist_item, new String[] { "songTitle" }, new int[] {
            R.id.songTitle });

    setListAdapter(adapter);

this is the error:

03-31 22:09:16.159 2258-2258/com.androidchatapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.androidchatapp, PID: 2258
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidchatapp/com.androidchatapp.PlayListActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=2258, uid=10184 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2434)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:153)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5451)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=2258, uid=10184 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
    at android.os.Parcel.readException(Parcel.java:1620)
    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
    at android.content.ContentProviderProxy.query(ContentProviderNative.java:421)
    at android.content.ContentResolver.query(ContentResolver.java:493)
    at android.content.ContentResolver.query(ContentResolver.java:435)
    at com.androidchatapp.SongsManager.getPlayList(SongsManager.java:48)
    at com.androidchatapp.PlayListActivity.onCreate(PlayListActivity.java:65)
    at android.app.Activity.performCreate(Activity.java:6323)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2387)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:153)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5451)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
You have asked the permission from the code , but you are probably forgetting to add this permission tag in the manifest file

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>