text:
Q: dom-if can't use a function as the "if" value in firefox code like the below works fine in chrome but in firefox I get the following error when using polymer 1.9.1
[undefined::_annotatedComputationEffect]: compute method hasMoreData not defined
<template>

    <template is="dom-repeat" items="[[sections]]">

            <template is="dom-if" if="{{hasMoreData(item)}}">

load more

            </template>

    </template>
</template>

this is really frustrating that something basic doesn't seem to work the way the documentation says in a particular modern browser and works fine in another. :( stuff like this makes me nervous about using polymer in production. I have faced other cross-browser issues but worked around them, but this time I think the framework has finally pushed me over the edge :)

A: so what I ended up having to do was move the conditional "load more" to its own component like so
<load-more section="[[item]]"></load-more>

and then use dom-if in the component like this
<dom-module id="load-more">
    <template>
        <template is="dom-if" if="[[hasMoreData(section)]]">
            load more
        </template>
    </template>
</dom-module>

why should I have to do this? why does it work the simpler way in chrome and not firefox?
who knows, but I've had too many of these kind of weird issues with polymer for it to be a coincidence.
sorry, google, I really wanted to like Polymer but I am starting to regret choosing it. everything has a learning curve but too many things work fine in one browser, completely fail in another, or have weird corner cases you trigger by just trying to use the framework as shown in the documentation, some of which is incorrect or out of date.
I think web components have heaps of potential, but Polymer, at least the version I am using, is not a good advertisement for web components.
unfortunately, this diagram about angular might as well apply to polymer too, and I have to agree with this guy's feelings about polymer.

I will try to make it work for my current project as I have probably gone too far down this rabbit hole to change my choice of technology now, but if things keep going the way they have been, I have a feeling I will avoid polymer wherever possible.


text:
Q: Get list of channels with Telegram TL I need a list of all channels that user has already joined. I found the below function:
channels.getChannels#0a7f6bbb id:Vector<InputChannel> = messages.Chats

But I couldn't understand "id: Vector<InputChannel>". If it's ID of a channel, is that mean it only return information of a single channel?! On the other hand, its return type is "messages.Chats". I really don't get it.

A: With messages.Dialogs we will have all dialog (Groups, Channel, and Users):
messages.getDialogs#191ba9c5 exclude_pinned:true offset_date:int offset_id:int offset_peer:InputPeer limit:int = messages.Dialogs;

This will return messages.dialogsSlice object:
messages.dialogsSlice#71e094f3 count:int dialogs:Vector<Dialog> messages:Vector<Message> chats:Vector<Chat> users:Vector<User> = messages.Dialogs;

Here "chats" is a list (vector) that contain groups and channels.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Keeping code folded in Eclipse If I close Eclipse and then reopen it sometime later, all the code I have folded will be unfolded.
Is there a way to keep it folded?

A: It actually depends on the the feature you're using. For Java you can specify which parts should stay folded initially. Unfortunately it only can be comments, header comments, inner types, members and imports.
Here is the screenshot from Eclipse workspace properties for Java > Editor > Folding

A: You can also use

*

*Ctrl + Shift + / to fold your editor code.

*Ctrl + Shift + * to unfold your editor code.

Note: Here * and / would be on Numeric Keypad


text:
Q: OpenTok Nexmo outbound call won't work with SipProperty secure set true I'm integrating Nexmo in an application that uses OpenTok React as the front-end and the OpenTok Java SDK as the back-end.
When I set the SipProperty secure to true the call won't work.
When the secure property to false it will work.
Could someone explain this?
BTW i used an trial Nexmo account to test this.

A: TokBox/Nexmo Developer Advocate here.
The secure property is a boolean flag that indicates whether the media must be transmitted encrypted (true) or not (false, the default).
The reason that the SIP dial does not work when setting secure to true is because at this time, Nexmo SIP does not support SRTP, you have to use RTP.
For more information, please check out the following resources:

*

*OpenTok SIP Interconnect

*Nexmo SIP

*SRTP

*RTP


text:
Q: Using npm start with PM2 I am currently using pm2 to manage my node processes on my VPS. I am running the following command with PM2: pm2 start npm -- start. This works fine except for the fact that I can only use it for one process.
I have 2 processes that each use npm start to start it. When I run pm2 start npm -- start in the folder of the 2nd process, it does not add it to pm2. Instead it just restarts my first process.
How would I use my 2nd process with pm2?


text:
Q: cloudkit how to write to public database Iam using cloudkit to read and write in public database - in my application user suppose to be able to upload files and write records to database and other users to read it
I am using cloudkit however as far as I know to write to the public database user has to login with icloud account however apple does not allow this in production so how to solve this - how can I give the users a right to write to DB
  let Container = CKContainer.default()
    let database = Container.publicCloudDatabase
    let predicate = NSPredicate(value: true)
    let query = CKQuery(recordType: "NewCode", predicate: predicate) //Photos is table name in cloudkit server
    //-------Fetch the data---------------------

    database.perform(query, inZoneWith: nil,
                             completionHandler: ({results, error in

        DispatchQueue.main.async() {   //Disp

            if (error != nil) {
                DispatchQueue.main.async() {

                }
            }

            else {  //a
                if results!.count > 0 {
                    print("count = \(results!.count)")
                     record = results![0]
                    currentRecord = record

                    newcode = currentRecord?.object(forKey: "Code") as! String
                     newcodevalue =  Int(newcode)!
                     newcodevalue = newcodevalue + 10

                        print("new code  is = \(newcodevalue)")
                    myCodeStrinValue = String(newcodevalue)
                    print("new code  string = \(newcodevalue)")
                    record?.setObject(myCodeStrinValue as CKRecordValue?,forKey: "Code")
                    database.save(record!, completionHandler:  //save
                        ({returnRecord, error in
                            if let err = error {
                                DispatchQueue.main.async() {

                                }
                            } else {
                                DispatchQueue.main.async() {
                                    print("NewCode Table updated successfully")
                                    // passing the code value we fetched above to the second viewcontroller "Uploadphotoviewcontroller" to be saved with the uploaded photo when saved button on the second controller clicked. remember you have to set an ID for the second view controller "Uploadphotoviewcontroller" to be used here when passing the value to it (set ID in the attributes right panel

                                    // Instantiate SecondViewController
                                    let UploadPhotoviewcontroller = self.storyboard?.instantiateViewController(withIdentifier:
                                        "UploadPhotoviewcontroller") as! UploadPhotoviewcontroller

                                    // Set the code value got from the DB above to the variable "myCodeValue" (this variable declared in the second view controller that will receive the value passed from here "Uploadphotoviewcontroller"

                                    // add alpha numeric value to the code to make it more complicated for secuirty reasons

                                    let CodeLetter = self.randomAlphaNumericString (length: 3)

                                    UploadPhotoviewcontroller.myCodeValue = CodeLetter + myCodeStrinValue
                                    UploadPhotoviewcontroller.codeOnly = myCodeStrinValue

                                    // Take user to SecondViewController and accordingly remember not create graphical sague way link in the main storyboard to avoid reload of the view controller - remember to set ID attribute to  UploadPhotoviewcontroller to use it here
                                    self.navigationController?.pushViewController(UploadPhotoviewcontroller, animated: true)

                                }
                            }
                        }))   //save

                }
                else { //G
                    DispatchQueue.main.async()
                        {

                    }

                 }  //G

        } //a

      }  //Disp

    }))


text:
Q: String to Custom Type Substitution I would like to write a function that takes a currencyCode As String input parameter and outputs a custom currencyFormatString. My dilemma is deciding on the best (proper) way to do this. currencyCode is an ISO 4217 Currency Code (e.g. "USD", "GBP", "JPY", etc.), and I want to perform the following steps:

*

*Check for null or empty strings.

*Convert the code to the corresponding currency symbol (e.g. "$", "£", "¥" as in the above).

*Format the returning string with the appropriate symbol.

I have two cases for the formatting: with cents, and without. In the case of JPY, there are never cents, so in this case I would always return the non-cents (not nonsense, :P) format.
My latest idea is to create a Dictionary and populate it with the codes and symbols I need (FYI, we currently only need 6 codes/symbols and this very rarely changes). Is this a bad idea? Is there a better one? An XML file perhaps? I would love a code sample if you could. I'd provide one myself, but it's a scrambled mess of failed/less-than-ideal attempts at this point.
SOLUTIONS -- Based on hours of research, trial and error, and input from @tinstaafl.
'Method 1: Using Enumerable Type with Character Codes
'  Limitation: Does not support currency symbols with more than one character.
Public Module SLCurrency
    Enum ISOCurrency
        USD = 36
        CAD = 36
        AUD = 36
        EUR = 8364
        GBP = 163
        JPY = 165
    End Enum

    Public Function GetCurrencyFormat(ByVal currencyCode As String, ByVal withCents As Boolean) As String
        Dim _numberFormatString, _currency As New ISOCurrency

        [Enum].TryParse(Of ISOCurrency)(currencyCode, _currency)

        If withCents AndAlso Not _curr.Equals(ISOCurrency.JPY) Then
            _numberFormatString = "{0}* #,##0.00;[Red]{0}* (#,##0.00);{0}* ""-"";@"
        Else
            _numberFormatString = "{0}* #,##0;[Red]{0}* (#,##0);{0}* ""-"";@"
        End If

        Return String.Format(_numberFormatString, ChrW(_currency).ToString.Trim({ChrW(0)}))
    End Function
End Module

'Method 2: Using a Dictionary of Currency Codes (key) and Symbols
'  Advantage: Support currency symbols with more than one character,
'  but is not quite as clean and can be more complex to implement.
Public Module SLCurrency
    Dim CurrencyDict As New Dictionary(Of String, String) From {
        {"USD", "$"}, {"CAD", "$"}, {"AUD", "$"}, {"EUR", "€"}, {"GBP", "£"}, {"JPY", "¥"}
    }

    Public Function GetCurrencyFormat(ByVal currencyCode As String, ByVal withCents As Boolean) As String
        Dim _numberFormatString, _currency As String
        _currency = String.Empty

        CurrencyDict.TryGetValue(currencyCode, _currency)

        If withCents AndAlso Not _currency.Equals("JPY") Then
            _numberFormatString = "{0}* #,##0.00;[Red]{0}* (#,##0.00);{0}* ""-"";@"
        Else
            _numberFormatString = "{0}* #,##0;[Red]{0}* (#,##0);{0}* ""-"";@"
        End If

        Return String.Format(_numberFormatString, _currency)
    End Function
End Module

I always welcome comments on my solutions. It helps me become a better programmer. :)
At this point, I think I'll go with Method 1 to keep the code a bit simpler as I do not anticipate a need for the added complexity to support longer currency symbols, especially since most of them are very obscure currencies which a business would be highly unlikely to ever accept as payment anyway.

A: One simple way would be to create an enum with the value being the character code of the symbol:
Enum CurrencySymbols
    USD = 36
    GBP = 163
    JPY = 165
End Enum

