Q: Arduino IDE is able to use avrdude to flash hex file, but command line on ubuntu is unable to Good day all,
I have an arduino pro micro (Chinese knock off version) with which I am able to flash to with the arduino IDE but I am unable to recreate the same effect with avrdude in the terminal on Ubuntu 16.04
This is what I have observed from the verbose output on the arduino IDE:
Forcing reset using 1200bps open/close on port /dev/ttyACM0
PORTS {/dev/ttyACM0, } / {} => {}
PORTS {} / {/dev/ttyACM0, } => {/dev/ttyACM0, }
Found upload port: /dev/ttyACM0
/home/philip/Desktop/arduino-1.8.5/hardware/tools/avr/bin/avrdude -C/home/philip/Desktop/arduino-1.8.5/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/ttyACM0 -b57600 -D -Uflash:w:/tmp/arduino_build_182426/strandtest.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 11:00:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "/home/philip/Desktop/arduino-1.8.5/hardware/tools/avr/etc/avrdude.conf"
     User configuration file is "/home/philip/.avrduderc"
     User configuration file does not exist or is not a regular file, skipping

     Using Port                    : /dev/ttyACM0
     Using Programmer              : avr109
     Overriding Baud Rate          : 57600
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

    Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader
Connecting to programmer: .
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.

Programmer supports the following devices:
    Device code: 0x44

avrdude: devcode selected: 0x44
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9587 (probably m32u4)
avrdude: reading input file "/tmp/arduino_build_182426/strandtest.ino.hex"
avrdude: writing flash (5918 bytes):

Writing | ################################################## | 100% 0.45s

avrdude: 5918 bytes of flash written
avrdude: verifying flash memory against /tmp/arduino_build_182426/strandtest.ino.hex:
avrdude: load data flash data from input file /tmp/arduino_build_182426/strandtest.ino.hex:
avrdude: input file /tmp/arduino_build_182426/strandtest.ino.hex contains 5918 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.05s

avrdude: verifying ...
avrdude: 5918 bytes of flash verified

avrdude done.  Thank you.

Which I have done my best to replicate by using this code:
stty -F /dev/ttyACM0 speed 1200
stty -F /dev/ttyACM0 speed 57600
/home/philip/Desktop/arduino-1.8.5/hardware/tools/avr/bin/avrdude -v -p m32u4 -C /home/philip/Desktop/arduino-1.8.5/hardware/tools/avr/etc/avrdude.conf -c avr109 -P /dev/ttyACM0 -b 57600 -D -U flash:w:layout.hex

To the extent of using the same avrdude file and configuration as the IDE
However, when I do it this way, I face the following error:
/home/philip/Desktop/arduino-1.8.5/hardware/tools/avr/bin/avrdude -v -p m32u4 -C /home/philip/Desktop/arduino-1.8.5/hardware/tools/avr/etc/avrdude.conf -c avr109 -P /dev/ttyACM0 -b 57600 -D -U flash:w:layout.hex

avrdude: Version 6.3, compiled on Jan 17 2017 at 11:00:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/home/philip/Desktop/arduino-1.8.5/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/philip/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

**Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
Found programmer: Id = ""; type =
    Software Version =  .; Hardware Version = .
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?**
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: leave prog mode
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: exit bootloader

So my question is, why is the Arduino IDE able to detect the type of programmer when the exact same avrdude executable is run through the terminal and yet is unable to flash the hex file?
My best bet is that it has something to do with the forced reset using the baud rate and that the arduino IDE is doing it differently from me, but I am unsure of what I need to change
Any help is greatly appreciated! Thank you.

A: Darn I fixed it within 5 seconds of posting the question, heres how I did it
Instead of using the baud rate to reset it I pressed the reset switch and run the exact same code
So the error is here
stty -F /dev/ttyACM0 speed 1200
stty -F /dev/ttyACM0 speed 57600

But I am not sure what exactly about it is wrong, and clarification would be appreciated anyway :)


Q: Is search speed achieved with fast data access or fast index access? From MySQL doc:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
    (create_definition,...)
    {DATA|INDEX} DIRECTORY [=] 'absolute path to directory'

My table is for search only and takes 8G of disk space (4G data + 4G index) with 80M rows
I can't use ENGINE = Memory to store the whole table into memory but I can store either the data or the index in a RAM drive through the DIRECTORY table options
From a theorical knoledge, is it better to store the data or the index in RAM?

A: MySQL's default storage engine is InnoDB. As you run queries against an InnoDB table, the portion of that table or indexes that it reads are copied into the InnoDB Buffer Pool in memory. This is done automatically. So if you query the same table later, chances are it's already in memory.
If you run queries against other tables, it load those into memory too. If the buffer pool is full, it will evicting some data that belongs to your first table. This is not a problem, since it was only a copy of what's on disk.
There's no way to specifically "lock" a table on an index in memory. InnoDB will load either data or index if it needs to. InnoDB is smart enough not to evict data you used a thousand times, just for one other table requested one time.
Over time, this tends to balance out, using memory for your most-frequently queried subset of each table and index.
So if you have system memory available, allocate more of it to your InnoDB Buffer Pool. The more memory the Buffer Pool has, the more able it is to store all the frequently-queried tables and indexes.
Up to the size of your data + indexes, of course.  The content copied from the data + indexes is stored only once in memory. So if you have only 8G of data + indexes, there's no need to give the buffer pool more and more memory.
Don't allocate more system memory to the buffer pool than your server can afford. Overallocating memory leads to swapping memory for disk, and that will be bad for performance.
Don't bother with the {DATA|INDEX} DIRECTORY options. Those are for when you need to locate a table on another disk volume, because you're running out of space. It's not likely to help performance. Allocating more system memory to the buffer pool will accomplish that much more reliably.

A:
but I can store either the data or the index in a RAM drive through the DIRECTORY table options...

Short answer: let the database and OS do it.
Using a RAM disk might have made sense 10-20 years ago, but these days the software manages caching disk to RAM for you. The disk itself has its own RAM cache, especially if it's a hybrid drive. The OS will cache file system access in RAM. And then MySQL itself will do its own caching.
And if it's an SSD that's already extremely fast, so a RAM cache is unlikely to show much improvement.
So making your own RAM disk isn't likely to do anything that isn't already happening. What you will do is pull resources away from the OS and MySQL that they could have managed smarter themselves likely slowing everything on that machine down.

What you're describing a micro-optimization. This is attempting to make individual operations faster. They tend to add complexity and degrade the system as a whole. And there are limits to how much optimizing you can do with micro-optimizations. For example, if you have to search 1,000,000 rows, and it takes 1ms per row, that's 1,000,000 ms. If you make it 0.9ms per row then it's 900,000 ms.
What you want to focus on is algorithmic optimization, improvements to the algorithm. These tend to make the code simpler and less complex, though often the data structures need to be more thought out, because you're doing less work. Take those same 1,000,000 rows and add an index. Instead of looking at 1,000,000 rows you'll spend, say, 100 ms to look at the index.
The numbers are made up, but I hope you get the point. If "what you want is speed", algorithmic optimizations will take you where no micro-optimization will.
There's also the performance of the code using the database to consider, it is often the real bottleneck using unoptimized queries, poor patterns for fetching related data, and not taking advantage of caching.
Micro-optimizations, with their complexities and special configurations, tend to make algorithmic optimizations more difficult. So you might be slowing yourself down in the long run by worrying about micro-optimizations now. Furthermore, you're doing this at the very start when you only have fuzzy ideas about how this thing will be used or perform or where the bottlenecks will be.
Spend your time optimizing your data structures and indexes, not minute details of your database storage. Once you've done that, if it still isn't fast enough, then look at tweaking settings.

As a side note, there is one possible benefit to playing with DIRECTORY. You can put the data and index on separate physical drives. Then both can be accessed simultaneously with the full I/O throughput of each drive.
Though you've just made it twice as likely to have a disk failure, and complicated backups. You're probably better off with an SSD and/or RAID.
And consider whether a cloud database might actually out-perform any hardware you might be able to afford.


Q: In a Rails 3 model, DateTime attributes are falsly "dirty" In my Rails 3 application, I only want to write an entry in a certain log if changes are actually made to a model. So if a user doesn't change any of the fields and clicks 'Submit', then there should not be a log entry.
But it seems that no matter what, Rails always seems to think that the DateTime attributes of the model have been changed.
When I debug, I run the following lines during my update and they both return true, which I would think would be a contradiction.
@request.begin_date == @request.begin_date_was  # Returns true
@request.begin_date_changed?  # Returns true

I'm wondering if it has something to do with changing the default date format in an initializer (to '%m/%d/%Y') or possibly something with time zones.
I'm stumped, so any help would be greatly appreciated.

A: You can change default date and time format in your en.yml locale file like this: (this is example for french format in one of my projects)
date:
 formats:
  default: "%d/%m/%Y"
  short: "%e %b"
  long: "%e %B %Y"
  long_ordinal: "%e %B %Y"
  only_day: "%e"
time:
 formats:
  default: "%d %B %Y %H:%M"
  time: "%H:%M"
  short: "%d %b %H:%M"
  long: "%A %d %B %Y %H:%M:%S %Z"
  long_ordinal: "%A %d %B %Y %H:%M:%S %Z"
  only_second: "%S"
 am: 'am'
 pm: 'pm'

Or you can simply convert your datetime instances to:
@request.begin_date.strftime("%m/%d/%Y") == @request.begin_date_was.strftime("%m/%d/%Y")
or even:
l(@request.begin_date, :format => your_format_in_locale_file) == l(@request.begin_date_was, :format => your_format_in_locale_file)
Hope it will help you

A: I realize when you asked, you were probably using a different Rails version, but I just stumbled upon this myself with Rails 3.2.5. Apparently its a regression in 3.2.5, too: https://github.com/rails/rails/issues/6591

A: I arrived here from a google search for a similar problem. It wasn't related to the Rails version, but I found out after some debugging that I was assigning a Time object with milliseconds. When calling changed, I got back and array of seemingly identical objects, since it got converted to DateTime's. Not sure if this can be considered a bug in Rails or not, but in case you end up with the same problem, check that you aren't assigning datetime's with milliseconds in them.


Q: Contrapositive, Converse and Inverse of statements with multiple quantifiers My textbook only touched on negation of statements with multiple quantifiers, and I would like to know:

*