A simple function to convert a string to enum value and return it as a string, could look something like this:
Private Function GetCurr(Input As String) As String
    Dim CurrCode As New CurrencySymbols
    If [Enum].TryParse(Of CurrencySymbols)(Input, CurrCode) Then
        GetCurr = ChrW(CurrCode)
    Else
        GetCurr = ChrW(0)
    End If
End Function

If the string is invalid this will return string with a character with code 0

A: It is up to you to decide which solution suits you and your task better, but one thing is for sure: you need a functionality somewhere which initializes these currencies, which is called at the initialization phase of your application and then you can use any currency through a getter.
Of course, you can use a dictionary. Also, you can use an XML file if you are sure no untrusted people will access it. Finally, you can store all these information into a database as well. So everything depends on your decision.


text:
Q: how to use Espresso with Kotlin Flow? In my app I use Kotlin Flow. Before I used suspend function with  EspressoIdlingResource.increment(), but it does not work with Kotlin Flow. How to solve this problem?

A: I've replicated your problem and then made it work.
I needed to add in your gradle the espresso-idling-resource lib in implementation and androidTestImplementation:
implementation 'androidx.test.espresso:espresso-idling-resource:3.3.0'
androidTestImplementation 'androidx.test.espresso:espresso-idling-resource:3.3.0'

This way I could create in my project the CountingIdlingResourceSingleton object:
object CountingIdlingResourceSingleton {

    private const val RESOURCE = "GLOBAL"

    @JvmField val countingIdlingResource = CountingIdlingResource(RESOURCE)

    fun increment() {
        countingIdlingResource.increment()
    }

    fun decrement() {
        if (!countingIdlingResource.isIdleNow) {
            countingIdlingResource.decrement()
        }
    }
}

Then you should call this in your code when you want the test to wait, in my case it was in the onViewCreated() of the first fragment shown:
CountingIdlingResourceSingleton.increment()

And when the first flow element arrived I just called:
CountingIdlingResourceSingleton.decrement()

And finally add this in your test class to make it wait until the countingIdlingResource is decremented:
init {
    IdlingRegistry.getInstance()
            .register(CountingIdlingResourceSingleton.countingIdlingResource)
}

@After
fun unregisterIdlingResource() {
    IdlingRegistry.getInstance()
            .unregister(CountingIdlingResourceSingleton.countingIdlingResource)
}

With this the test that checked that the value matches the first value returned by flow (Jody) works.
A working example can be find in github.com/jeprubio/waitflow where a flow element is emitted every 5 secs and the espresso test waits until the first element is emitted which is when the CountingIdlingResourceSingleton is decremented.


text:
Q: Segmentation fault when strdupa void pointer I'm fairly new to pointers, and void pointers is still black art to me.
In the following code I get a segfault when tmp->item = strdup(item);
I'm not sure how to fix.
int springmap_add(SpringMap *sm, char *key, void *item) {
    SpringMap *tmp = sm;
.
.
.
while (tmp) {

        if (!tmp->next) {

            tmp->next = springmap_init();
            tmp->next->key = strdup(key);
            tmp->next->item = strdup(item); // Segfault here
            return 1;
        }
        tmp = tmp->next;
    }
    return 0
}

int main(int argc, char* argv[]) {
    char* key[ESTS] = {"alpha"};
    void* ptr[ESTS] = {(void*)0xdeadbeef};

    SpringMap* map = springmap_init();

    for(int i = 0; i < TESTS; i++) {
    int status = springmap_add(map, key[i], ptr[i]);
    }
    springmap_free(map);
    return 0;

I'm not up to speed on void pointers.

A: The function name already tells: strdup composes of string duplicate, and it only is able to duplicate null-terminated C-strings (well, admittedly any data as long as it contains a null byte somewhere, though it would get cut off too early unless this null byte was the very last byte within the data).
void pointers in C have the unfortunate nature of implicitly converting to any other pointer type, happening in your code as well. However these pointers do not point to null-terminated C-strings, actually, they aren't even valid at all (most of most likely, at least)! Thus trying to read from them yields undefined behaviour.
So at first make sure that your void pointers point to valid memory. To use strdup they should point to C-strings, otherwise memcpy is the way to go, though you need to malloc storage space as target first. For both, you need the size of the object available, though. However you cannot get that back from the void pointer any more, thus you need yet another parameter.
You could write your own objdup function covering the duplication:
void* objdup(size_t size, void* object)
{
    void* copy = malloc(size);
    if(copy)
    {
        memcpy(copy, object, size);
    }
    return copy;
}

Still your pointers need to be valid! Some possible example might look like:
int main()
{
    SomeDataType o1;
    AnotherDataType o2;
    AnotherDatatType* ptr = &o2; // create a valid pointer
                                 // (could be done by malloc'ing memory, too)

    void* c1 = objdup(sizeof(o1), &o1);
    //                            ^ take the address of a REAL object!
    if(c1)
    {
        void* c2 = objdup(sizeof(*o2), o2); // or via pointer to REAL object
        if(c2)
        {
            // ...

            free(c2);
        }
        free(c1);
    }
    return 0;
}


text:
Q: For prosseguir se true Bom, estou tentando executar vários downloads, um atrás do outro, e gostaria que só começasse o próximo depois que o outro terminar.
Os códigos são esses:
  if StrToInt(version) < StrToInt(version2) then
  begin
    for x := StrToInt(version) to StrToInt(version2) do
      url := 'http://pokestage.ddns.net/patch/'+IntToStr(x)+'.rar';
    BaixarArquivo(IdHTTP1, url, x);
  end
  else
    sProgressBar1.Position := sProgressBar1.Max;
  slabel1.caption := '100%';
end;

Onde BaixarArquivo retorna true quando o arquivo termina de ser baixado.
Como faço para que só vá para o próximo depois que um for concluido?

A: Conforme seu comentário:

Sim, está executando normalmente, só que ele já começa baixando o último arquivo.

O seu problema está no seu comando for.
É uma questão de sintaxe da linguagem Pascal, o Begin e o End.
Como o { } para php entre outros.
Por isso da identação ser uma coisa importante.
Veja seu exemplo:
  if StrToInt(version) < StrToInt(version2) then
  begin
    // o for executa todos os contadores..
    for x := StrToInt(version) to StrToInt(version2) do
      url := 'http://pokestage.ddns.net/patch/'+IntToStr(x)+'.rar';

    // quando chegar aqui, a URL será a última --> valor de version2
    BaixarArquivo(IdHTTP1, url, x);
  end
  else
    sProgressBar1.Position := sProgressBar1.Max;
  slabel1.caption := '100%';
end; // <-- sobrando, a princípio

Como deveria ser esse laço for?
for x := StrToInt(version) to StrToInt(version2) do
begin
  url := 'http://pokestage.ddns.net/patch/'+IntToStr(x)+'.rar';
  BaixarArquivo(IdHTTP1, url, x);
end;

Agora ele gera uma url e passa para o método BaixarArquivo, depois gerará outro, e então passará para o método BaixarArquivo. Assim, sucetivamente.
Como as linhas deveriam ficar:
if StrToInt(version) < StrToInt(version2) then
begin
  for x := StrToInt(version) to StrToInt(version2) do
  begin
    url := 'http://pokestage.ddns.net/patch/'+IntToStr(x)+'.rar';
    BaixarArquivo(IdHTTP1, url, x);
  end;
end
else
  sProgressBar1.Position := sProgressBar1.Max;

slabel1.caption := '100%';

Sobre os comandos dentro do método OnTimer do componente TTimer:
Há um detalhe aqui que você precisa saber.
O componente TTimer executará o evento OnTimer de tempos em tempos conforme setado na sua proprieadade Interval.
Logo, como desejado por você na sua última pergunta, é fundamental na primeira linha do método OnTimer ter a atribuição do valor false para a propriedade do método Enable do componente TTimer.
procedure Form1.Timer1OnTimer(sender: TObject);
begin
  Timer1.Enable := false;

  ... // restante dos seus comandos.
end;

Caso você não faça isso, o método OnTimer será executado repetidamente, tentando fazer novamente os comandos de download.
Pelo tempo informado, você pode ter os comandos de download sendo executados novamente antes mesmo de ter terminado a primeira iteração do for com o método BaixarArquivo.
Espero que isso tenha ficado claro.


text:
Q: Shopify - Adding Footer Nav I'm using Shopify's Debut theme and would like to add the footer navigation to the bottom. In the backend, I have two navigations, "Main menu" and "Footer menu" set up.
This works:

{% for link in linklists.main-menu.links %}

{{ link.title }}

{% endfor %}

but this doesn't when I put "footer-menu":

{% for link in linklists.footer-menu.links %}

{{ link.title }}

{% endfor %}

A: The default footer menu is just footer not footer-menu.
So you should call linklists.footer.links instead.


text:
Q: Passing list Between Functions I have the code below where I change the globals. Most of what I have read has said to stay away from globals... In the example below I want to use "make_lists" then print it in "print_list" then clear the list. I use globals to do this, suggestions on how to avoid globals?
I know I could add this all in one function, but this is all part of a bigger function this is the only part I am having problems with. Thank in advance.
x_lst = []

def make_lists():
    global x_lst

    x_lst.append("Hello")

def print_list():
    global x_lst

    for i in x_lst:
        print(i)

    x_lst = []

def main():
    make_lists()
    print_list()

if __name__ =="__main__":
    main()

A: To avoid using global, you have to use the return keyword in the function declaration to return a value, which will be your newly created list in our case. You also have to use arguments in the function declaration, which are the placeholders of the values in the function. So the reason why you don't need the global value is because you are passing the list from one function to another.
def make_lists():
    return ['Hello']  # Your are creating the list with a single value,
                      # and return it

def print_list(ls):
    for i in ls:      # You are iterating thru the list,
        print(i)      # which is the input of this function

def main():
    print_list(make_lists())  # In your main function you call the make_list()
                              # which will return the newly created list, and
                              # pass it to print_list, which will iterate thru
                              # the list and prints your values out

if __name__ =="__main__":
    main()

A: def make_list():
    return ['Hello']

def print_list(l):
    for x in l:
        print(x)

def main():
    print_list(make_list())

Pass data into functions with arguments, and pass data out with return values.

A: Here's my simple suggestion, why not give the functions inputs. Passing in a list to print out instead of using a global variable is an easy alternative. If you're looking for a way to keep state for a particular scope, maybe try putting these functions in a class (in other words use OOP)
The problem with global variables is that when you declare 'x_lst' as global, it opens up "x_lst" to outside the function, which may not or be your intended goal.

A: I've made the minimal set of changes to your code that illustrate how to pass your list instead of using a global.  Hope this helps clarify.
def make_lists(x_lst):
    x_lst.append("Hello")

def print_list(x_lst):
    for i in x_lst:
        print(i)

def main():
    x_lst = []

    make_lists(x_lst)
    print_list(x_lst)

if __name__ =="__main__":
    main()


text:
Q: Running games through RemoteApp I'm trying to build a solution which allows me to keep my games and production software separated, without having to dual-boot and while keeping the ability to use Hyper-V on the host (since it's used to develop UWP apps and I need the emulators).
I decided to try the RemoteApp feature by installing Windows Server 2012 R2 on a newly created Hyper-V machine and, using RemoteApp Tool, I did a test with an old copy of Age of Empires 3.
What I get is a message saying:

The game cannot be run in a remote desktop session

which stops me from playing.
I've also tried by manually configuring the server with RD roles and stuff, but it fails the connection because of certificate issues (I wasn't able to use a self-signed certificate for some reasons).
Since I'm finding online posts telling that it's possible to play through RemoteApp, is there any kind of solution to this issue?

A: Another job for MS!
All jokes aside, don't use RD or RA for that. Use TeamViewer. It's free and it allows you to run games, as you're connecting to the console rather than a RD socket.


text:
Q: How to create a "Solid" block? pygame I want to implement solid blocks to my simple platformer game I´m working on, but I don´t know how.
I tried lots of things, but nothing work.
I want to do following:
when I jUMP on it, I will stay there
when I jump underneath it, I won´t reach the top
when I jump from left side, I won´t reach the right side
when I jump from right side, I won´t reach the left side
I would really appreciate your help, thanks.
my code:
from pygame.locals import *
SCREEN_WIDTH = 1923
SCREEN_HEIGHT = 1000

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super(Player, self).__init__()
        self.surf = pygame.image.load('C:\Sprites\mrkva.png').convert()
        self.surf.set_colorkey((0, 0, 0), RLEACCEL)
        self.rect = self.surf.get_rect()
        self.rect.y = y
        self.rect.x = x

        self.isJump = False
        self.jumpCount = 9

    def update(self, pressed_keys):

        if pressed_keys[K_a]:
            self.rect.move_ip(-10, 0)
        if pressed_keys[K_d]:
            self.rect.move_ip(10, 0)

        if pressed_keys[K_LEFT]:
            self.rect.move_ip(-10, 0)
        if pressed_keys[K_RIGHT]:
            self.rect.move_ip(10, 0)

        if self.rect.left < 0:
            self.rect.left = 0
        if self.rect.right > SCREEN_WIDTH:
            self.rect.right = SCREEN_WIDTH
        if self.rect.top <= 0:
            self.rect.top = 0
        if self.rect.bottom >= 970:
            self.rect.bottom = 970

    def jump(self):
        if self.isJump:
            if self.jumpCount >= -10:
                neg = 3
                if self.jumpCount < 0:
                    neg = -3
                self.rect.y -= self.jumpCount**2 * 0.101 * neg
                self.jumpCount -= 1
            else:
                self.isJump = False
                self.jumpCount = 9

class Platform(pygame.sprite.Sprite):
    def __init__(self, xloc, yloc):
        super(Platform, self).__init__()
        self.surf = pygame.image.load('C:\Sprites\kocka.png').convert()
        self.surf.set_colorkey((255, 255, 255), RLEACCEL)
        self.rect = self.surf.get_rect()
        self.rect.y = yloc
        self.rect.x = xloc

pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

pygame.display.set_caption('gameee')
platform = Platform(1, 527)
player = Player(1, 969)

all_sprites = pygame.sprite.Group()
all_sprites.add(platform)
all_sprites.add(player)

clock = pygame.time.Clock()
run = True
while run:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                run = False
            elif event.key == K_SPACE:
                player.isJump = True

        elif event.type == QUIT:
            run = False

    clock.tick(35)
    screen.blit(player.surf, player.rect)
    screen.fill((28, 173, 234))
    for entity in all_sprites:
        screen.blit(entity.surf, entity.rect)
    pygame.display.flip()

    pressed_keys = pygame.key.get_pressed()

    player.jump()
    player.update(pressed_keys)

    pygame.display.update()