*For a statement like
$\forall M>0, \exists \delta > 0$ such that if $0 < |x-a| < \delta$ then $|f(x)| > M,$
is its contrapositive
$\forall M>0, \exists \delta > 0$ such that if ~$(|f(x)| > M)$ then  ~$(0 < |x-a| < \delta)\quad?$

*Do the converse and inverse similarly just affect the if-else?

A: Yes, Contrapositive, Converse and Inverse all refer and apply to conditional formulae and affect only their antecedents and consequents and not any surrounding quantifier or connective.
This is not to say that they never alter quantifiers: the contrapositive of $$\forall x\big(Px\to\exists y Qxy\big)$$ is $$∀x(∀y¬Qxy→¬Px).$$ (Strictly speaking, we are referring to the contrapositive of the string within the parentheses.)
How can I know when to negate quantifiers when taking the contrapositive of a statement?


Q: How to automatically delete the key line from known_hosts when a session is closed? I'm working on automating a whole environment by using AWS CloudFormation and during the testing period I'm required to kill and re-create the servers very often.
The servers are configured to set their IP addresses from a dedicated pool which means that on the first time I connect to them I have to accept the host key checking (the yes/no question) and then when I delete the server and re-create it, I have to delete the server's key from the known_hosts file each time.
My question is:
Is it possible to delete the key from known_hosts automatically when I close the session? is there such a setting which I've missed?

A: You can configure ssh to use multiple files for the known_hosts and new entries only get added to the first, by setting that to /dev/null effectively they won't get saved:
UserKnownHostsFile /dev/null ~/.ssh/known_hosts

Combine it with your personal favourite of asking or automatically accepting unknown keys:
StrictHostKeyChecking no

You probably want to those options restricted to only (specific hosts in) your DEV environment rather than global defaults, as they will take away quite a bit of the security key checking provides so in your ~/.ssh/config:
Host *.dev.example.com
    IdentityFile ~/.ssh/id_rsa.dev.example.com
    UseKeychain yes
    User hbruijn-adm
    StrictHostKeyChecking ask
    UserKnownHostsFile /dev/null ~/.ssh/known_hosts

A: You could do:
ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -l user host

StrictHostKeyChecking=no is of course a bad idea, since it will automatically accept all hosts keys
UserKnownHostsFile=/dev/null will not save anything to your normal known_hosts file.

A: The proper way would be to put the SSHFP (automatically) into the DNS, sign the zone via DNSSEC and let SSH handle the rest, especially, if you need to do this very often and the keys are changing constantly.


Q: pg_dump output formats I'm trying to dump a database and restore it. Running on windows 10, PostgreSQL 15.
I cannot wrap my head around the following:
This command creates a file that I cannot restore through pgadmin (pg_restore: error: input file does not appear to be a valid archive):
pg_dump -U postgres --blobs -Fc lusiadas > C:\mm\db_backup\lusiadas00.sql

This command creates a file that can be used in pg_restore (through pgadmin, same as above):
pg_dump --file C:\mm\db_backup\lusiadas0.sql -U postgres -Fc --blobs lusiadas

I've tried to do the same with a clean (empty) database (the "postgres" one that comes with the server), same results, so seems like the contents of the DB are not at fault.
The plain format obviously works with both notations when restored with psql, only c and t are causing the problem.

A: When using pg_dump > file, the pg_dump  program writes bytes to the standard output, and the calling shell is responsible for writing the bytes to disk, into file.
Some shells change the contents in transit, instead of just passing the bytes through. Powershell, for instance. See this still-open issue on github:  Don’t parse the pipeline as text when it is directed from an EXE to another EXE or file. Keep the bytes as-is. #1908 .
Since the wrong file looks about twice the size of the other one, the shell probably  encoded it to UTF-16 (2 bytes per character for most characters).
The simplest solution is to use the --file option, or if it's really needed to pipe the output to a shell, make sure to use a shell program that does not have this problem.


Q: Accessing the DOM representation of a template instance that is calling a helper I am trying to access a DOM element corresponding to the particular template instance that is calling a helper function. As I read the Meteor documentation, Template.instance() should return the template instance object that called the helper, and something like Template.instance().$() would allow me to grab DOM elements within that instance.
However, the following code (and similar variations) is not working for me:
* HTML *
<template name="input_container">

</template>