pygame.quit()```

A: When performing a collision test in platformer, you must always consider the direction of movement of the player. The player's reaction is different as they hit a platform from above or below. This can lead to different cases in your code.
I'll give you an example of how to land on a platform, based on your code.

First, correct the code that makes the player jump. Add a constant for the jump count and round the player's y coordinate. So the player falls on the same distance as it moves up:
JUMP_COUNT = 10

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y):
        # [...]

        self.isJump = False
        self.jumpCount = JUMP_COUNT

    # [...]

    def jump(self):
        if self.isJump:
            if self.jumpCount >= -JUMP_COUNT:
                neg = 3
                if self.jumpCount < 0:
                    neg = -3
                self.rect.y -= round(self.jumpCount**2 * 0.101 * neg)
                self.jumpCount -= 1
            else:
                self.isJump = False
                self.jumpCount = JUMP_COUNT

Save the player's y coordinate before moving the player. Check for collisions after the player moves. If the player falls and a collision is detected, place the bottom of the player on top of the platform:
run = True
while run:
    # [...]

    prev_y = player.rect.y

    player.jump()
    player.update(pressed_keys)

    if player.rect.colliderect(platform.rect):
        dir_y = player.rect.y - prev_y
        if dir_y > 0:
            player.isJump = False
            player.jumpCount = JUMP_COUNT
            player.rect.bottom = platform.rect.top

    pygame.display.update()


text:
Q: Substituindo DatePickerAndroid e TimePickerAndroid por DateTimePicker, porém não consigo utilizar Estou fazendo um projeto de um curso que comprei, porém em certa aula é utilizado o DatePickerAndroid e TimePickerAndroid, que foram descontinuados (inclusive o TimePicker nem exite mais).
O código era o seguinte:
export default function DateTimeInputAndroid({type}){

    const [datetime, setDateTime] = useState();

    async function selectDataOrHour(){
        if(type == 'date'){
            const {action, year, month, day} = await DatePickerAndroid.open({
                mode: 'calendar'
            })
        if (action == DatePickerAndroid.dateSetAction)
        setDateTime(`${day} - ${month} - ${year}`);
        } else {
            const {action, hour, minute} = await TimePickerAndroid.open({
                is24Hour: true
            });

            if (action != TimePickerAndroid.dismissedAction)
            setDateTime(`${hour}:${minute}`);
        }
    }

    return (
        <TouchableOpacity onPress={selectDataOrHour}>
            <TextInput style={styles.input}
            placeholder={type =='date' ? 'Clique aqui para definir a data' : 'Clique aqui para definir a hora'}
            editable={false}
            value={datetime}/>
            <Image style={styles.iconTextInput}
            source={type =='date'? iconCalendar : iconClock} />
        </TouchableOpacity>
    )
}

Segui as instruções da documentação do DateTimePicker, e tentei reconstruir o código, porém o mesmo não está funcionando como deveria (ao clicar no touchable, abrir o calendário/relógio). Ficou desta maneira:
export default function DateTimeInputAndroid({type}){

    const [datetime, setDateTime] = useState();

    setDate = (event, date) => {
        if (date !== undefined) {
          setDateTime(format(new Date(date), 'dd/MM/yyyy'));
        }
      };

      setTime = (event, date) => {
        if (date !== undefined) {
            setDateTime(format(new Date(date), 'HH:mm'));
        }
      };

    async function selectDataOrHour(){
        if(type == 'date'){
        <DateTimePicker mode='date' value={new Date()} onChange={setDate()} display='default'/>
        } else {
        <DateTimePicker is24Hour={true} mode='time' value={new Date()} onChange={setTime()}/>
        }
    }

    return (
        <TouchableOpacity onPress={selectDataOrHour}>
            <TextInput style={styles.input}
            placeholder={type =='date' ? 'Clique aqui para definir a data' : 'Clique aqui para definir a hora'}
            editable={false}
            value={datetime}/>
            <Image style={styles.iconTextInput}
            source={type =='date'? iconCalendar : iconClock} />
        </TouchableOpacity>
    )
}

Não consegui identificar o que fiz de incorreto, visto que se o DateTimePicker for criado dentro do return, ele executa assim que o componente é carregado normalmente.


text:
Q: List-view groups with Qt? We have ListView.Groups in .NET. Is there an equivalent in Qt (without using Windows APIs)?
I am unable to find anything that indicates support for this in the documentation for Qt.
Example in Windows Vista/7: http://i50.tinypic.com/zumgyg.jpg
Thanks in advance!

A: It looks like that is very easy to do with Qt model-view control.
It's a little confusing at first, but basically all lists, tree ctrls and grids are treated in the same way - which lets you do interestign combiantions of them very easily.
Edit: Casey posted a useful comment in an answer that was deleted.
Here is the text and the link:

creating your tree model is pretty
  straight forward. To create that
  "grouped" effect where the parent
  nodes look different then their
  children, I would suggest creating an
  ItemDelegate then setting it on your
  view using setItemDelegate1. In the
  Delegate's paint function you can
  detect whether the index is a header
  or now, and draw something
  appropriately. When you get there if
  you need help, start another question
  and I can post an example.

http://doc.trolltech.com/4.6/qabstractitemview.html#setItemDelegate


text:
Q: Is it possible to create multiple "mj-column" using a for loop? I would like something like below
{% for item in list %}
    <mj-column>
        {{ item }}
    </mj-column>
{% endfor %}

But after giving it a try and convert to HTML via the official editor, the HTML file cannot find item.


text:
Q: Get rows where lastLoginTimestamp is in last 7 days I'm trying to get the rows from a table where lastLoginTimestamp is in last 7 days and I'm doing as follow:
SELECT * FROM representative WHERE DATE_SUB(lastLoginTimestamp, INTERVAL 7 DAY)

lastLoginTimestamp is stored as a VARCHAR so this is where the problem is I though. How do get that rows in this case? Any help?
This are some of the values on that column to play with:
1427162434
1422557283
1395854997

Update
Based on the first answer I've changed my query to this:
SELECT
    *, from_unixtime(lastLoginTimestamp) AS lastLogin
FROM
    representative
WHERE
    DATE_SUB(
        from_unixtime(lastLoginTimestamp),
        INTERVAL 7 DAY
    )

But I'm getting the wrong values, for example I'm getting a row from this lastLogin = 2015-03-23 21:30:34 which is wrong

A: The values seem to be Unix timestamps, stored as strings. You can use the special datetime functions that MySQL has for conversions:
SELECT *
FROM representative
WHERE DATE_ADD(FROM_UNIXTIME(lastLoginTimestamp), INTERVAL 7 DAY) >= NOW() ;

but it won't be very good for efficiency. Much more efficient, if there is an index on the column, to do it the other way around:
(we assume that the values in the columns are CHAR(10). If some values have smaller length, you'll get erroneous results.)
SELECT *
FROM representative
WHERE lastLoginTimestamp
      >= CAST(UNIX_TIMESTAMP(NOW() - INTERVAL 7 DAY) AS CHAR(10));

The above condition if you want all rows, starting from exactly 7 days ago, same time as now. If you want rows starting from 6 days ago at midnight, so previous 6 days + today (whatever that is, a few minutes or 23 hours, 59 mins):
SELECT *
FROM representative
WHERE lastLoginTimestamp
      >= CAST(UNIX_TIMESTAMP(CURRENT_DATE - INTERVAL 6 DAY) AS CHAR(10));

A: select from_unixtime("1427162434");

the rest you will figure out
but consider formatting the historical data and just change the type and test. Can't believe that the dates are pushed to the DB as chars.


text:
Q: Statistics, Central limit theorem The amount of nicotine in Dytusoon cigarettes have a mean of 0.941 g and a standard deviation of 0.313 g. Find the probability of randomly selecting 40 cigarettes with a total of 36 g of nicotine or more.
When using my TI84 calculator I enter the problem as "normalcdf(36,E99,.941,.313/(squareroot of 40))" but I get 0 as the answer. So I am wondering how I would solve this using my calculator( what part of my formula is wrong or is there a step I am missing).

A: My guess is that you aren't calculating the probability associated with the correct distribution, so the answer you are getting is too small, so you are getting an underflow error and thus your calculator reports 0. Let's rehash the steps to solving the problem here

EDIT:
The first entry probably should not be 36. I can't tell you exactly what I think it might be since I don't know how the "normalcdf" function on your calculator works or what its parameters are; there are multiple ways to interpret it.
My guess is that the "normalcdf" function is using the distribution of $\mathcal{N}(0,1)$ to calculate the probabilities.
However, what you want to calculate is the distribution of $\mathcal{N}(40*(0.941),40*(0.313)^2)$ where the first number in parentheses is the mean, and the second is the variance (square of the standard deviation). We can transform the probabilities of the one distribution to another as follows (I believe; I am doing this all in my head and not writing it down so I am probably making mistakes).
What we want to calculate is $\mathbb{P}(Z \ge 36)$ where $Z = \sum_{i=1
}^{40} X_i$, and $Z \sim \mathcal{N}(40*(0.941),40*(0.313)^2)$ but your calculator only lets you calculate the distribution of $\mathcal{N}(0,1)$. So we normalize $Z$ to get a random variable $$Y= \frac{Z-(40*0.941)}{\sqrt{40}*(0.313)}$$ which is distributed as $\mathcal{N}(0,1)$.
Now $$\mathbb{P}(Z \ge 36)=\mathbb{P}\left(Y \ge \frac{36-40*0.941}{\sqrt{40}*0.313}\right)$$

Let $X$ be the amount of nicotine in the $i$th cigarette, $i=1, \dots, 40$.
Assume that the amount of nicotine in each cigarette is independent, i.e. all of the $X_i$ are independent.
Using the Central Limit Theorem, approximate the $X_i$ by normal variables with mean $0.941$ and and variance $0.313$.
Thus what you want to calculate is the probability distribution of $\sum_{i=1}^{40} X_i$, which is the sum of independently distributed normal random variables, and therefore normally distributed itself.
Make sure you are calculating the mean and variance of $\sum_{i=1}^{40} X_i$ correctly; they are not the same as the mean and variance of the $X_i$, which looks like what you calculated above. See the formulas on Wikipedia for two independently distributed normal random variables, https://en.wikipedia.org/wiki/Sum_of_normally_distributed_random_variables, and then generalize.

A: Hint: The sum of normally distributed and independent random variables are normally distributed as well.
If $X_i\sim \mathcal N(\mu, \sigma ^2)  $
then $\sum_{i=1}^n X_i\sim \mathcal N(n\cdot \mu, n\cdot \sigma ^2) $
Therefore $P(\sum_{i=1}^{40} X_i\geq 36)=1-P(\sum_{i=1}^{40} X_i <36)$
$=1-\Phi\left(\frac{36-40\cdot 0.941}{\sqrt{40} \cdot 0.313}\right)=1-\Phi(-0.82846)$
where $\Phi(z)$ is the cdf of the standard normal distribution. The value for this function can be looked up in this or other tables.
If you use a calculator with the function $\texttt{normalcdf}(X; \mu; \sigma)$, then you get the result of $P(\sum_{i=1}^{40} X_i\geq 36)$ by typing in $\texttt{normalcdf}(36;40\cdot 0.941; \sqrt{40}\cdot 0.313)$ or
$\texttt{normalcdf}(36; 37.64;  1.9796)$
Then you take the result and subtract it from $1$.


text:
Q: How to delete first occurrence of value in array? I have a container of integers from which I would like to delete a specific value v. The container can contain more than one copy of v but I only want to delete the first instance I encounter. How do I fix my code to accomplish this?
void delete (int s[] , int &top , int v)
{
    int ts[size] ;
    int ttop=-1;
    while(top!=-1)
    {
        if(s[top]!=v)
            push(ts,ttop,s[top]);
        pop(top);
    }
    while(ttop!=-1)
    {
        push(s,top,ts[ttop]);
        pop(ttop);
    }
}

A: You need to define a flag which will be set after the first find.
void delete (int s[] , int &top , int v)
{
    bool found = false;
    int ts[size] ;
    int ttop=-1;
    while(top!=-1)
    {
        if (s[top]!=v)
        {
            push(ts,ttop,s[top]);
        }
        else
        {
           if (found == false)
           {
              found = true;
              push(ts,ttop,s[top]);
           }
        }
        pop(top);
    }
    while(ttop!=-1)
    {
        push(s,top,ts[ttop]);
        pop(ttop);
    }
}

As long as found is false, it will also check to see if the element matches. Once found is true, it will always include the item, even if it matches.
Note that this is not the most effective way to do this, merely a means of modifying your code so that it does the trick.


text:
Q: Getting the JSON values in a component I have a chatter API response in below JSON format
    "currentPageToken": null,
"currentPageUrl": "/services/data/v39.0/chatter/feeds/record/0F98E0000004UhASAU/feed-elements",
"elements": [
    {
        "body": {
            "isRichText": false,
            "messageSegments": [
                {
                    "text": "Hi All,\n\nPlease find attached the THOR February Release notes. Please refer to the deck to know about the enhancements which have been deployed.
                    "type": "Text"
                }]

I want the "text" part shown in the component. The JSON value i had parsed to an object. Its not throwing any warnings/error but does not show any values in the UI.
          Component
         ===========
        <aura:component  access="global" controller="ChatterFeedController">
        <aura:attribute name = "groupatt" type="Object" />
        <aura:handler name="init" action="{!c.userFeedItem}" value="{!this}"/>

              <aura:iteration items="{!v.groupatt}" var="att">

                {!att}

              </aura:iteration>

     Controller
     ==========
    userFeedItem: function(component, event, helper) {
    var userFeed = component.get("c.getFeedData");
    var groupID = component.get("v.groupattid");
    console.log("GroupID: " + groupID);
    userFeed.setParams({"groupId" : groupID});
    userFeed.setCallback(this,function(response){
    var state = response.getState();
        if(state==="SUCCESS"){
           var jtext = response.getReturnValue();
       for (var i=0; i<jtext.elements.length; ++i){
          var body = jtext.elements[i].body;
       }
        component.set("v.groupatt",body.messageSegments[0].text);
        } else {
            console.log('Problem getting feed, response state: ' + state);
        }
    });
    $A.enqueueAction(userFeed);
},

A: Here is a method that takes the output that you have in your question and parses and extracts the required data.
I noticed that you have some problems with the output JSON - however, this is just an output from chatter correct - so I doubt there is a problem there - perhaps just a transcription error?
Here is the sample method that you can drop into any component:
({
    init : function(component, event, helper) {
        var jsonOBJ = {
                    "currentPageToken": null,
                    "currentPageUrl": "/services/data/v39.0/chatter/feeds/record/0F98E0000004UhASAU/feed-elements",
                    "elements": [
                      {
                        "body": {
                          "isRichText": false,
                          "messageSegments": [
                            {
                              "text": "Hi All,\n\nPlease find attached the THOR February Release notes. Please refer to the deck to know about the enhancements which have been deployed.",
                              "type": "Text"
                            }
                          ]
                        }
                      }
                    ]
                  };
        var jsonSTR = JSON.stringify(jsonOBJ);
        var parsedJSON = JSON.parse(jsonSTR);

        console.log(JSON.stringify(jsonOBJ));
        console.log(jsonOBJ.elements[0].body.messageSegments[0].text);
    }
})

If the object you are receiving is actually an object there is no need to parse or stringify - try something like this:
var jsonResult = response.getReturnValue();
//breaking this into two lines because so formatting doesn't like it:
var body = jsonResult.elements[0].body;
component.set("v.groupatt",body.messageSegments[0].text);

EDIT - Added a sample callback handler
userFeed.setCallback(this, function(response) {
    var state = response.getState();
    if (state === "SUCCESS") {
        var jtext = response.getReturnValue();
        var groupatt = component.get("v.groupatt");

        for (var i = 0; i < jtext.elements.length; ++i) {
            var body = jtext.elements[i].body;
                if (body && body.messageSegments.length){
                    groupatt.push(body.messageSegments[0].text);
                }
        }
        component.set("v.groupatt", strArray);
    }
    else {
        console.log('Problem getting feed, response state: ' + state);
    }
});

And finally, for the component itself change from object to string array:
<aura:attribute name = "groupatt" type="String[]" />


text:
Q: Error in finding Coefficients and odds ratio of variables in binomial logistic regression with stepwise selection of variables in R I am trying to build a binomial logistic regression model. I firstly build the equation, then applied stepwise method to choose the best variables. In the end I am trying to use the function logistic.display to get the coefficients and odds ratio because I want to demonstrate  to effect of the variables on the model. when I run the logistic.display function I get error "$ operator is invalid for atomic vectors". Can anyone help? Thank you
model <- glm(decision ~., data = train.data,family = "binomial")

step.model <- stepAIC(model, direction = "both",
                      trace = FALSE)

logistic.display(step.model)

summary(step.model)

Call:
glm(formula = decision ~ Exposure + VehAge + BonusMalus, family = "binomial",
    data = train.data)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-0.6911  -0.3210  -0.2710  -0.2261   2.9227

Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept) -4.66465    0.81457  -5.727 1.03e-08 ***
Exposure     1.16920    0.54048   2.163   0.0305 *
VehAge      -0.05930    0.03710  -1.599   0.1099
BonusMalus   0.01961    0.01008   1.946   0.0517 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 275.12  on 800  degrees of freedom
Residual deviance: 267.24  on 797  degrees of freedom
AIC: 275.24

Number of Fisher Scoring iterations: 6

class(step.model)
[1] "glm" "lm"

This is a sample of my train.data
structure(list(id = c(1, 3, 5, 10, 11, 13, 15, 17, 18, 21),
    var1 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), var2 = c(0.1,
    0.77, 0.75, 0.09, 0.84, 0.52, 0.45, 0.27, 0.71, 0.15), var3 = c("D",
    "D", "B", "B", "B", "E", "E", "C", "C", "B"), var4 = c(5L,
    5L, 6L, 7L, 7L, 6L, 6L, 7L, 7L, 7L), var5 = c(0L, 0L, 2L,
    0L, 0L, 2L, 2L, 0L, 0L, 0L), var6 = c(55L, 55L, 52L, 46L,
    46L, 38L, 38L, 33L, 33L, 41L), var7 = c(50L, 50L, 50L,
    50L, 50L, 50L, 50L, 68L, 68L, 50L), var8 = c("B12", "B12",
    "B12", "B12", "B12", "B12", "B12", "B12", "B12", "B12"),
    var9 = c("Regular", "Regular", "Diesel", "Diesel", "Diesel",
    "Regular", "Regular", "Diesel", "Diesel", "Diesel"), var10 = c(1217L,
    1217L, 54L, 76L, 76L, 3003L, 3003L, 137L, 137L, 60L), var11 = c("R82",
    "R82", "R22", "R72", "R72", "R31", "R31", "R91", "R91", "R52"
    ), decision = c(1, 1, 1, 1, 0, 1, 1, 0, 1, 1)), row.names = c(NA,
10L), class = "data.frame")


text:
Q: Confidence intervals statistics question Let $\mu_{1}$ and $\mu_{2}$ be the service time of employee $1$ and $2$.For random sample $n_{1}=8$ for employee $1$ the average service time $\bar{x_{1}} = 181.6 $ and for random sample $n_{2}=10$ for employee $2$  the average service time $\bar{x_{2}} = 141.5$.It is given that $\sigma_{1}^{2} = \sigma_{2}^{2}=40$ and $P(Z>=1.96) = 0.025$,$P(Z>=1.64)=0.05$. Find a 95% confidence interval of the difference between the service times of employees 1 and 2.
I was thinking of applying this formula:
$\bar{x_{1}}-\bar{x_{2}}-z_{0.975}\cdot\sqrt{\frac{\sigma_{1}^{2}}{n_{1}^2}+\frac{\sigma_{2}^{2}}{n_{2}^2}}<=\mu_{1}-\mu_{2}<=\bar{x_{1}}-\bar{x_{2}}+z_{0.975}\cdot\sqrt{\frac{\sigma_{1}^{2}}{n_{1}^2}+\frac{\sigma_{2}^{2}}{n_{2}^2}}$
But it doesnt give me $z_{0.975}$.How can I find $z_{0.975}$ from $P(Z>=1.1.96) = 0.025$,$P(Z>=1.64)=0.05$?


text:
Q: Thunderbird Contacts with Zimbra server (zindus alternative) is there a plug in for thunderbird 24+ that can sync contacts (the address book)
with a zimbra server?
I used zindus but the end of its life left me without sync plug in
reference: zindus end of life


text:
Q: Sort a list of strings that contain integers while ignoring white space in python I want to sort the list that has white space between each element. When I try to sort it using sorted(), it sorts the white space as well. I do not want that. How do I implement this in python?
A = '1 10'
sorted(A)
print(A)

Output:

[' ', '0', '1', '1']

Output I want:

'1 10'

A: Your variable A is currently a string. You want to first convert into a list, by using the split() function. The split function is used to convert a string to a list based on the given delimiter. For example,
x=A.split(" ") will give you a list x as ['1','10'], and then you can sort x itself using x.sort(), or x=sorted(x). The difference between sorted and sort is sorted will return a new list, while sort sorts the given list.

A: I think you could try the following for this.
string = '1 10'
final = sorted(string.split(), key = int)
final = " ".join(final)

A: You can split and then sort them. Use key parameter in sorted
A='1 10'
out=sorted(A.split(),key=int)
# ['1','10']

From other answers I understood you can use join.
' '.join(sorted(A.split(),key=int))
# '1 10'

A: After getting the list of numbers sorted use join to return a string with white spaces.


text:
Q: Como exportar uma DIV HTML para PDF rederizando o CSS? Alguem tem algum codigo que consiga exportar uma DIV para PDF renderizando todo o CSS dessa DIV?
É melhor eu fazer isso no backEnd (Java) ou no frontEnd (JavaScript)?
Se alguem puder ajudar agradeço!!
EDIT:
Valeu pela resposta Gabriel Rodrigues, mas esse esquema ai não funfou do jeito que eu preciso
E a pagina original com css era assim:

A: Da pra fazer umas solução boa juntando jsPDF e html2canvas
Exemplo:

$('#button').click(function() {
  var doc = new jsPDF('landscape', 'pt', 'a4');
  doc.addHTML($('#conteudo'), function() {
    doc.save("teste.pdf");
  });
});
body {
  text-align: center;
}
div {
  color: #605B5B;
  background-color: white;
  padding: 50px;
  margin: 10px;
}
button {
  background-color: #44c767;
  -moz-border-radius: 28px;
  -webkit-border-radius: 28px;
  border-radius: 28px;
  border: 1px solid #18ab29;
  display: inline-block;
  cursor: pointer;
  color: #ffffff;
  font-family: Arial;
  font-size: 17px;
  padding: 16px 31px;
  text-decoration: none;
  text-shadow: 0px 1px 0px #2f6627;
}
button:active {
  position: relative;
  top: 1px;
}

Silvio Santos Ipsum!

boca sujuam... sem vergonhuamm. Mah é a porta da esperançaam. O Raul Gil é gayam! ... Maa O Ah Ae! Ih Ih! O Raul Gil é gayamm! Mah é a porta da esperançaam.

    Patríciaaammmm... Luiz Ricardouaaammmmmm. Ha haeeee. Hi hi. É namoro ou amizadeemm? Ma vale dérreaisam? Eu só acreditoammmm.... Vendoammmm. Mah você não consegue né Moisés? Você não consegueam. Um, dois três, quatro, PIM, entendeuam? Ma vejam só, vejam
    só.

<button id="button">Baixar</button>

Veja funcionando no jsfiddle

A: Update
Baseado na seguinte resposta, adaptei o script e criei uma função estendida do JQuery para facilitar a criação de PDF's baseado em HTML. O script prove criar multiplicas páginas caso o tamanho da imagem ultrapasse o limite da folha a4, além de manter o CSS da página.
Disponível também no gist.

(function($){
    $.fn.createPdf = function(parametros) {

        var config = {
            'fileName':'html-to-pdf'
        };

        if (parametros){
            $.extend(config, parametros);
        }

        var quotes = document.getElementById($(this).attr('id'));

        html2canvas(quotes, {
            onrendered: function(canvas) {
                var pdf = new jsPDF('p', 'pt', 'letter');

                for (var i = 0; i <= quotes.clientHeight/980; i++) {
                    var srcImg  = canvas;
                    var sX      = 0;
                    var sY      = 980*i;
                    var sWidth  = 900;
                    var sHeight = 980;
                    var dX      = 0;
                    var dY      = 0;
                    var dWidth  = 900;
                    var dHeight = 980;

                    window.onePageCanvas = document.createElement("canvas");
                    onePageCanvas.setAttribute('width', 900);
                    onePageCanvas.setAttribute('height', 980);
                    var ctx = onePageCanvas.getContext('2d');
                    ctx.drawImage(srcImg,sX,sY,sWidth,sHeight,dX,dY,dWidth,dHeight);

                    var canvasDataURL = onePageCanvas.toDataURL("image/png", 1.0);
                    var width         = onePageCanvas.width;
                    var height        = onePageCanvas.clientHeight;

                    if (i > 0) {
                        pdf.addPage(612, 791);
                    }

                    pdf.setPage(i+1);
                    pdf.addImage(canvasDataURL, 'PNG', 20, 40, (width*.62), (height*.62));
                }

                pdf.save(config.fileName);
            }
        });
    };
})(jQuery);

function createPDF() {
    $('#renderPDF').createPdf({
        'fileName' : 'testePDF'
    });
}

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

<button type="button" class="btn btn-success" onclick="createPDF();">pdf</button>

Bootstrap Tutorial

Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile-first projects on the web.

     #
     Population
     Date
     Age

     1
     1,363,480,000
     March 24, 2014
     19.1

     2
     1,241,900,000
     March 24, 2014
     17.4

     3
     317,746,000
     March 24, 2014
     4.44

     4
     249,866,000
     July 1, 2013
     3.49

     5
     201,032,714
     July 1, 2013
     2.81

     6
     1,363,480,000
     March 24, 2014
     19.1

     7
     1,241,900,000
     March 24, 2014
     17.4

     8
     317,746,000
     March 24, 2014
     4.44

     9
     249,866,000
     July 1, 2013
     3.49

     10
     201,032,714
     July 1, 2013
     2.81

     11
     1,363,480,000
     March 24, 2014
     19.1

     12
     1,241,900,000
     March 24, 2014
     17.4

     13
     317,746,000
     March 24, 2014
     4.44

     14
     249,866,000
     July 1, 2013
     3.49

     15
     201,032,714
     July 1, 2013
     2.81

     16
     1,363,480,000
     March 24, 2014
     19.1

     17
     1,241,900,000
     March 24, 2014
     17.4

     18
     317,746,000
     March 24, 2014
     4.44

     19
     249,866,000
     July 1, 2013
     3.49

     20
     201,032,714
     July 1, 2013
     2.81

     21
     1,363,480,000
     March 24, 2014
     19.1

     22
     1,241,900,000
     March 24, 2014
     17.4

     23
     317,746,000
     March 24, 2014
     4.44

     24
     249,866,000
     July 1, 2013
     3.49

     25
     201,032,714
     July 1, 2013
     2.81

     26
     1,363,480,000
     March 24, 2014
     19.1

     27
     1,241,900,000
     March 24, 2014
     17.4

     28
     317,746,000
     March 24, 2014
     4.44

     29
     249,866,000
     July 1, 2013
     3.49

     30
     201,032,714
     July 1, 2013
     2.81

     31
     1,363,480,000
     March 24, 2014
     19.1

     32
     1,241,900,000
     March 24, 2014
     17.4

     33
     317,746,000
     March 24, 2014
     4.44

     34
     249,866,000
     July 1, 2013
     3.49

     35
     201,032,714
     July 1, 2013
     2.81

     36
     1,363,480,000
     March 24, 2014
     19.1

     37
     1,241,900,000
     March 24, 2014
     17.4

     38
     317,746,000
     March 24, 2014
     4.44

     39
     249,866,000
     July 1, 2013
     3.49

     40
     201,032,714
     July 1, 2013
     2.81

     41
     1,363,480,000
     March 24, 2014
     19.1

     42
     1,241,900,000
     March 24, 2014
     17.4

     43
     317,746,000
     March 24, 2014
     4.44

     44
     249,866,000
     July 1, 2013
     3.49

     45
     201,032,714
     July 1, 2013
     2.81

     46
     1,363,480,000
     March 24, 2014
     19.1

     47
     1,241,900,000
     March 24, 2014
     17.4

     48
     317,746,000
     March 24, 2014
     4.44

     49
     249,866,000
     July 1, 2013
     3.49

     50
     201,032,714
     July 1, 2013
     2.81

     51
     1,363,480,000
     March 24, 2014
     19.1

     52
     1,241,900,000
     March 24, 2014
     17.4

     53
     317,746,000
     March 24, 2014
     4.44

     54
     249,866,000
     July 1, 2013
     3.49

     55
     201,032,714
     July 1, 2013
     2.81

     56
     1,363,480,000
     March 24, 2014
     19.1

     57
     1,241,900,000
     March 24, 2014
     17.4

     58
     317,746,000
     March 24, 2014
     4.44

     59
     249,866,000
     July 1, 2013
     3.49

     60
     201,032,714
     July 1, 2013
     2.81

________________________________________________________
Utilizando as funções jspdf e html2canvas é possivel criar um PDF sem perder as propriedades do CSS.
Porém deve-se ficar atento ao fluxo da criação do pdf.
A ideia é criar uma imagem do html usando html2canvas e posteriormente usar a hash(imagem) criada para criar o pdf usando jspdf.
Como o formato padrão do pdf é no formato a4, temos que redefinir a largura da div para o formato a4 e após a criação do pdf, voltar ao CSS normal.
Primeiramente importar os js nessa ordem e após o jquery:

*

*1º http://cdn.rawgit.com/MrRio/jsPDF/master/dist/jspdf.min.js

*2º    http://html2canvas.hertzen.com/build/html2canvas.js
Definir um id a div que será renderizada.
Exemplo:

Basic Panel

A Basic Panel

Partindo para o JavaScript...


text:
Q: PySpark dynamic like operations I have a PySpark dataframe like this:
data = [{"ID": 1, "Value": 3478},
        {"ID": 2, "Value": 10},
        {"ID": 3, "Value": 3323},
        {"ID": 1, "Value": 2300},
        {"ID": 2, "Value": 40},
        {"ID": 3, "Value": 93},
        {"ID": 1, "Value": 500},
        {"ID": 2, "Value": 50},
        {"ID": 3, "Value": 73}]

df = spark.createDataFrame(data)
df.show(20, False)
# +---+-----+
# |ID |Value|
# +---+-----+
# |1  |3478 |
# |2  |10   |
# |3  |3323 |
# |1  |2300 |
# |2  |40   |
# |3  |93   |
# |1  |500  |
# |2  |50   |
# |3  |73   |
# +---+-----+

I have another Spark dataframe like this:
final_data = [{"ID": 1, "Value": 1234563478},
              {"ID": 2, "Value": 2134510},
              {"ID": 3, "Value": 789033323}]

final_df = spark.createDataFrame(final_data)
final_df.show(5, False)
# +---+----------+
# |ID |Value     |
# +---+----------+
# |1  |1234563478|
# |2  |2134510   |
# |3  |789033323 |
# +---+----------+

Now my requirement is to filer final_df based on df values.
from pyspark.sql import functions as F

final_df.filter(F.col("ID") == "1").where(F.col("Value").like('%3478%') | F.col("ID").like('%2300%') | F.col("ID").like('%500%')).show(5, False)
# +---+----------+
# |ID |Value     |
# +---+----------+
# |1  |1234563478|
# +---+----------+

Here from the df values I have manually passed as value to like condition.
Is there a dynamic way to call the value of df in final_df. Today I have only 3 values for matching id == 1, tomorrow I might have 10 values. How to set dynamically like conditions in PySpark dataframe?

A: Not sure what you really expect. Lets try use lists and fstring if you are after declaring variables and having them dynamically picked. If not what you are after, let me know.
s='3478'
s1 ='2300'
s2 ='500'
lst=['1']
from pyspark.sql import functions as F

final_df.filter(F.col("ID").isin(lst)).where(F.col("Value").like(f'%{s}%') | F.col("ID").like(f'%{s1}%')| F.col("ID").like(f'%{s2}%')).show(5,False)

A: You may need some python to create a filter with many dynamic conditions. I assume your df is relatively small, so I use collect
filter_list = df.groupBy('ID').agg(F.collect_set('Value').alias('vals')).collect()
row_filter = []
for r in filter_list:
    s = f"ID={r['ID']} AND "
    s += '(' + ' OR '.join([f"Value LIKE '%{v}%'" for v in r['vals']]) + ')'
    row_filter.append(s)
final_df.filter(f"({') OR ('.join(row_filter)})").show()

The following must work in Python 2.7, I think.
filter_list = df.groupBy('ID').agg(F.collect_set('Value').alias('vals')).collect()
row_filter = []
for r in filter_list:
    s = "ID=" + str(r['ID']) + " AND "
    s += '(' + ' OR '.join(["Value LIKE '%" + str(v) + "%'" for v in r['vals']]) + ')'
    row_filter.append(s)
final_df.filter("(" + ") OR (".join(row_filter) + ")").show()


text:
Q: suds.WebFault: Server raised fault: 'org.xml.sax.SAXException: Invalid type: employees' I am new to netsuite and I have to integrate the netsuite my current application. I have written the following code to login into the netsuite sandbox environment and create a new data entry into the database.
from suds.client import Client
import os, time, sys, datetime
import suds
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger('suds.client').setLevel(logging.DEBUG)

reload(sys)
sys.setdefaultencoding('utf8')

NS_HOST = 'https://webservices.sandbox.netsuite.com'
email ='utkarsh.sharma@ABCD.com'
pwd   ='ABCDEFGHI!'
account = "3828138"
NS_ENDPOINT = "2017_1"
NS_ROLE = 25

wsdl = 'https://webservices.sandbox.netsuite.com/wsdl/v2017_1_0/netsuite.wsdl'

client = Client(url=wsdl)
ApplicationInfo = client.factory.create('ns16:ApplicationInfo')
ApplicationInfo.applicationId = "A8C51D62-63FC-42DC-AE13-B1B971F41C47"

client.set_options(location= NS_HOST + "/services/NetSuitePort_" +
NS_ENDPOINT, soapheaders={'applicationInfo':ApplicationInfo})

passport = client.factory.create('ns4:Passport')
passport.email = email
passport.password = pwd
passport.account = account

loginResponse = client.service.login(passport,_soapheaders=
{'applicationInfo': ApplicationInfo})

print('Login Response: ')
print (loginResponse.status)

recordRef = client.factory.create('ns4:RecordRef')
recordRef._internalId = 123456789
recordRef._type = 'employees'
record = client.service.get(recordRef)
print (record)

I can login but while trying to post the data, I am facing the following error.
suds.WebFault: Server raised fault: 'org.xml.sax.SAXException: Invalid type: employees'

Any kind of help is welcomed. Thanks in advance.

A: The record type should be singular.  Try setting recordRef.type = 'employee', not 'employees'.  Record types will usually be the singular version like, invoice, salesorder, customer, vendor.


text:
Q: adding namespace to xpath I have classes full of xpaths that now needs a specfic namespace.  How can I accomplish this?  What would be the easiest way to refactor this code?  find replace?
What would be the best way to grab specific nodes in the future, if I don't know the namespaces ahead of time?
susr1 = root.SelectSingleNode("/PurchaseOrderRequest/DocumentHeader/DocumentInformation/DocumentIdentification/Type");

susr1 = root.SelectSingleNode("/PurchaseOrderRequest/ssdh:DocumentHeader/ssdh:DocumentInformation/ssdh:DocumentIdentification/ssdh:Type");

A: You can try this XML Library.  Use XPathElement().  This is a .Net 3.5 solution if you can use it.
XElement root = XElement.Load(file) or .Parse(string)

Then either of your xpath's should work as long as there are not conflicting nodes with the same name (but different namespaces).
XElement susr1 = root.XPathElement("/PurchaseOrderRequest/DocumentHeader/DocumentInformation/DocumentIdentification/Type");

XElement susr1 = root.XPathElement("/PurchaseOrderRequest/ssdh:DocumentHeader/ssdh:DocumentInformation/ssdh:DocumentIdentification/ssdh:Type");

The library should figure out the namespace for you.  I cannot test it without example xml to be sure.


text:
Q: can one predict variable using scikit-learn rather binary classification if yes than how I am working in the field of Pharmaceutical sciences, I work on
chemical compounds and with calculating their chemical properties or descriptors we can predict certain biological function of that compounds. I use python and R programming language for the same and also use Weka machine learning tool. Weka provides facility for binary prediction using SVM and other supporting algorithms.
Ex data set: Training set
Chem_ID   MW LogP HbD HbE IC50 Class_label
  001    232  5    0   2    20    0
  002    280  2    1   4    41    1
  003    240  5    0   2    22    0
  004    300  4    1   5    48    1
  005    245  2    0   2    24    0
  006    255  1    0   2    20    0
  007    299  5    1   4    49    1

Test set
Chem_ID  MW   LogP HbD HbE IC50 Class_label
    000   255  1    0   2    20

In weka there are few algorithm with them we can predict the "class_label" or we can also predict specific variable (we usually predict "IC50" values ), does scikit-learn or any other machine learning library in python  having that capabilities. if yes how can we use it thanks.

A: Yes, this is a regression problem. There are many different models to solve a regression problem, from a simple Linear Regression, to Support Vector Regression or Decision Tree Regressors (and many more).
They work similarly to binary classifier: You give them your training data and instead of 0/1 labels you give them target values to train. In your case you would take the feature you want to predict as target value and delete it form the training data.
Short example:
target_values = training_set['IC50']
training_data = training_set.drop('IC50')

clf = LinearRegression()
clf.fit(training_data, target_values)

test_data = test_set.drop('IC50')

predicted_values = clf.predict(test_data)


text:
Q: Unity3D IP Camera I'm using a Marmitek IP RoboCam 641 to import a video feed into unity. I use constantly refreshing snapshots to update a GUI.DrawTexture on the screen. However I recently switched to the Marmitek from a Velleman wireless ip colour camera. Now my snapshot only refreshes once or twice, before stopping and giving this error:
UnityException: Recv failure: Connection was reset
SEMTEX+c__Iterator0.MoveNext () (at Assets/Scripts/SEMTEX.cs:37)
And this is my code:
using UnityEngine;
using System.Collections;

public class SEMTEX : MonoBehaviour {

//public string uri = "http://192.168.1.101/snapshot.cgi";//velleman
public string uri = "http://192.168.1.30/cgi/jpg/image.cgi";//marmitek
public string username = "admin";
public string password = "admin";
int calc = 0;

Texture2D cam;
Texture2D cam2;

public void Start() {
    cam=new Texture2D(1, 1, TextureFormat.RGB24, true);
    StartCoroutine(Fetch());
    cam2=new Texture2D(1, 1, TextureFormat.RGB24, true);
    StartCoroutine(Fetch());
}

public IEnumerator Fetch() {
    while(true) {
        Debug.Log("fetching... "+Time.realtimeSinceStartup);

        WWWForm form = new WWWForm();
        form.AddField("dummy", "field");    // required by WWWForm
        WWW www = new WWW(uri, form.data, new System.Collections.Generic.Dictionary<string,string>() {  // using www.headers is depreciated by some odd reason
            {"Authorization", "Basic " + System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(username+":"+password))}
        });
        yield return www;

        if(!string.IsNullOrEmpty(www.error))
            throw new UnityException(www.error);

        www.LoadImageIntoTexture(cam);
        www.LoadImageIntoTexture(cam2);
    }
}

public void OnGUI() {
    GUI.DrawTexture(new Rect(0,0,Screen.width/2,Screen.height), cam);

    calc = (Screen.width/2-100);

    GUI.DrawTexture(new Rect(calc,0,Screen.width/2,Screen.height), cam2);
    Debug.Log (Screen.width);
}

Does anyone have any ideas regarding my error?


text:
Q: Saving datetime string to DateTimeField returns validation error I'm trying to save this value 2013-05-01T00:00:00.000+02:00 to a DateTimeField in django, but I get a validation error on save.
What could be wrong?
Here is Model,
class Entry(models.Model):
            name = models.CharField(max_length=500, )
            published = models.DateTimeField(blank=True, null=True)

--
@task()
def import_entry_from_xml(data):
    #Import function
    entry = Entry(name=values['name'])
    if hasattr(data, 'published'):
          entry.published = data['published'] #Returns 2013-05-01T00:00:00.000+02:00
    entry.save()

Error:
ValidationError: [u"'' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]

A: DateTimeFields expect a Python datetime object, not a string. Use strptime to convert your string into a datetime.
The hasattr call is almost certainly wrong, too. If you want to see if published is in your data dictionary, use if 'published' in data:


text:
Q: How to implement caching using etag in Angular 6? Is there a sample code on how to implement HTTP caching using etag header in Angular 6? I read the angular-http-etag but it's not that clear for me. I want to cache a resource (get/post request result). Example of API https://api.icndb.com/jokes/3?escape=javascript
I want to be able to call a same API, e.g. /jokes/3, through a HttpClient.get() from different places. If the cache has not expired then I want to take the local cache instead of fetching from the remote database again, unless the get parameter or post body has changed, e.g. /jokes/4.
The package angular-http-etag weekly download is around 100 and I haven't been able to find an example using the package in angular 2+.
(Another alternative I read is the caching through RxJS sharedReply)
Thanks.


text:
Q: Can't use Express to send data back to client more than once In my app, I send a post request to the server with data containing a CSV file:
$.ajax({
  type:"POST",
  contentType: "application/json",
  url:"/",
  data: JSON.stringify({fileData:My_CSV_FILE}),
  success: function(csvJson) {
    console.log('in the done block!');
    //can use csvJson in this handler
   });
});

Note: I'm posting to the home route, and I am able to get a response with the data converted from the server. The problem is that whether I run on localhost or Heroku, I am only able to trigger the POST request once, then I have to restart the server (even if I refresh the page). So I know the issue is with my route somewhere:
UPDATED TO INCLUDE FULL SERVER FILE:
    'use strict';
const express = require('express');
const csvtojson = require('csvtojson');
const PORT = process.env.PORT || 3000;
const bodyParser = require('body-parser');
const Converter = require('csvtojson').Converter;

var converter = new Converter({});
let app = express();

app.use(bodyParser.json({limit: '300kb'}));

app.use(express.static(__dirname +'/public'));

app.post('/',function(req,res) {
  var csvFile = (req.body.fileData);
  converter.fromString(csvFile, function(err, result) {
    if(!err) {
      console.log(result);
      res.json(result);
    }else {
      res.json({error: 'Could not convert'});
    }
  })
});

app.listen(PORT, () => {
  console.log(`app listening on port ${PORT}`);
});

I'm using Express 4. Again, everything works, but only once. When I run Heroku logs, or check the console on localhost I get:
 Error: Can't set headers after they are sent.

But I don't understand how I'm re-setting them.
If wanting to run on localhost, here is a link to the projects github: https://github.com/qctimes/calendar_export

A: You should move the converter instantiation to be done inside the app.post callback method. This way it will instantiate a new object at every request.
This is is how your code should be:
'use strict';
const express = require('express');
const csvtojson = require('csvtojson');
const PORT = process.env.PORT || 3000;
const bodyParser = require('body-parser');
const Converter = require('csvtojson').Converter;

let app = express();

app.use(bodyParser.json({limit: '300kb'}));

app.use(express.static(__dirname +'/public'));

app.post('/',function(req,res) {
  var csvFile = (req.body.fileData);
  var converter = new Converter({}); // instantiation is done here
  converter.fromString(csvFile, function(err, result) {

    if(!err) {
      console.log(result);
      res.send(result);
    }else {
      res.send({error: 'Could not convert'});
    }
  });
});

app.listen(PORT, () => {
  console.log(`app listening on port ${PORT}`);
});


text:
Q: Implicit Internal Intent vulnerability showing up when Android app is deployed to the Playstore Recently I have uploaded my android apk on the app store and its been told that the next upload to Google play store will get rejected and we need to check and resolve it. Below is the screenshot of the message:

They are referring to package name also. Below is the code:
 @Override
    public void onDestroy() {
        cleanup();
        super.onDestroy();
        Intent intent = new Intent("com.test.dummyapp");
        sendBroadcast(intent);
    }

Please assist me how to resolve this.
Below is the code where the component is triggered:
 IntentFilter restartFilter = new IntentFilter("com.test.dummyapp");
        registerReceiver(restartBroadcastReciver, restartFilter);

private BroadcastReceiver restartBroadcastReciver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          doBindService();
        }
    };

A: When you do this, you are broadcasting an "implicit Intent". This is dangerous because any app can register to get this (potential leak of information) and any app can also broadcast this Intent (triggering your app).
Intent intent = new Intent("com.test.dummyapp");
sendBroadcast(intent);

To fix this you can use LocalBroadcastManager (it is deprecated, but still works). Using a local broadcast ensures that other apps cannot see your broadcast Intent and other apps cannot trigger your app this way.
See https://developer.android.com/reference/androidx/localbroadcastmanager/content/LocalBroadcastManager

As an alternative, you should be able to make the Intent explicit by setting the package name:
Intent intent = new Intent("com.test.dummyapp");
intent.setPackage("my.package.name");
sendBroadcast(intent);

A: It seems really weird to send a Broadcast in onDestroy.  I can't possibly see a use for that, and I can see a lot of problems due to onDestroy being called unexpectedly (rotation, screen size change, etc).
But if you have to do it, use new Intent(getPackageName()).  What they're looking for is a hardcoded package name like that.  The problem is that if you run 'com.facebook.whateveritscalled' and a piece of malware is installed that named itself that, you would be sending the intent to it.  Which if you have extras in the intent could be leaking information to it.

A: Thanks for the information.
I made some changes to the posted code. Let me know if this works fine.
@Override
public void onDestroy() {
    cleanup();
    super.onDestroy();
    openApp((Context) context,"com.test.dummyapp");
}

public static boolean openApp(Context context, String packageName) {
    PackageManager manager = context.getPackageManager();
    try {
        Intent i = manager.getLaunchIntentForPackage(packageName);
        if (i == null) {
            return false;
        }
        i.addCategory(Intent.CATEGORY_LAUNCHER);
        context.sendBroadcast(i);
        return true;
    } catch (ActivityNotFoundException e) {
        return false;
    }
}


text:
Q: How to convert numeric to strings in the box plot I want to plot the boxplot of the following dataset :
A = [150, 112, 108, 70]
B = [260, 90, 165, 100]
C = [160, 50, 90, 60]
D = [110, 20, 35, 70]
E = [105, 450, 45, 200]

One way I can do it is via the following code:
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
font_prop = font_manager.FontProperties( size=18)

Positions = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5]
Heat = [150, 112, 108, 70, 260, 90, 165, 100, 160, 50, 90, 60, 110, 20, 35, 70, 105, 450, 45, 200]

groups = [[] for i in range(max(Positions))]
[groups[Positions[i]-1].append(Heat[i]) for i in range(len(Heat))];

b = plt.boxplot(groups, patch_artist=False);
plt.rcParams.update({'font.size': 16})
plt.rc ('xtick', labelsize=16)
plt.rc ('ytick', labelsize=18)

for median in b['medians']:
    median.set(color = 'r', linewidth = 2)

I can get the following box plot but I want the numbers 1...5 to be replaced by A...E? Is there an alternative way I can do this?

A: To convert a char to an integer, use
ord(char)

To convert an integer to a char, use
chr(int)

An example:
int_array = list(range(5))
char_array = [chr(x + ord('A')) for x in int_array]
# char_array = ['A', 'B', 'C', 'D', 'E']


text:
Q: Inserting new data into a SQLite database using Terminal? I am trying to insert data into a SQLite database that is used for a Rails application.
I initially thought I could have used SQLite manager and insert into tablename (value) values ('value') however, it did not insert anything into the table and did not produce an error.
Am I doing anything wrong? Is there a way to do this directly with Rails?
I thought I could use some sort of activerecord migration and just rake db:migrate, however I have been unable to find the appropriate commands.

A: rails runner is a nice way to leverage the Rails runtime, without needing to load the entire Rails stack for your application. It'll give you the full ActiveRecord resources for your underlying DB, making it easy to do database operations.
From the runner built-in help:

rails runner
Usage: runner [options] ('Some.ruby(code)' or a filename)

    -e, --environment=name           Specifies the environment for the runner to operate under (test/development/production).
                                     Default: development

    -h, --help                       Show this help message.

You can also use runner as a shebang line for your scripts like this:
-------------------------------------------------------------
#!/usr/bin/env /Users/greg/junk/foo/script/rails runner

Product.all.each { |p| p.price *= 2 ; p.save! }

I've used this several times for jobs that loaded data underneath Rails into the database. It'd be a great solution for what you need to do.
"Rails task: script/runner or rake?" is worth reading too for more information.


text:
Q: Eclipse 3.5 load time and other performance improvement I am using eclipse 3.5 Galileo enterprise edition for development of java standalone applications.I have disabled few plugins in startup.Still i am not quite happy with the IDE performance.Are there any more feature disable or configurations to make it work faster?
Please tel me if further information is required to answer this,i will update the question:)

A: I created a RAM disk and placed key files such as the JDK and Eclipse plugin directory on the RAM disk.  That improved Eclipse 3.5 performance very significantly.
You can read about it here.

A: You can improve performance by tuning your eclipse.ini file. Here's an example file with some tuning options added:
-startup
plugins\org.eclipse.equinox.launcher_1.0.101.R34x_v20080819.jar
--launcher.XXMaxPermSize
256m
-vmargs
-Xms256m
-Xmx512m
-XX:PermSize=256m
-XX:MaxPermSize=256m
-XX:+AggressiveOpts
-XX:+StringCache
-XX:+UseFastAccessorMethods
-XX:+UseLargePages
-XX:LargePageSizeInBytes=4m
-XX:AllocatePrefetchLines=1
-XX:AllocatePrefetchStyle=1
-Dide.gc=true

I would do some research and testing to work out which settings work best for you. There's some information here that might help with this.


text:
Q: Retrieving a value from an XDocument I have an XDocument called doc which consists of:
<bar>
  <foo>
    <item address="123">CCC</item>
  </foo>
  <definitions>
    <item address="123">AAA</item>
    <item address="456">BBB</item>
  </definitions>
</bar>

I'd like a simple linq query (preferably with lambda expression) that given 123 the expression will return AAA
I suspect I want to use doc.Descendants("definitions"), but I'm not sure how to implement the lambda clause.  Actually, it would be nice to see both lambda and a where clause just to compare the two.

A: IEnumerable<string> childList =
    from el in doc.Element("bar").Element("definitions").Elements()
    where el.Attribute("address").Value == "123"
    select el.Value;

If you need to extract values from within elements of different names, I suggest you to use XMLReader rather than XDocument. Performance wise XMLReader is better as it doesn't parse the complete document unlike XDocument.
List<string> values = new List<string>();
using (StringReader sr = new StringReader(stringXML))
using (XmlReader xr = XmlReader.Create(sr))
{
    while (xr.Read())
    {
        if (xr.NodeType == XmlNodeType.Element && xr.Name == "item" && xr.GetAttribute("address") == "123" )
        {
            values.Add(xr.GetAttribute("address"));
        }
    }
}

A: You need to use also the XElement.Attribute property. I would create an extension method that looks like this:
public static class ProjectExtensions
{
    public static String GetValue(this XDocument source, String name, String value)
    {
        //          return source
        //                      .Root
        //                      .Element(name)
        //                      .Elements("item")
        //                      .Where (f => f.Attribute("address").Value == value)
        //                      .FirstOrDefault()
        //                      .Value;
        // or alternative
        var result = (from e in source.Root.Element(name).Elements("item")
                    where e.Attribute("address").Value == value
                    select e.Value).FirstOrDefault();
        return result;
    }
}

Then the usage looks like this:
var xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
<bar>
    <foo>
        <item address=""123"">AAA foo</item>
    </foo>
    <definitions>
        <item address=""123"">AAA definition</item>
        <item address=""456"">BBB</item>
    </definitions>
</bar>";

try
{
    var document = XDocument.Parse(xml);
    Console.WriteLine(document.GetValue("foo", "123"));
    Console.WriteLine(document.GetValue("definitions", "123"));
}
catch (Exception exception)
{
    Console.WriteLine(exception.Message);
}

The output is:
AAA foo
AAA definition

Consider adding exception handling and checks to prevent errors. The LINQ fluent and query syntax are in this case (almost) identical.


text:
Q: ArcPy Get Value of Field for Selected Record I am building a script to populate a field in one feature class based on a field in another feature class.  First I have a leases layer which is all small polygons.  Then I have an index grid layer which is large polygons.  I want to know which leases exist within which index grid polygon.  The index grid layer has an "Id" field, and I want the Id value from the index grid that each lease exists within to be written to a new column in the leases layer.
For example, index grid polygon with an 'Id' of '7' contains leases '14' '6' and '12'.  The final result should be a column where lease 14, 6, and 12 all have a value of '7' in the new column.
Here is what I have so far:
import arcpy, sys

grid = arcpy.GetParameterAsText(0)
leases = arcpy.GetParameterAsText(1)
workspace = arcpy.GetParameterAsText(2)
new_field = arcpy.GetParameterAsText(3)

if arcpy.ListFields(leases, new_field):
    sys.exit(arcpy.AddError("Error:Field Already exists"))

arcpy.AddField_management(leases, new_field, 'SHORT', '', '', '')

grid_lyr = arcpy.MakeFeatureLayer_management(grid, 'grid_lyr')
leases_lyr = arcpy.MakeFeatureLayer_management(leases, 'leases_lyr')

fields = ['file',new_field]
with arcpy.da.UpdateCursor(leases_lyr,fields) as cur:
    for row in cur:

        leases = row[0]
        where = '"file" = \'{}\''.format(leases)
        arcpy.SelectLayerByAttribute_management(leases_lyr, 'NEW_SELECTION', where)

        arcpy.SelectLayerByLocation_management(grid_lyr, 'CONTAINS', leases_lyr)
        map_no =  #I think this is all that is missing

        row[1] = map_no
        cur.updateRow(row)

The value 'map_no' represents the index grid Id which the lease belongs to.
As I have a comment in my code, I think there is only one line that is missing...in the original script which this is derived from, this line uses the arcpy.GetCount_management, but obviously it needs to be something different.  It just needs to be some kind of get value function, but I simply cannot figure it out.
I derived this work so far from a script that counts the number of points in in a polygon, and then writes that value to a new column in the polygon layer.  I mention this because maybe there is a better solution.
Using ArcMap 10.1.

A: Going to assume that not all grids contain leases and that grids completely contain leases. No need to make the "in_memory" feature class if all grids will be used. If some leases overlap grids, you will only get the last grid id value.
import arcpy, sys

grid = arcpy.GetParameterAsText(0)
leases = arcpy.GetParameterAsText(1)
workspace = arcpy.GetParameterAsText(2)
new_field = arcpy.GetParameterAsText(3)

if arcpy.ListFields(leases, new_field):
    sys.exit(arcpy.AddError("Error:Field Already exists"))

arcpy.AddField_management(leases, new_field, 'SHORT', '', '', '')

grid_lyr = arcpy.MakeFeatureLayer_management(grid, 'grid_lyr')
leases_lyr = arcpy.MakeFeatureLayer_management(leases, 'leases_lyr')

fields = ['file',new_field]
arcpy.SelectLayerByLocation_management(grid_lyr, "CONTAINS", leases_lyr)
arcpy.FeatureClassToFeatureClass_conversion(grid_lyr, "in_memory", "gridsWithLeases")
gridsWithLeases = r"in_memory/gridsWithLeases"
arcpy.MakeFeatureLayer_management(gridsWithLeases, 'gridLease_lyr')
with arcpy.da.SearchCursor('gridLease_lyr', ['ID']) as gridCursor:
    for gridRow in gridCursor:
        arcpy.SelectLayerByLocation_management(leases_lyr, "WITHIN", 'gridLease_lyr')
        with arcpy.da.UpdateCursor(leases_lyr, fields) as leaseCursor:
            for leaseRow in leaseCursor:
                leaseRow[1] = gridRow[0]
                leaseCursor.updateRow(leaseRow)

A: The solution is to use the Spatial Join (Analysis) Tool.
Use the index grid as the target feature and the leases as the join feature.
Enter the output Feature Class.
Select one to many relationship.
Join type - keep all.
Leave field mapping as is or remove unnecessary fields (it is only necessary to keep the 'index grid id' field as this will be the final result).
Lastly, select the join operator 'CONTAINS'.
The link above also shows how to access this tool using arcpy if desired.


text:
Q: perl regex to get params string from functions I have a document containing 100's of lines as show below.
 fn:concat(xs:float("-3.4028235E38"),xs:float("3.4028235E38"))
 fn:concat(xs:int("-1873914410"),xs:int("-2147483648"))
 fn:concat(xs:int("-1873914410"))

I'd like to get something like this
fn.concat(-3.4028235E38,3.4028235E38);
fn.concat(-1873914410,-2147483648);
fn.concat(-1873914410);

Thank you. Your time is appreciated!

A: in a quick and dirty one liner
perl -i -pe 's/\bxs:(?:float|int)\("(.*?)"\)/$1/g; s/(?<=\w):(?=\w)/./g;' file


text:
Q: AIMLbot Input string was not in a correct format. C# I try to make an artificial engine with AIMLbot in C#, but when I say the first word the program breaks and I get the following error:

Exception User-Unhandled System.FormatException: 'Input string was not
  in a correct format'

at the line
Result result = bot.Chat(request);

The code with the error:
private void Rec(object s, SpeechRecognizedEventArgs e)
{
    string speech = e.Result.Text;
    //richTextBox1.Text = "You: " + speech + Environment.Newline;

    richTextBox1.AppendText("You: " + speech + Environment.Newline);
    Request request = new Request(speech, user, bot);
    Result result = bot.Chat(request);

    richTextBox1.AppendText("AIDA" + result.RawOutput + Environment.Newline + Environment.Newline);
}

I really need some help :))

A: Your error

Input string was not in a correct format

Tells you that you have something expecting a string but you are not passing it in a string.  The exact line that this is failing on tells you that it is
request

that is not a string when you are passing into bot.Chat(request)
You have declared it as a Request thus it is not a string, however it may be null so if you put a break point on that line, debug and step through the code you can inspect the value of request and see what it is.
Hope this helps


text:
Q: How do I calculate how much weight is needed to sink a specific amount of air and for how deep will it sink? Understanding buoyancy
I'm trying to understand buoyancy so I created a question that should help me greatly.
To keep this simple my above is a photo is of a 20 ft long tank. Each line represents 1 cubic ft which each holds 62 lb of water. To get specific this full tank would be:
1' x 1' x 20 ' and would hold a total of 1,240 lb of water as each line is 1' x 1' x 1'.
The question is how do I calculate how much weight is needed to sink a specific amount of air? Also how do I calculate how far it would sink considering water pressure increases by depth. I'd like to find the MAXIUMUM amount of air I could sink with the LEAST amount of weight to be at least beyond 11 ft deep.
We can start with this example photo where I've made the section of air 30 % of 1 cubic foot and the other 70% is just of weight.
THIS IS A CLOSED CHAMBER which would be:

3.6" x 3.6" x 3.6" = .03 cubic ft = AIR           (PINK)
8.4" x 8.4" x 8.4" = .07 cubic ft = WEIGHT = 43.4 lb  (GREEN)

In theory this wouldn't be enough air to even lift that amount of weight so I'd assume that It would sink until it remains still due to water pressure at a specific depth.

A: If your sample of air were in a container open at the bottom with extra weights attached, sinking would require that the total weight of the air, container, and weights must exceed the weight of the water displaced by all three.  Once submerged, the volume of the air would start to decrease and the system would continue to sink.  If the air were in a sturdy closed container, very little compression would occur with a moderate increase in depth.

A: Buoyancy does not really change with depth (water temperature differences can slightly change it's density). Once a sealed container weighed more than the water it displaced (negative buoyancy), it would begin to sink and go to the bottom. If it weighed less than the amount of water it displaced (positive buoyancy) it will float. So to decide if your container will sink or float, find it's outer volume (that is the amount of water it will displace), find the weight of that volume of water, if the sealed container's total weight is more than the weight of the same volume of water, it will sink to the bottom. If it is lighter than the water it will float. Neutral buoyancy, where it weighs the same as the water, and will neither sink or float, is an unstable condition.


text:
Q: sorting sections of text file content with ms-dos commands I have a bunch of configuration files which I want to sort their content.  The file has sections in it, like the example below.
First, I need to sort the sections.  Then, I need to sort the lines in each section.
I am looking for some hints on how to do this automatically with batch of ms-dos commands.
What are the main steps?  Which commands to be used?
I will be grateful for your hints.
Thank you.
[DEF]
ITY=YES
WEKTY=NO
WKEOW=50
ADFGG=3
SDF=YES

[ABC]
KASDF=AB
WERY=59
KAKSDOE=YES
ABEE=NO
PTOP=MAX
WWQ=98

...and so on