* JS *
Template.input_container.helpers({
   isActive: function() {
       if (Template.instance().$('.empty') && [some Session variable logic] {
           return 'active';
       }
   }
});

When I do something like:
if (some Session logic) {
    console.log(Template.instance())
}

I get the helper properly logging multiple versions of:
Blaze.TemplateInstance {view: Blaze.View, data: 7,
firstNode: div.small-12.medium-12.large-6.columns.empty.active-container,
lastNode: div.small-12.medium-12.large-6.columns.empty.active-container, $: function…}
(With data: values going from 1-12 appropriately, but otherwise each seems to be the same)
How do I get from this to being able to used the template methods such as template.$ or template.find?
EDIT:
While not a perfect solution, I did manage to work around some of these issues by using Template.currentData() and setting an identifier on each instance of the input.
Template.create_form.helpers(
  # Create 12 input containers
  inputContainer: () ->
    [0..11]

And then:
Template.input_container.helpers(

isActive: () ->
    # Get which template instance we are working with, will return the number 0-11 that was used to create it
    current = Template.currentData()

    # Now I can do $(".input-container").eq(current) to grab the correct DOM element

)
But it seems a little dirty to need to use so much jQuery.

A: I'm not sure if I've interpreted the question correctly, but if you're trying to access another DOM element on the page - I was able to use a jquery selector.
For example, given html of
<input type="textfield" id="initials" value=" ">

and a simple meteor template of
<template name="demo">
    <input type="button" div id="s0">
</template>

I can successfully access the initials field when the s0 button is clicked as follows
Template.demo.events({
   'click .cell': function(event, template) {
        if ($('#initials').val().trim().length > 0) {
           console.log($('#initials').val().trim() + ' - you clicked button '+$(event.target).attr('id'));
    }
},


Q: SSO with Classic Asp I am in the process of trying to implement Single Sign On for our classic asp parts of our site that run on a separate server. I have already implemented the php SSO on our other server using simpleSAMLphp. I am attempting to use shibboleth right now for the classic asp / IIS side of things. I have made it as far as getting to the login page of our Identity Provider, but once I authenticate I get stuck at /SAML2/POST and a webpage saying that the ip address of my server cannot be found. I have tried implementing fixes I found in forums but still have not made any progress. I am wondering if there is another tool that I could try to implement SSO with classic asp with? I am open to any suggestions at this point.

A: Shibboleth supports IIS using "native module" package (iis7_shib.dll).
Check this https://wiki.shibboleth.net/confluence/display/SP3/IIS for further information.


Q: Google Analytics referral exclusions do not seem to work when using the Google Tag Manager script Two days ago I added 'paypal.com' to the referral exclusions on the google analytics account for my website.
My website is submitting its data to GA via google tag manager.
So far, yesterday's visits are not excluding paypal as referral.
Do you know if the process of setting the referral exclusions with google tag manager is different than it is for google analytics? do you know how long do the referral exclusions settings take to have any effect?

A: I sorted this out by implementing the referral exclusion in javascript, right before the gtm tag:
var previousReferrer = Cookies.get("previous_referrer")
if(document.referrer.match(/paypal\.com/))
  Object.defineProperty(document,
                        "referrer",
                        {get : function(){
                          return previousReferrer; }});
Cookies.set("previous_referrer", document.URL);

please notice that as it is hard to change the document.referrer variable we need to use defineProperty and that this only works in modern browsers (safari <=5, Firefox < 4, Chrome < 5 and Internet Explorer < 9 ):
How to manually set REFERER header in Javascript?


Q: Why is my relation-object reinitialized each time it is accessed? I use Realm Swift 0.95.3. In my project I'm working with a contact (not with contacts AddressBook), which contain information about the name, last name, middle name, email, … and photograph.
I have created a subclass of Object called Contact. I understand that the image, or any other binary data, should not be stored in the Realm. Especially as my images could be large enough ~5 Mb.
In any case, I wanted to store the image in the file system, and Realm stores only a link to this image. I thought that in the future I may need to attach other files (audio, PDF, …) to subclasses of Object. So I decided to create a separate class File, which is inherited from Object. The whole structure looks like.
class File: Object {
  dynamic var objectID = NSUUID().UUIDString

  private var filePath: String {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0] as NSString
    return documentsDirectory.stringByAppendingPathComponent(objectID)
  }

  lazy var fileData: NSData? = {
    return self.readFile()
  }()

  override static func primaryKey() -> String? {
    return "objectID"
  }

  override static func ignoredProperties() -> [String] {
    return ["fileData"]
  }

  override func copy() -> AnyObject {
    let result = File(value: self)
    result.objectID = NSUUID().UUIDString
    result.fileData = fileData?.copy() as? NSData
    return result
  }
}

extension File {
  //MARK:-
  private func readFile() -> NSData? {
    let lFilePath = filePath
    print("Try to read file \(lFilePath)")
    return NSData(contentsOfFile: lFilePath)
  }

  private func writeFileWithFileData() {
    if let lFileData = fileData {
      lFileData.writeToFile(filePath, atomically: true)
      print("File \(filePath) was created")
    } else {
      removeFile()
    }
  }

  private func removeFile() {
    do {
      try NSFileManager.defaultManager().removeItemAtPath(filePath)
      print("File \(filePath) was removed")
    } catch {
      print(error)
    }
  }
}

As you can see, when trying to get the property fileData, data is received from the file system. Moreover fileData is declared with the keyword lazy, that is, I wish that the data is requested from disk to cache in this property. If this property is changed, the File object before saving to the database, I call writeFileWithFileData (), and data on the disk is overwritten. This system works as I need to, I to experiment. Then I created a Contact.
class Contact: Object {
  dynamic var objectID = NSUUID().UUIDString

  dynamic var firstName = ""
  dynamic var lastName = ""
  ...
  private dynamic var avatarFile: File?

  var avatar: UIImage? {
    get {
      guard let imageData = avatarFile?.fileData else { return nil }
      return UIImage(data: imageData)
    }

    set {
      avatarFile = File()
      guard let imageData = newValue else {
        avatarFile?.fileData = nil
        return
      }
      avatarFile?.fileData = UIImagePNGRepresentation(imageData)
    }
  }

  override static func primaryKey() -> String? {
    return "objectID"
  }

  override static func ignoredProperties() -> [String] {
    return ["image"]
  }
}

The problem is that when I choose a contact from the database, and am trying to get the avatar, then access to the file system occurs every time you access this property. That is, property fileData does not operate as lazy - as I thought at first. But then I looked at the memory address properties avatarFile, each time it is received, the address has changed. From this I can conclude that the object avatarFile is constantly requested from the database again, with any reference to this property. As a consequence, all its ignoredProperties are reset.

*

*Why is the relation-object reinitialized each time it is accessed?

*Share your opinion about my arch

A: *

*It should be fine. Realm Objects are live links to their parent Realm object, not static copies, so their addresses do periodically change. This is normal, and the objects aren't getting re-allocated so you shouldn't see any memory issues here. As far as I'm aware, NSData itself is lazy, so the data won't actually be read until you explicitly request it.

*Your architecture looks good! You're right in that it's usually not the best form to store file data directly inside a Realm file, but you've done a good job at making the Realm Object manage the external file data as if it was. :)


Q: How to retain specific parts of an element in a column and eliminate everything else in R? I have a column containing the brand and model of cars. How to keep only the brand and remove the model? In the original dataset, the brand and the mode were separated by a space. So I tried this:
carprice$CarName=gsub(pattern = " *", replacement = "",carprice$CarName)

What happened was the space got eliminated and now the brand and the model names are concatenated. I am not able to even undo it.


Q: How do I reverse a string in java by creating a new temporary string? What's the error in the following code? I am not able to identify it shows the index 0 out of bounds exception.
public class stringBuilders{
    public static void main(String[] args)
        {

            StringBuilder str = new StringBuilder("Shubham");
            StringBuilder str2= new StringBuilder();

            int j=0;

            for(int i = str.length()-1; i>=0 ; i--)
            {
                str2.setCharAt(j++,str.charAt(i));
            }

            System.out.print(str2);

        }

}

A: As you are already iterating from end to start you can just append the characters to the fresh and empty string builder. setChar() is only intended to replace existing characters.
public class StringBuilders {
    public static void main(String[] args) {
        String str = "Shubham";
        StringBuilder str2 = new StringBuilder();

        for (int i = str.length() - 1; i >= 0; i--) {
            str2.append(str.charAt(i));
        }

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

gives
$ java StringBuilders.java
mahbuhS

A: You haven't declared a value to the str2 string.
The for loop is trying to find a character at index j=0 in str2 to set value i of str2, which it cannot find.
Hence the error.
For this to work, you need declare a value of str2 to a length >= str1. i.e., if str1 = "0123456", str2 should be at least 0123456 or more.
Instead of using StringBuilder to set the char, you can use String to just append to it.
        String str1 = new String("Shubham");
        String str2 = new String();

        int iter = str1.length() -1;

        for(int i=iter; i>=0; i--) {
            str2 += str1.charAt(i);
        }

        System.out.println(str2)


Q: How to stop iPhoto and iTunes from opening automatically when plugging in an iPhone? I'm still pretty much a noob in OS X (Snow Leopard, if that makes any difference).
How to stop iPhoto and iTunes from opening automatically when plugging in an iPhone?

A: Found the answer to how to stop iPhoto from opening here: http://michaelkrol.com/2007/09/13/tell-your-iphone-to-stop-opening-iphoto/

Open Image Capture and go to the Preferences menu (under the Image Capture menu item). Under the General tab, change the option for “When a camera is connected…” to “No Application” instead of “iPhoto”.
This means you’ll have to manually start iPhoto when you connect your digital camera, but you won’t have to CLOSE iPhoto every time you plug in your iPhone (which, for me, is a heck of a lot more often than plugging in a camera!)

A: iTunes has an option to automatically start iTunes when the iPod is connected ...  I assume the same option is there when you connect an iPhone on the Mac. Simply uncheck the checkbox.
Connect the iPhone, click on it in the left hand panel on iTunes, and look for the option over on the right. (Main tab).

A: For iTunes select your device and uncheck Automatically sync when this iPhone is connected

For Image Capture, select the up symbol and then select No Application

A: For iPhoto, do like alxp said.
For iTunes, you can also remove the iTunesHelper in your launching elements.
This will not load iTunes when any iPhone is plug.

A: I find this,
http://www.simplehelp.net/2009/09/29/how-to-stop-iphoto-from-opening-when-you-plug-in-an-ipod-touch-or-any-device-with-a-camera/
sry for posting link I'm busy now and can't post it here with photo. :(

A: There is also an excellent control panel add-on called Cameras for Mac OS X which allows you to choose what it will do if you connect, say an iPhone, your DSLR or any other camera like the device. Best of all, it free. You can specify in the control panel what action the mac will take when a certian device hooks up to machine. You can download it here This utily won't disable iPhoto completely from launching on device connect, but only for the devices you want. It iritated me 2 everytime I connected my iPhone, iPhoto would automatically launch, and this works great. It's been a bit flaky under Snow Leopard though, so update wouldn't hurt either @flexibits


Q: Exporting Result Set to Another Table? How can you export a result set given by a query to another table using SQL Server 2005?
I'd like to accomplish this without exporting to CSV?

A: INSERT INTO TargetTable(Col1, Col2, Col3)
SELECT Col1, Col2, Col3
FROM SourceTable

A: insert into table(column1, columns, etc) select columns from sourcetable

You can omit column list in insert if columns returned by select matches table definition. Column names in select are ignored, but recommended for readability.
Select into is possible too, but it creates new table. It is sometimes useful for selecting into temporary table, but be aware of tempdb locking by select into.

A: SELECT col1, col2, ...
INTO dbo.newtable
FROM (SELECT ...query...) AS x;


Q: Handling pagination with Blogger Api I understand the documentation regarding the nextPageToken and retrieving subsequent pages.
My question-- what is the best practice to implement a way to go to the PREVIOUS page?


Q: How to get parent id with jQuery?

$('td').click(function() {
  myId = $(this).parent().attr("id");
  myItem = $(this).text();
  alert('u clicked ' + myId);
});

    Computer

    maths

    physics

When I click on table item I want to get alert 'u clicked science' but I get undefined.
Any help would be appreciated!

A:
There are no id attributes in your markup. All you are dealing with is innerText

$('td').click(function() {

  var myItem = $(this).text();
  alert('u clicked ' + myItem);

});

    Computer

    maths

    physics

A: You have invalid markup. extra closing div is added after last tr closing markup. you need to remove it.
what you need to alert is text of element and not parent id. use .text() along with clicked td elements jquery context:

$('td').click(function(){
 myItem=$(this).text();
 alert('u clicked ' +myItem);
});

Computer

maths

physics

A: try this:
    $('td').click(function () {
        alert('u clicked ' + $(this).text());
    });

A: As I have already commented, you are missing ID in tr. I have added few more tds for demo.

$('td').click(function() {
  var myId = $(this).parent().attr("id");
  var myItem = $(this).text();
  alert('u clicked ' + myId);
});

    Computer

    maths
    History

    physics
    Chemistry
    Biology


Q: Pyinstaller - ModuleNotFoundError: No module named 'cpuinfo' I'm trying to package this script but I keep getting this error message
Traceback (most recent call last):
  File "systeminfo.py", line 1, in <module>
ModuleNotFoundError: No module named 'cpuinfo'
[6308] Failed to execute script systeminfo

I tried this into cmd
pyinstaller -F --hidden-import="cpuinfo" systeminfo.py

I'm on the latest version of pyinstaller and pip.
This is the import section of my file:
import psutil, platform, GPUtil, cpuinfo, os, sys, wmi, winreg, getpass
from tabulate import tabulate
from datetime import datetime

When I run it, it just opens up and closes out. But when I run it through CMD, that's when I get that error message.
How do I fix this? I want to include all the modules so I can run this script on different computers that don't have python installed.
EDIT:
I fixed this issue by using this thread: Pyinstaller 'failed to execute' script
I use pycharm so this worked for me.
The only issue is whenever the CMD opens up, nothing happens. The only thing that can printed is if I hardcode a print(). Functions aren't working at all.

A: fix it with :
pip install py-cpuinfo


Q: What should I learn first? (For web programming) Should I learn PHP or JQuery.I have some knowledge in HTML CSS and JavaScript.

A: Modern web development is now actually divided in to two major parts

*

*Frontend (JavaScript and related things)

*Backend (PHP, NodeJS or others)
Now if you are more interested in designing the User Interface and what shows on the screen, then go forward to HTML and then JavaScipt and then JQuery (which is an opensource library in JavaScript) and then CSS.
However if you are interested in Backend (means server side coding, databases and business logics etc) then you should target PHP or any other suitable server side language.
Bonus: If you are interested in starting things quickly, I would recommend that start learning JavaScript first, because there is a server side technology named NodeJS (which does almost all the work PHP does) and it uses JavaScript. So in that case, you only will have to learn JavaScript and CSS.

A: They are for different purposes. JQuery is for Front End, that means, what will run on users's browsers. The same goes for HTML and CSS. PHP is what will run on the server.
If you are extremely newbie, just as I was a few years ago, you might want to learn them all at the same time. Also, SQL, as it is the language for databases.
This site is for beginners: http://www.w3schools.com/


Q: Generalizing the product rule to dot products I will be using the notation, assumptions, and definitions mentioned in the statement of this question: Proving that a vector-valued function is differentiable

Define $\varphi \bullet \psi:\Omega\rightarrow\mathbb{R}$ by $(\varphi \bullet \psi)(\underline{x})=\varphi(\underline{x})\bullet\psi(\underline{x})$, where "$\bullet$" denotes a dot product. We also define $\mu:\mathbb{R}^{2p}\rightarrow\mathbb{R}$ by writing elements of $\mathbb{R}^{2p}$ as $\begin{bmatrix}\underline{x} \\ \underline{y} \\ \end{bmatrix}$ for $\underline{x},\underline{y}\in \mathbb{R}^p$, and letting $\mu(\begin{bmatrix}\underline{x} \\ \underline{y} \\ \end{bmatrix})= \underline{x} \bullet \underline{y}$.

Prove that $\varphi \bullet \psi$ is differentiable at $\underline{a}$, and find an expression for its differential.

Like the title says, I'm pretty sure this is leading to the generalization of the product rule, and so I expect the answer to be $d(\varphi \bullet \psi)(\underline{a})=d\varphi(\underline{a}) \bullet \psi(\underline{a})+\varphi(\underline{a}) \bullet d\psi(\underline{a})$.
We have already shown that $\varphi \bullet \psi=\mu \circ \begin{bmatrix}\varphi \\ \psi \\ \end{bmatrix}$, and we've proven the chain rule as well:
$d(\varphi \circ \psi)(\underline{a})=d\varphi(\psi(\underline{a}))\circ d\psi(\underline{a})$
I'm just not sure where to begin (or how to finish). I think I should try to show that $\mu$ is differentiable, and then by the chain rule I at least know the dot product function is differentiable. How I can arrive at the desired product rule is a bit of a mystery to me, though.

A: We don't need the $\mu$. You are given a scalar-valued function
$$f(x):=\phi(x)\cdot\psi(x)$$
and are asking for its derivative. The derivative of $f$ at a point $a$ either appears as a linear functional $df: \>{\Bbb R}^n\to{\mathbb R}$ or as  gradient vector $\nabla f(a)$. You are right in conjecturing that somehow the product rule applies, but writing $df$ in the form you tried makes no sense: You can not take the scalar product of a linear map  $d\phi(a): \>{\Bbb R}^n\to{\Bbb R}^n$ with a vector.
In order to see what's going on here we have to go back to the definitions. We have
$$\eqalign{f(a+h)-f(a)
&= \bigl(\phi(a+h)-\phi(a)\bigr)\cdot\psi(a)+\phi(a)\cdot\bigl(\psi(a+h)-\psi(a)\bigr)\cr
&\qquad+ \bigl(\phi(a+h)-\phi(a)\bigr)(\psi(a+h)-\psi(a)\bigr) \ .  \cr}$$
Since $$\phi(a+h)-\phi(a)=d\phi(a).h+R(h)$$ with $R(h)/|h|\to0$, and of course $|\phi(a+h)-\phi(a)|\leq M|h|$ for suitable $M$ we get
$$\eqalign{&{\bigl|f(a+h)-f(a)-d\phi(a).h \cdot\psi(a)-\phi(a)\cdot d\psi(a).h\bigr| \over |h|}\cr &\qquad\qquad\leq{|R_1(h)|\over|h|}|\psi(a)|+{|R_2(h)|\over|h|}|\phi(a)|+M_1M_2|h|\ .\cr}$$
Here the right hand side converges to $0$ when $h\to0$. This proves that
$$df(a).h=d\phi(a).h \cdot\psi(a)+\phi(a)\cdot d\psi(a).h \ .\tag{1}$$
Now in an inner product space we have the rule
$$y\cdot Ah=  A^\top y\>\cdot h\ .$$
Therefore we can replace $(1)$ by
$$df(a).h=d\phi(a)^\top\!. \psi(a)\cdot h +d\psi(a)^\top\!.\phi(a)\cdot h \ ,$$
and this shows that
$$\nabla f(a)=d\phi(a)^\top\!. \psi(a) +d\psi(a)^\top\!.\phi(a)\ .$$


Q: Apache Getting Bogged Down By Certain Script (Wp-Cron.php) - How To Kill Process Automatically I have a server that is running a number of wordpress blogs, and a number of them have several hundred/thousand posts.
Every couple of days, the server slows to a crawl due to a file being run on Wordpress called WP-cron.php. My entire apache process log turns into this :
http:// imgur.com/A7K9k.png
Times that by quite a bit. And server no go.
Each process takes up about 1.1% of ram. And when we have 50 of them on the go. It gets insane. Not all of them are coming from the same blog, they are pretty widespread. In the Apache process page of WHM, they are usually ALL set to the status of "C", which means closing. But they can sit there until they crash the server, and they still hold the memory.
Just google "wp-cron.php load" and you will find plenty of people with similar issues.
In anycase, we have think it is down to users adding a tonne of dead "pinglists" to their wordpress installation. Which in turn wordpress loops through them endlessly.
Problem number 1.
Does anyone have any other suggestions about what would cause the Wordpress file wp-cron.php to loop endlessly. I still think it is down to pings, because all of the people we have contacted about their account load going sky high, have had massive ping lists.
Problem number 2.
Even if it is down to excessive pinglists in wordpress. We cannot be babying every single account on the server waiting for it to start spawning the wp-cron processes. It often happens overnight, and I start getting SMS alerts at 2am about the load.
I have CSF installed, which apparently would have ended the processes if they ran over XXX time. But I have been told that it won't catch the processes because they end up in this state of "closing" (They show up as "C" on the Apache page of WHM). Apparently CSF will only kill processes that are "running" which C does not count.
I have seen various other scripts such as : http://dltj.org/article/die-apache-die/ . I took a look at the stat of /proc. But I was boggled at which delimited part was the time running. And if there was any way I could connect it back to an actual Apache process, so that I could see what file was running (So only close connections connected to wp-cron.php, with a state of "C").
Overall I know Problem 2 glosses over the real reason. But I do put the whole thing to excessive pinglists in Wordpress. But I just cannot sit there and babysit every single installation 24/7. So I need a way to save the server when I am not available.
Any help would be much appreciated.

A: Anychance you can have a different server run the same site, and run cron there? For some of our larger sites, that's what we've done, we've disabled wp-cron on the customer facing web heads, yet have one internally that runs..
Add define('DISABLE_WP_CRON', true); to the wp-config,

A: Take a look at excellent process watcher/killer, psmon. It's just a Perl script which daemonizes itself background and contains an Apache-style config file with possibility to kill processes if they consume X amount of memory or if they've been consumed X amount of CPU time. PSMon can alert you via syslog or email whenever it decided to slay a process.
Also, you might want to wrap wp-cron.php around a shell script, which would use a lockfile and make sure that only one copy of wp-cron.php is running around any given time.

A: The question is, would your users be confortable not having wp-cron.php.. are your blogs/plugins dependent on them. If not, you can either use mod_security or just plain apache config to blog wp-cron.php from executing. For every blog, WP will run its own instance of wp-config.php.


Q: Unity custom UI Messagebox I am trying to make a custom messagebox to display text that characters say throughout my game. I tried to achieve this through this code:
[SerializeField] public Text PresetText;
[SerializeField] public GameObject PresetBorder;
[SerializeField] public GameObject Canvas;

private Text UIText;

private Text _tempText;
private GameObject _tempBorder;

public static bool TEXT_INPUT;

public string text = "Placeholder.";

void Start ()
{
    _tempBorder = Instantiate(PresetBorder as GameObject);
    _tempBorder.transform.SetParent(Canvas.gameObject.transform, false);

    _tempText = Instantiate(PresetText) as Text;
    _tempText.transform.SetParent(Canvas.gameObject.transform, false);

    UIText = _tempText;
    UIText.text = text;
}
public void SetText ( string _text )
{
    text = "Speech: " + _text;
}
void Update ()
{
    UIText.text = text;
}

... and I am calling the SetText () function through this in a dummy file:
public MessageShell m;
void Start ()
{
    m.SetText("Test!");
}

(MessageShell because my code file is named MessageShell.cs)
The problem is if I call this, an empty border with no text appears. How do I fix this and could I improve this script?

A: First thing that I would do is to figure out where the problem lies. Is the text created? Where does it actually appear? Run the game, and look at the game object view to see what is happening for these objects.
My second observation is that you probably want the text to be parented to the border. This allows the border to adequately manage the text, and how it laid out. They should go together.
Lastly, take a look at LayoutGroups. If your border has a layout group, then it should adjust it's size (Or adjust the size of it's children) to match the text as you want it to be.


Q: VS2008 keeps hanging busy when clicking design view VS2008 express web developer keeps hanging whenever I try to go to design mode. this just started a couple days ago for some reason, was fine before.
whenever i click design mode, the whole thing freezes, any clicks anywhere on the program give me a 'ding' sound until i end task in task manager.
usually there's no error to see, though sometimes i'll see some error in the status update about jquery intellisense problems loading, the thing is that this happens even on a brand new project and default.aspx with no jquery attached.
any ideas? this is very frustrating, i can no longer work.
multiple uninstalls and fresh installs have done nothing to help.

A: VS gets hang many times when we click on its design page (aspx) and it dies.
This issue can be solved by following these steps –
1.  Go to control Panel
2.  Add or Remove programs
3.  Find Microsoft Visual Studio Web Authoring Component.
4.  Click on change and then click Repair.
5.  Restart your system and hopefully your problem will get solved. 

A: It might be the ToolBox refreshing itself.  Try this tip:
http://weblogs.asp.net/stevewellens/archive/2009/07/23/speed-up-the-visual-studio-toolbox.aspx

A: There is a good resolution on MSDN blog. Follow the link below:
Troubleshooting "Visual Studio 2008 Design view hangs" issues

A: This link fixed my hang problem:
https://blogs.msdn.microsoft.com/amol/2009/07/23/visual-studio-2008-hangs-on-switching-to-design-view/
Run regedit.exe and look for HKEY_LOCAL_MACHINE\Software\Microsoft\Office\12.0\Common\ProductVersion key. If key is missing, add it and set “LastProduct” value to 12.0.4518.1066. Restart the machine after this step.

Also, you can try repair "Microsoft Visual Studio Web Authoring Component" in programs and features.


Q: Twig: mapping array to table I need to have such output
--------------------------------
|    | id1   | id2   | id  ... |
--------------------------------
| m1 | x1,x2 | x3    | x5      |
--------------------------------
| m2 | x4    | x6,x7 | ...     |
--------------------------------
|m...| ...   | ...   | ...     |
--------------------------------

where "x" is unique, "m" and "id" are not unique;
each row in object array returns m,x,id values
how can I map such array using other array to have above result?
main problem is to map first row as header and then make x'es to sort based on column header.
I know how to use nested loop in Twig but have no idea how to prepare array with data.
results from database can be sorted by any of this values if needed.


Q: How to uninstall an older PHP version from centOS7 My project is on Laravel 5.2. and as per guide it required php >= 5.5.6 but there was php 5.4 intalled and I had to upgrade php version through YUM,
But now it is giving error "PDO driver not found" and I tried YUM install php-pdo
but it's giving error that "there is conflict between php56w-common and php-comon-5.4.16". I am stuck on this point

A: yum -y remove php* to remove all php packages then you can install the 5.6 ones.

A: Subscribing to the IUS Community Project Repository
cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh

Run the script:
sudo bash setup-ius.sh

Upgrading mod_php with Apache
This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.
Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.
sudo yum remove php-cli mod_php php-common

Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.
sudo yum install mod_php70u php70u-cli php70u-mysqlnd

Finally, restart Apache to load the new version of mod_php:
sudo apachectl restart

You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:
systemctl status httpd


Q: Implementing a second battleship into a one dimensional game "River Battleship" Would anybody be able to offer me a simple way to implement a second enemy battleship into a game I have designed to only have one enemy, this is my code currently :
import java.util.*; //Scanner that reads user input

public static void main(String[] arg)
    {
        int riverLength = promptForInt("Select Length for River ") ; //Variable that stores the user input when prompted
        int [] shipArray = new int[riverLength] ; //User input is used to create an Array, i.e. River Size
        int battleshipCoordinates = new Random().nextInt(riverLength) ; //Random number is found within the Array (Where the enemy ship will hide)

        shipArray[battleshipCoordinates] = 1 ;
        boolean hit = false ; //Statement created for ship hit and default to false
        int playerSelection; //int Variable declared

        do
       {
           displayRiver (shipArray, false);
           playerSelection = promptForInt(String.format("Select location to launch torpedo (1 - %d) ", riverLength));
           playerSelection = playerSelection -1 ;

           if(shipArray[playerSelection] == 1 ) //if a user strikes the Enemy (Case 1) correctly they system informs them of a strike
           {
            System.out.println("Battleship Sunk!");
            hit = true;
            displayRiver(shipArray, true);
           }
           else if(shipArray[playerSelection] == -1)
           {
            System.out.println("Location already Hit! Try again.");
           }
           else if(shipArray[playerSelection] == 0)
           {
            System.out.println("Miss!");
            shipArray[playerSelection] = -1 ;
           }

       } while(!hit);

    }
}

A: Step 0 - Create a new battleship and place them on the array just like the first one.
Step 1- Change your boolean hit to an int equaling 2.
Step 2- Instead of toggling hit, reduce it by 1 when you hit a ship and then set
that position on the array to a 0.
Step 3- Adjust your logic so that you do not win unless hit < 1


Q: React Native: GiftedChat only updating chat message if I scroll to top of screen? I'm using Gifted Chat for a chat app using React Native. When I send either a text message or an image, the code executes, but the new message does not appear on the screen unless I scroll to the top of the chat screen. If I scroll to the bottom, nope, and if I only scroll halfway up, still nope. Only when I scroll to the top of the screen does it update. Anyone understand why this could be happening? Here is my code.
import React, { useState } from 'react';
import { Image, StyleSheet, Text, View, Button, FlatList, TouchableOpacity, Alert } from 'react-native';

import { GiftedChat } from 'react-native-gifted-chat';

const Conversation = (props) => {

  const chatId = props.chatId || "12345";
  const userId = props.userId || "6789";
  const [messages, setMessages] = useState([
    {
      _id: 1,
      text: 'My message',
      createdAt: new Date(Date.UTC(2016, 5, 11, 17, 20, 0)),
      user: {
        _id: userId,
        name: 'Jane',
        avatar: 'https://randomuser.me/api/portraits/women/79.jpg',
      }
    },
    {
      _id: 3,
      text: 'My next message',
      createdAt: new Date(Date.UTC(2016, 5, 11, 17, 21, 0)),
      user: {
        _id: 4,
        name: 'Gerry',
        avatar: 'https://randomuser.me/api/portraits/women/4.jpg',
      },
      image: 'https://media1.giphy.com/media/3oEjHI8WJv4x6UPDB6/100w.gif',
    }
  ]);
  const d = Date.now();

  const onSend = (msg) => {
    console.log("msg : ", msg);
    const message = {
      _id: msg[0]._id,
      text: msg[0].text,
      createdAt: new Date(),
      user: {
        _id: userId,
        avatar: "https://randomuser.me/api/portraits/women/79.jpg",
        name: "Jane"
      }
    }
    const arr = messages;
    arr.unshift(message);
    setMessages(arr);
  }

  return (
    <GiftedChat
      messages={messages}
      onSend={newMessage => onSend(newMessage)}
      user={{
        _id: userId,
        name: "Jane",
        avatar: "https://randomuser.me/api/portraits/women/79.jpg"
      }}
    />
  )
}

export default Conversation;

A: Figured it out. GiftedChat requires that you use one of its own methods called append.
const onSend = (msg) => {
  console.log("msg : ", msg);

  // first, make sure message is an object within an array
  const message = [{
    _id: msg[0]._id,
    text: msg[0].text,
    createdAt: new Date(),
    user: {
      _id: userId,
      avatar: "https://randomuser.me/api/portraits/women/79.jpg",
      name: "Jane"
    }
  }]

  // then, use the GiftedChat method .append to add it to state
  setMessages(previousArr => GiftedChat.append(previousArr, message));
}


Q: MixPanel: Should all property names be denoted with dollar signs? The built-in default properties of MixPanel such as $browser or $city all start with dollar signs. Does this have any purpose? Should we denote custom properties with dollar signs as well or is the dollar sign meant to be the marker for a default property?

A: It would not be recommended to start all of your custom properties with the same dollar convention. The dollar sign convention is meant to denote properties that the Mixpanel SDKs track automatically or properties that have some special meaning within Mixpanel itself. That link you shared is great for the default properties and there is also documentation for the reserved user profile properties and reserved event properties if you were curious about those.


Q: Google Sheets importxml() scraping doesn't work with xpath copied from console I am trying to scrape content from tradingview website. Specifically the Industry of a particular ticker given in the description.

I have the xpath which I copied from the element inspector of the browser. But it doesn't seem to work and the output I get is "#N/A".
The formula I have used is
=IMPORTXML("https://www.tradingview.com/symbols/NSE-FINPIPE/", "//div[3]/div[3]/div/div[2]/div/div/div[1]/div[3]/div/div[2]/div/div[1]/div[2]/div[2]/a")

A: IMPORTXML as well as IMPORTHMTL they can only see the source code, not the DOM shown on the web browser developer console.
If the the content that you want to scrape is added to the DOM by client-side JavaScript or the web browser engine, it can't be scraped by using IMPORTXML.


Q: Sending arrays to REST services in CakePHP I'm currently writing a REST service using CakePHP and I was wondering how can I send an array of item_ids through REST to an action.
class ItemsController extends AppController {

var $components = array('RequestHandler');
var $helpers = array('Text', 'Xml');

function index()
{

}

function create($itemsArr)
{
        //handle $itemsArr here and sends data as xml to views.
}

}

I guess my real question is, How will the request look like?
http://mysite/items/create/???
I guess I can pass the values as 1 argument using implode(someSeperator, array) but is there a better solution?
Thanks in advance

A: This is not REST.
REST is about using HTTP, not XML!
A typical HTTP REQUEST to create an item would be like this
PUT http://mysite/items/ HTTP/1.1
Host: xxxxx

<myitem>
<text> asdasdas </text>
</myitem>

And you can use whatever you want in the body of the request. XML, JSON, PHP SERIALIZE or your own data format.

A: If you truly want to be RESTful about this, you'd definitely want to use a POST request to create records. That's if you care to be strict about the standard, but it would also help you because I'm reading that your array's length could vary tremendously - sometimes 1 ID, perhaps 30 other times, etc. URI query strings do (or used to?) have a maximum character limit that you could conceivably bump up against.
If you roll with a POST request, you could easily passing in a comma-delimited list (think about how a field name with multiple checkboxes is passed) or, my favorite mechanism, a JSON-encoded array (represented as a string that can easily be JSON-decoded on the other side.

A: This actually applies to any web page, not just CakePHP.
Any web page which wants to send a large number of fields has to include them all in their POST request.
If you had a web page form with 50 inputs and a submit at the bottom, the page would by default serialise the data and send it in the form request.
If you don't want all the data sent in seperate bars, then using a seperator would work fine too and would mean they all went in 1 parameter.
Somthing like:
http://mysite/items/create?mydata=23-45-65-32-43-54-23-23-656-77

A: another option:
$safedata = base64_encode(serialize($arrayofdata));

and pass it to URL as safe string.
then uncompress it:
$data = unserialize(base64_decode($safedata);


Q: Why am I getting this 'enum' is not a class or a namespace error? I need call a method with this signature in my Manager class:
void createPlayer(Player& player, PlayerType& playerType);

I have a Player defined like so:
using namespace std;

enum PlayerType { FORWARD, DEFENSEMAN, GOALIE };

class Player {
  public:
    Player();
    void setType(PlayerType);
  private:
    PlayerType type;
};

This is how I try to call the method in main ...
#include "Player.h"
#include "Manager.h"

int main() {

  Manager manager;
  Player player;
  PlayerType t = PlayerType::FORWARD;
  manager.createPlayer(player, t);

  return 0;
}

... but it fails to compile with this error:
Main.cc: In function ‘int main()’:
Main.cc:12:18: error: ‘PlayerType’ is not a class or namespace

Any ideas?  Note: I cannot change the signature of the createPlayer method.

A: Unfortunately enum by default doesn't create an enum namespace. So when declaring:
enum PlayerType { FORWARD, DEFENSEMAN, GOALIE };

you'll have to use it like this:
auto x = FORWARD;

Thankfully, though, C++11 introduced enum class or enum struct to solve this issue:
enum class PlayerType { FORWARD, DEFENSEMAN, GOALIE };

You'll then be able to access it like you did:
auto x = PlayerType::FORWARD;

A: enum doesn´t create a namespace.
Therefor PlayerType t = PlayerType::FORWARD; should be changed to:
PlayerType t = FORWARD;

Notice that c++11 introduce enum classes, which have a namespace. Beside this MSVC has an extension which treats (regular) enums like they have namespace. So your code should actually work with MSVC.

A: Your error seems to be in this line:
PlayerType t = PlayerType::FORWARD;
As far as I know, the scope resolution operator (::) is not valid on regular C++98 enums unless your compiler supports them through non-standard extensions (like Visual Studio). Therefore you can't use it to reference an specific value from the enumerator.
Also, C++98 enums have the problem of polluting the namespace in which they are defined which can lead to name clash. Luckily C++11 solved this introducing the enum class. For more information check Stroustrup's FAQ: http://www.stroustrup.com/C++11FAQ.html#enum

A: add a static function say getForward:
class Player {
  public:
    Player();
    void setType(PlayerType);
    static PlayerType getForward {
        return FORWARD;
    }
  private:
    PlayerType type;
};

Then use it in main:
manager.createPlayer(player, Player::getForward());

This should work.


Q: how to efficiently redirect url in Cloudfront without S3 My requirement is to redirect url from Cloudfront. So for this I see there are possibilities to do using Lambda function as mentioned here.
My application is not hosted in S3, rather it is hosted in Apache webserver which is running on some EC2 instance.
Because redirect rules are many so I would like Lambda function to read configuration of redirect mapping from some other place but I do not know what could be the other place.  I see it is possible to read either from S3 or SNS topic. Could you please suggest what is the best practice to store redirect mapping and handle redirect via Lambda?
As I understood it is not possible to do using Route53 to read mapping and then do redirect. Please correct me if I am wrong.
I am new to this and would request your expert guidance!

A: I think you are mistaking some concepts. If I got it right you need a CDN for an Apache server on EC2. In that case you want Cloudfront with EC2 as origin . https://aws.amazon.com/cloudfront/getting-started/EC2/


Q: how to minimize database latency issues for increase sharepoint web front end servers issues how to minimize database latency issues for increase sharepoint web front end and applications servers performance
I have a large scale of sharepoint farm and in peak time there is issue of Sql server slowness

A: Some things to check consider:

*

*Add RAM to SQL Server box

*Decrease the distance between the SQL Server and the SharePoint servers

*Isolate the SQL Server from other applications--just have SharePoint databases on one server, no other instances or non-SharePoint application databases

*Point the web servers back to themselves (127.0.0.1) in the HOSTS file.

*Decrease the services on the web front end servers that should be application server specific.

*Add more servers to the farm and scale out.

*Follow the recommended requirements


Q: Is the union of Cartan subgroups over $k$ dense? Let $k$ be a finite field and $G$ a connected, reductive linear algebraic group defined over $k$. It is well-known that the union of the maximal tori of $G$ is dense in $G$ (more generally, if $G$ is not reductive, the union of its Cartan subgroups is dense).
It is also true, that $G$ is generated by the maximal tori defined over $k$ (this is proven in a paper by Borel and Springer from 1968).
However, is the union of the maximal tori which are defined over $k$ still dense in $G$?

A: The set of maximal tori defined over $k$ is finite: if $T$ is one of them, they correspond to the $k$-rational points of the $k$-variety $G/\text{(normalizer of }T)$. So their union is not dense, unless $G$ is a torus.


Q: Servlet running under Grails How can I run a servlet (UploadAction from GWTUpload project) under grails? I've successfully added the servlet and use it from the web.xml file. However, I really want to wrap some logic around the doPost/doGet methods using the grails framework (gorm).
Can I just subclass the servlet as a Controller, maybe just instantiate the servlet in the controller and call init()? I'm not sure how to do this properly.

A: The simplest thing that comes to my mind is:

*

*write a grails controller, instantiate the servlet (once, in the contstructor or in @PostConstruct) and call init()`

*map the controller method (via UrlMappings.groovy) to the url that your servlet would be mapped

*call servlet.service(request, response).

It's a bit of a hack though. Another way is to get ahold of a spring (grails) bean in a filter applied to the servlet, with WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()) and invoke the custom logic there.


Q: Fluid grid layout I am creating a form. In the form I have 20+ html controls i.e. textboxes, checkboxes, textarea. I want to arrange all the html elements in a table format. But when the screen sizes is reduces the number of column should get reduced.
example. Initially there will be 4 columns. when screen size reduces no of columns becomes 3. on further screen size reduction no of columns becomes 2 and then to 1.
How this can be achieved?

A: Use Flexbox Layout to design flexible responsive layout structure:

* {box-sizing: border-box;}

/* Style Row */
.row {
  display: -webkit-flex;
  -webkit-flex-wrap: wrap;
  display: flex;
  flex-wrap: wrap;
}

/* Make the columns stack on top of each other */
.row > .column {
  width: 100%;
  padding-right: 15px;
  padding-left: 15px;
}

/* Responsive layout - makes a two column-layout (50%/50% split) */
@media screen and (min-width: 600px) {
  .row > .column {
    flex: 0 0 50%;
    max-width: 50%;
  }
}

/* Responsive layout - makes a four column-layout (25%/25% split) */
@media screen and (min-width: 991px) {
  .row > .column {
    flex: 0 0 25%;
    max-width: 25%;
  }
}

Resize this frame to see the responsive effect!

Column 1

Some Text...

Some Text...

Some Text...

Column 2

Some Text...

Some Text...

Some Text...

Column 3

Some Text...

Some Text...

Some Text...

Column 4

Some Text...

Some Text...

Some Text...

Reference:
Create a Mixed Column Layout


Q: split column in multiple columns in sql view I have created a view for the Leco results and it is attached here as ‘Leco Teble’ excel file. I would like to have same view in database with ‘expanded table’ column based on the sample ID’s as given in the expanded table. Would you please arrange with one of your team member to create a script to expand the table in the same view. Last column in the table “Shift” should be picked up based on the time with the sample ID. 6am to 6pm is day shift.


Q: Deleting records from fact table and dimension table I want to delete records from target table as records deleted from a source. I used merge/rows and delete stop both individuals, but I solved my problem in delete case when I deleted record from source. Then, after transformation fact table had only that record which was deleted from the source while it must had all those instead of this. I want the same method for the dim table also.enter image description here


Q: Alert to detect the available space on the hard drive I would like to know if it is possible to create an alert in a google cloud platform instance, to identify that a hard drive of an instance is 90% busy, for example, and that this sends a notification to some user.
I await your response, and thanks in advance.

A: You can use Google Stackdrive to setup alerts and have an email sent.
However, disk percentage busy is not an available metric. You can chose from Disk Read I/O and Disk Write I/O bytes per second and set a threshold for the metric.

*

*Go to the Google Console Stackdriver section. Click on Monitoring.

*Select Alerting -> Create Policy in the left panel.

*Create your alerting policy based upon Conditions and Notifications

You can create custom metrics. This link describes how.
Creating Custom Metrics


Q: Missing choices 11 in case statement and failed synthesizing module LIBRARY ieee;
USE ieee.std_logic_1164.ALL;

entity mucodec is
    port (
        din     : IN std_logic_vector(2 downto 0);
        valid   : IN std_logic;
        clr     : IN std_logic;
        clk     : IN std_logic;
        dout    : INOUT std_logic_vector(7 downto 0);
        dvalid  : OUT std_logic;
        error   : OUT std_logic);
end mucodec;

architecture Behavioral of mucodec is
    type state_type is (St_RESET, St_ERROR, St_BOS_1, St_BOS_2, St_BOS_3, St_BOS_4, St_EOS_1, St_EOS_2, St_EOS_3, St_EOS_4, St_DECODE, St_Out);
    signal state, next_state : state_type := St_RESET;

    -- Define additional signal needed here as needed
begin
    sync_process: process (clk, clr)
    begin
        if clr = '1' then
            state <= St_RESET;
        elsif rising_edge(clk) then
            state <= next_state;

        end if;
    end process;

    state_logic: process (state)
    begin
        -- Next State Logic
        -- Complete the following:
        next_state <= state;
        case(state) is
            when St_RESET =>
                if (valid = '1') THEN
                    next_state <= St_BOS_1;
                end if;
            when St_ERROR =>
                if (valid = '1' and din = "000") THEN
                    if (valid = '1' and din = "111") THEN
                        if (valid = '1' and din = "000") THEN
                            if ( valid = '1' and din = "111") THEN
                                next_state <= St_DECODE;
                            else
                                next_state <= St_ERROR;
                            end if;
                        end if;
                    end if;
                end if;
            when St_BOS_1 =>
                if (valid = '1' and din = "000") THEN
                    next_state <= St_BOS_2;
                elsif (valid = '1' and din > "111") THEN
                    next_state <= St_ERROR;
                else
                    next_state <= St_BOS_1;
                end if;
            when St_BOS_2 =>
                if (valid = '1' and din = "111") THEN
                    next_state <= St_BOS_3;
                elsif (valid = '1' and din > "111") THEN
                    next_state <= St_ERROR;
                else
                    next_state <= St_BOS_1;
                end if;
            when St_BOS_3 =>
                if (valid = '1' and din = "000") THEN
                    next_state <= St_BOS_4;
                elsif (valid = '1' and din > "111") THEN
                    next_state <= St_ERROR;
                else
                    next_state <= St_BOS_1;
                end if;
            when St_BOS_4 =>
                if (valid = '1' and din = "111") THEN
                    next_state <= St_DECODE;
                elsif (valid = '1' and din > "111") THEN
                    next_state <= St_ERROR;
                else
                    next_state <= St_BOS_1;
                end if;
            when St_EOS_1 =>
                if (valid = '1' and din = "111") THEN
                    next_state <= St_EOS_2;
                elsif (valid = '1' and din > "111") THEN
                    next_state <= St_ERROR;
                else
                    next_state <= St_BOS_1;
                end if;
            when St_EOS_2 =>
                if (valid = '1' and din = "000") THEN
                    next_state <= St_EOS_3;
                elsif (valid = '1' and din > "111") THEN
                    next_state <= St_ERROR;
                else
                    next_state <= St_BOS_1;
                end if;
            when St_EOS_3 =>
                if (valid = '1' and din = "111") THEN
                    next_state <= St_EOS_4;
                elsif (valid = '1' and din > "111") THEN
                    next_state <= St_ERROR;
                else
                    next_state <= St_BOS_1;
                end if;
            when St_EOS_4 =>
                if (valid = '1' and din = "000") THEN
                    next_state <= St_Out;
                elsif (valid = '1' and din > "111") THEN
                    next_state <= St_ERROR;
                end if;
            when St_DECODE =>
                if (valid = '1') THEN
                    for i in 0 to 7 loop
                        if (din = "001") THEN
                            if (din = "010") THEN
                                dout <= x"41";
                            elsif (din = "011") THEN
                                dout <= x"42";
                            elsif (din = "100") THEN
                                dout <= x"43";
                            elsif (din = "101") THEN
                                dout <= x"44";
                            elsif (din = "110") THEN
                                dout <= x"45";
                            end if;
                        elsif (din = "010") THEN
                            if (din = "001") THEN
                                dout <= x"46";
                            elsif (din = "011") THEN
                                dout <= x"47";
                            elsif (din = "100") THEN
                                dout <= x"48";
                            elsif (din = "101") THEN
                                dout <= x"49";
                            elsif (din = "110") THEN
                                dout <= x"4A";
                            end if;
                        elsif (din = "011") THEN
                            if (din = "001") THEN
                                dout <= x"4B";
                            elsif (din = "010") THEN
                                dout <= x"4C";
                            elsif (din = "100") THEN
                                dout <= x"4D";
                            elsif (din = "101") THEN
                                dout <= x"4E";
                            elsif (din = "110") THEN
                                dout <= x"4F";
                            end if;
                        elsif (din = "100") THEN
                            if (din = "001") THEN
                                dout <= x"50";
                            elsif (din = "010") THEN
                                dout <= x"51";
                            elsif (din = "011") THEN
                                dout <= x"52";
                            elsif (din = "101") THEN
                                dout <= x"53";
                            elsif (din = "110") THEN
                                dout <= x"54";
                            end if;
                        elsif (din = "101") THEN
                            if (din = "001") THEN
                                dout <= x"55";
                            elsif (din = "010") THEN
                                dout <= x"56";
                            elsif (din = "011") THEN
                                dout <= x"57";
                            elsif (din = "100") THEN
                                dout <= x"58";
                            elsif (din = "110") THEN
                                dout <= x"59";
                            end if;
                        elsif (din = "110") THEN
                            if (din = "001") THEN
                                dout <= x"5A";
                            elsif (din = "010") THEN
                                dout <= x"5B";
                            elsif (din = "011") THEN
                                dout <= x"5C";
                            elsif (din = "100") THEN
                                dout <= x"5D";
                            elsif (din = "101") THEN
                                dout <= x"5E";
                            end if;
                        end if;
                        dvalid <= '1';
                    end loop;
                next_state <= St_EOS_1;
                end if;
        end case;
    end process;

    output_logic: process (state)
    begin
        if (state = St_Out and valid = '1') THEN
            next_state <= St_RESET;
        end if;
    end process;

end Behavioral;

A: I suggest checking your code. It is missing a choice for St_Out of the state signal. Case statement must cover all possible values. This can be done using the when others => case, but this may not be suitable.
You will also have issues with this code. Your state_logic process is missing many signals. This will lead to simulation synthesis mismatch. You need to put every signal read inside the process inside the sensitivity list for an asynchronous process.
An easy fix for this is to use the VHDL 2008 process(all). This will force the compiler to work what the sensitivity list should be from the code inside the process.


Q: working out an average I have a nested list like so:
temperature = [["Jan", 12, 18, 16, 18], ["Feb", 10, 20, 50, 50], ["Mar", 23, 32, 10, 32]]

the list contains all the months up until December with the 3 highest temp recorded over the entire month and then the highest out of the 3 appended to the end of the list.
I have worked out the highest temp for each month in the following way:
def sortTemp():
    for temp in temperatures:
        temp = [temp[0], temp[4]]
        highest.append(temp)
    highest.sort()
    print(highest)

This works, however I had to work out the max values beforehand, and append it to the temperature list as explained above. Is there an easier way to do this?
Also, how do I work out the average temp of each month using the data provided in the temperature list, sorted by the highest average?
Output should be like:
AverageTemp = [["Month", AverageTemp], ["Month", AverageTemp]]

A: You can use a list comprehension to compute the averages
>>> AverageTemp = [[i[0], sum(i[1:])/len(i[1:])] for i in temperature]
>>> AverageTemp
[['Jan', 16.0], ['Feb', 32.5], ['Mar', 24.25]]

Or if you have numpy
>>> import numpy as np
>>> AverageTemp = [[i[0], np.mean(i[1:])] for i in temperature]
>>> AverageTemp
[['Jan', 16.0], ['Feb', 32.5], ['Mar', 24.25]]

Then to sort you can use the key and reverse arguments
>>> AverageTemp = sorted([[i[0], np.mean(i[1:])] for i in temperature], key = lambda i: i[1], reverse = True)
>>> AverageTemp
[['Feb', 32.5], ['Mar', 24.25], ['Jan', 16.0]]

A: You can use a list comprehension within sorted function :
>>> from operator import itemgetter
>>> sorted([[l[0],sum(l[1:])/4]for l in temperature],key=itemgetter(1),reverse=True)
[['Feb', 32], ['Mar', 24], ['Jan', 16]]

In preceding code you first loop over your list then get the first element and the avg of the rest by [l[0],sum(l[1:])/4] and use operator.itemgetter as the key of your sorted function to sort your result based on the second item (the average)

A: Understanding more about list comprehension and slice notation will really help you do this simply with pythonic code.
To explain @CoryKramer's first answer:
>>> AverageTemp = [[i[0], sum(i[1:4])/len(i[1:4])] for i in temperature]
>>> AverageTemp
[['Jan', 15], ['Feb', 26], ['Mar', 21]]

What he is doing is using i to cycle through the lists in temperature (which is a list of lists) and then using slice notation to get the info you need. So, obviously i[0] is your month, but the notation sum(i[1:4]) gets the sum of the items in the list from index 1 to the 3 using slice notation. He then divides by the length and creates the list of lists AverageTemp with the information you need.
Note: I have edited his answer to not include the high temperature twice per the comment from @TigerhawkT3.

A: That's not a very good structure for the given data: you have differentiated items (name of a month, temperatures, maximum temperature) as undifferentiated list elements. I would recommend dictionaries or objects.
months = {"Jan":[12, 18, 16], "Feb":[10, 20, 50], "Mar":[23, 32, 10]}
for month in sorted(months, key=lambda x: sum(months.get(x))/len(months.get(x)), reverse=True):
    temps = months.get(month)
    print(month, max(temps), sum(temps)/len(temps))

Result:
Feb 50 26.666666666666668
Mar 32 21.666666666666668
Jan 18 15.333333333333334

class Month:
    def __init__(self, name, *temps):
        self.name = name
        self.temps = temps
    def average(self):
        return sum(self.temps)/len(self.temps)
    def maximum(self):
        return max(self.temps)
months = [Month('Jan', 12, 18, 16), Month('Feb', 10, 20, 50), Month('Mar', 23, 32, 10)]
for month in sorted(months, key=lambda x: x.average(), reverse=True):
    print(month.name, month.maximum(), month.average())

Result:
Feb 50 26.666666666666668
Mar 32 21.666666666666668
Jan 18 15.333333333333334


Q: Symbol to method call Is there a way to transform a symbol to a method call? I know it's possible for a String, but not for a symbol. I have this code in conveyance.rb:
def boats
  boats = []
  User.all.each{ |u| boats += u.boats}
  boats
end
def boats_nb
  self.boats.length
end
def cars
  cars = []
  User.all.each{ |u| cars += u.cars}
  cars
end
def cars_nb
  self.cars.length
end

I would like to know if there is a means to make a method like that:
def conveyances(:symb)
  c = []
  User.all.each{ |u| c += u.to_method(:symb) }
  c
end
def conveyances_nb(:symb)
  User.to_method(:symb).length
end

A: You could use Object#public_send method:
def conveyqnces_nb(symb)
  User.public_send(symb).length
end

or, if you would like, Object#send might be suitable. The difference is that send allows to call private and protected methods, while public_send acts as typical method call - it raises an error if method is private or protected and the caller object isn't allowed to call it.

A: Use the #send instance method
u.send(:symb)


Q: input css rendering inconsistencies across browsers The input button is incorrectly higher than the input field.
I used Firebug to copy all the styles applied to the 3 elements in question (the containing p element and the 2 child input elements) to replicate the problem.
http://jsfiddle.net/XBjz3/
I have a feeling it's to do with me using negative relative positioning on the input button.
Displays as it should in

*

*Firefox 12

*Chrome 19

*Internet Explorer 9

Displays wrong in

*

*Android 2.3.5 browser

*iOS 5.1 browser

*Safari 5.1.7

*Opera 11.6

It's strange that it displays fine in Chrome when the 3 other webkit browsers renders it incorrectly.

A: Instead of using
top:-0.5em;

You can use
bottom : 0.4em;

As its not good practice to use negative values for position.

A: check this one i hope this will help you..
HTML
<p>
    <input type="password" class="pw-box" id="pwbox-33" name="post_password">
    <input type="submit" class="pw-submit" value="Submit" name="Submit">
</p>

CSS
p {

    width:50%;
    display: inline;
    float: left;
    padding-left: 1%;
    padding-right: 1%;
    position: relative;
    font-size: 1em;
    line-height: 1.5em;
    margin:20px 0 0 20px;
    background:rgba(0,0,0,0.1);

}
#pwbox-33 {
    width: 200px;
    border:0;
    background: #606D80;
    border-top:solid 1px  #1F3453;
    color: #DCE0E6;
    margin: 0;
    padding: 0.5em;
    text-shadow: 0 1px 0 #1F1F20;
    vertical-align: top;
}
.pw-submit{
cursor: pointer;
    background:#2B4C7E;
    color: #DCE0E6;
    padding: 0.5em 1em;
    position: absolute;
    text-shadow: 0 -1px 0 #1F1F20;
    top: -0.3em;
    border:0;
    font-size:12px;
    font-family:arial;
    left:200px;
    border-bottom:solid 0.5em #0E2952;
    outline:0;

}

http://jsfiddle.net/YjNJ5/3/

A: Found a solution that looks exactly the same as intended.
http://jsfiddle.net/XBjz3/8/
Here are the changes from the original.
#pwbox-33 {
    vertical-align: bottom;
}
.pw-submit {
    top: 0;
    vertical-align: bottom;
}

Tested to work on Firefox, Chrome, IE, Safari, Opera, and Android stock browser.


Q: iPhone simulator screenshot not capturing device bezel I'm trying to capture a simulator screenshot using Xcode 12. Right now, even though the "Show Device Bezels" option is enabled (and it shows the bezels on the screen), when I take the screenshot, the bezel isn't part of the resulting screenshot. I've tried through the camera button on the simulator, through the "Save Screen" menu item, through "xcrun simctl screenshot" command-line as well, but it doesn't work correctly.
Weirdly, it was working fine just yesterday, but I was playing with setting the "defaults write com.apple.screencapture disable-shadow -bool TRUE" from the command-line (to prevent the shadow in video capture of the window) ... I'm not sure if that's related to this issue, and I flipped it back to FALSE, but that doesn't seem to help either.
I've also tried restarting the simulator, restarting the Mac, switching "Show Bezel" on/off, using Xcode11, erasing contents of simulator.... but it's still not working. Very frustrating.
This is what it looks like:

Any tips of what I can try?
Thanks.

A: The bezel is not saved as part of the screenshots from Simulator.app / simctl.  The only option you have is whether or not the framebuffer mask is applied.
If you want the bezel, you'll need to use the macOS screenshot support.  Hit shift-cmd-4, then hit space to toogle from "draw the rectangle" mode to "select the window" mode.  Then click on the window to take a screenshot.


Q: Redundant distributed NFS file system and replication factor > 1. Is it safe for Kafka deployment? I have a cluster Kafka set up where the log.dir is set to a mounted NFS path pointing to distributed file system which all the brokers have access to.
Since the distributed file system provides all the redundancy I need, is it really necessary have a replication factor > 1?
Also, I read in this article https://engineering.skybettingandgaming.com/2018/07/10/kafka-nfs/ that you are not recommended to have the logs on an NFS mounted filesystem. Does this still hold and does anyone have any more experience in doing this?

A: From the storage side, maybe this is safe, but your single replica is only able to be read / sent from a single broker.
If that machine goes down, the data will still be available on your backend, sure, but you cannot serve requests for it without knowing there is another replica for that topic (replication factor < 2).


Q: Output only one blank line fresh-line outputs a newline only if we are not already at start of the line, in other words goes to the next line but never produces a blank line, in other words outputs a maximum of one consecutive newline character.
I need a function that outputs a blank line only if we have not just output one already, in other words outputs a maximum of two consecutive newline characters.
Or put another way, I'm looking for an idempotent blank-line function, one which will output exactly one blank line even if called several times.
What's the best way to do this?

A: If I understand correctly your question, I think you can use the following property of fresh-line (see the manual):

fresh-line returns true if it outputs a newline; otherwise it returns false.

to define something like:
(defun my-fresh-line ()
  (unless (fresh-line)
    (terpri)))

If, on the other hand, you want always a blank line after the current written text, be it terminated with a new line or not, you can define something like:
(define blank-line ()
  (fresh-line)
  (terpri))

and then call it after the current output.


Q: jboss-eap-6.1 oracle driver definition when installed as deployment I have several Jboss EAP 6.1 installations working with Oracle driver installed as a module.
This is the standard configuration I use in standalone.xml:
<datasource jndi-name="java:jboss/fooDatasource" pool-name="java:jboss/fooDatasource" enabled="true" use-java-context="false" >
 <connection-url>jdbc:oracle:thin:@1.2.3.4:1527/SOMEDB.foo</connection-url>
 <driver>oracle</driver>
     <security>
         <user-name>xxxxx</user-name>
             <password>xxxxxxxxx</password>
     </security>
 [...]
</datasource>
<driver name="oracle" module="oracle.jdbc">
    <xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource</xa-datasource-class>
    <datasource-class>oracle.jdbc.OracleDriver</datasource-class>
</driver>

The ojdbc6.jar is in $JBOSS_HOME/modules/system/layers/base/oracle/jdbc/main/ together with the appropriate module.xml and everything works fine.
Now a customer required to install the driver as a deployment, so I moved ojdbc6.jar to $JBOSS_HOME/standalone/deployments/ and I see from logs that it is deployed without errors:
[org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-3) JBAS010403: Deploying JDBC-compliant driver class oracle.jdbc.OracleDriver (version 11.2)
INFO  [org.jboss.as.server] (ServerService Thread Pool -- 25) JBAS018559: Deployed "ojdbc6.jar" (runtime-name : "ojdbc6.jar")

But I don't know how to edit my standalone.xml to make it work again: i tried to edit the driver definition "module" attribute with several different values (ojdbc6.jar, deployment.ojdbc6.jar, oracle.jdbc.OracleDriver...) but none seem to "match" and Jboss keeps throwing errors at startup:
ERROR [org.jboss.as.controller.management-operation] (ServerService Thread Pool -- 24) JBAS014613: Operation ("add") failed - address: ([
("subsystem" => "datasources"),
("jdbc-driver" => "oracle")
]) - failure description: "JBAS010441: Failed to load module for driver [ojdbc6.jar]"
[...]
INFO  [org.jboss.as.controller] (Controller Boot Thread) JBAS014774: Service status report
JBAS014775:    New missing/unsatisfied dependencies:
  service jboss.jdbc-driver.oracle (missing) dependents: [service jboss.driver-demander.java:jboss/spiDatasource, service jboss.data-source.java:jboss/fooDatasource]

Could anyone please provide a working example of the driver definition?
Thanks

A: Ok, I found the answer myself.
Surprisingly, all the guides I found around explain how to do this configuration via web admin interface or via jboss-cli, but no one in the Jboss community seem to bother explaining how to manually edit the standalone.xml to do the job.
This is a working example (basically I just deleted the entire Oracle driver definition section and replaced the driver name in the datasource definition with the name of the runtime name of the deployed jar file):
<datasource jta="false" jndi-name="java:/jdbc/fooDS" pool-name="foo-ds" use-ccm="false">
    <connection-url>jdbc:oracle:thin:@1.2.3.4:1527/SOMEDB.foo</connection-url>
    <driver-class>oracle.jdbc.OracleDriver</driver-class>
    <driver>ojdbc6.jar</driver>

    [...] other datasource stuff here

</datasource>

# DELETE FROM HERE...
<driver name="oracle" module="oracle.jdbc">
    <xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource</xa-datasource-class>
    <datasource-class>oracle.jdbc.OracleDriver</datasource-class>
</driver>
# ...TO HERE

That's all.

A: Probably you have to mention in this way...
<subsystem xmlns="urn:jboss:domain:datasources:1.1">
        <datasources>
            <datasource jndi-name="java:jboss/XXX" pool-name="XXX"     enabled="true" use-java-context="true">
                <connection-url>jdbc:oracle:thin:@SID:PORT:DBNAME</connection-url>
                <driver>oracle</driver>
                <security>
                    <user-name>user</user-name>
                    <password>password</password>
                </security>
            </datasource>
            <drivers>
                <driver name="oracle" module="com.oracle">
                    <xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource</xa-datasource-class>
                    <datasource-class>oracle.jdbc.OracleDriver</datasource-class>
                </driver>
            </drivers>
        </datasources>
</subsystem>

A: *

*Create directories like x1/x2/main

*Create module.xml file under main directory

*Keep ojdbc6-11.1.1.3.0.jar  in main directory level

In Module.xml
<module xmlns="urn:jboss:module:1.1" name="x1.x2">
<properties>
    <property name="jboss.api" value="unsupported"/>
</properties>
<resources>
    <resource-root path="ojdbc6-11.1.1.3.0.jar"/>
</resources>
<dependencies>
    <module name="javax.api"/>
    <module name="javax.transaction.api"/>
    <module name="javax.servlet.api" optional="true"/>
</dependencies>

In domain.xml
<datasource jndi-name="java:/TestName" pool-name="TestName" enabled="true" use-java-context="true">
                    <connection-url>jdbc:oracle:thin:@ldap://xxxxx:3000/UKXXX,cn=OracleContext,dc=dcm,dc=XXXX</connection-url>
                    <driver>dps</driver>
                    <security>
                        <user-name>XXXXX</user-name>
                        <password>*****</password>
                    </security>
                </datasource>
                <drivers>
                    <driver name="dps" module="x1.x2">
                        <xa-datasource-class>oracle.jdbc.driver.OracleDriver</xa-datasource-class>
                    </driver>
                    </driver>
                </drivers>

Try to keep the correct ojdbc jar, some versions won't work :)


Q: prototype.js innerHTML does not work with IE Apparently IE (10) does not like this piece of code:
$('size_list').innerHTML = '<form id="dropdown_menu"><select id="dropdown_options"></select></form>';

The dropdown menu is not being generated. I get an Unknown Run Time error, which is really "helpful". The next line of code is:
$('dropdown_options').innerHTML = '<option>Choose size</option>';

But when I debug - I don't even get till here.
The 'size_list' element is just a simple empty div:

I found some info that states .innerHTML does not really work with IE, but I have many other places in my script where I assign even bigger chunks of HTML to div elements, through .innerHTML and all works. Except the upper stated assigning of dropdown form.

A: Try this:
$('#size_list').html('<form id="dropdown_menu"><select id="dropdown_options"></select></form>');
$('#dropdown_options').html('<option>Choose size</option>');

You can't use a hammer as a wrench...
Or use document.getElementById('size_list').innerHTML or use $('#size_list').html()
Don't forget to put a # before an id selector in jQuery and a . before a class selector otherwise jQuery tries to find a <size_list> tag which won't exist in the DOM tree.

A: First of all, while it may be convenient to add select options using the direct insert html methods, it rarely works universally. The bulletproof way to add options to a select is to build them up one at a time in a loop, assigning their value and label the old-fashioned way.
var form = new Element('form', {id: 'dropdown_menu' });
var picker = new Element('select', {id: 'dropdown_options', size: 1 });
$('size_list').insert(form);
form.insert(picker);
picker.options[picker.options.length] = new Option('Choose size', '');
// want to add a list of elements in a loop?
$w('Foo Bar Baz').each(function(val){
  picker.options[picker.options.length] = new Option(val, val);
});

IE has never dealt with modifications of the select element gracefully at all, this goes back to IE 5 when I first started trying to do this sort of thing.


Q: jQuery focus after submit on last input field edited On jQuery keyup on two IDs a function is executed.
$('#supplier_name').keyup(function(){
    clearTimeout(typingTimer);
    if ($('#supplier_name').val) {
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    }
    $.cookie("inputFocus", "#supplier_name");
});

After this the form is submitted. I want to do jQuery .focus on the ID which led the keyup function to execute.
So if I entered text into #supplier_name after form submit I want the focus to be on that. Vice versa with #aircraft_type.
EDIT: I am trying to do this via cookies however it doesn't seem to be working.
How do I do this with the following jQuery code:
<script>
$(document).ready(function() {
    $("#state").change(function () {
    this.form.submit();
})
$.cookie("inputFocus").focus();
$("#supplier_name").val($("#supplier_name").val());
$("#aircraft_type").val($("#aircraft_type").val());
var typingTimer;
var doneTypingInterval = 800;

$('#supplier_name').keyup(function(){
    clearTimeout(typingTimer);
    if ($('#supplier_name').val) {
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    }
    $.cookie("inputFocus", "#supplier_name");
});

$('#aircraft_type').keyup(function(){
    clearTimeout(typingTimer);
    if ($('#aircraft_type').val) {
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    }
    $.cookie("inputFocus", "#aircraft_type"); });

function doneTyping () {
    $("form").submit();
}

});
</script>

A: The solution to the above problem was to create an object to use focus() and to add the jQquery cookie plug-in.
The change is below:
"$.cookie("inputFocus").focus();" to "$($.cookie("inputFocus")).focus()"
Added the below code to the page:
""