text:
Q: Is there any way to copy a text from another program without Select it? I want to copy text from other program,
in this program Ctrl+a is considered for other command, and I can't use " SendKeys.SendWait("^a");" to select the text.
Is there any way to copy that text?

A: You can do that with UIAComWrapper, you will need handle to that window (from where you are trying to copy) and information about that element which you can get from UIAutomationVerify.
var elementCollection = AutomationElement.FromHandle(windowHandle).FindAll(TreeScope.Subtree, Condition.TrueCondition);
foreach (var item in elementCollection)
{
   //check item properties if element is the one you looking for
}

Also, instead of Condition.TrueCondition you can provide more complex filter to get only that one element.
Edit, added real example:
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
const string InternetExplorerClass = "IEFrame";
static void Main()
{
    var windowHandle = new IntPtr(0);

    //Find internet explorer instance
    windowHandle = FindWindow(InternetExplorerClass, null);

    if (!windowHandle.Equals(IntPtr.Zero))
    {
        //create filter to improve search speed
        var localizedControlType = new PropertyCondition(
            AutomationElement.LocalizedControlTypeProperty,
            "tab item");

        //get all elements in internet explorer that match our filter
        var elementCollection =
            AutomationElement.FromHandle(windowHandle)
                .FindAll(TreeScope.Subtree, localizedControlType);

        //iterate through search results
        foreach (AutomationElement item in elementCollection)
        {
            Console.WriteLine(item.Current.Name);
        }
    }
    else
    {
        Console.WriteLine("Internet explorer not found");
    }

    Console.ReadLine();
}

Code above will find Internet Explorer and will print all tab titles to console. I put source code to GitHub.

A: What kind of editor is that, and why you can't just get source file? Maybe that will work:
   1. Place cursor on the start of the first line
   2. Hit Ctrl+Shift+End
   3. Ctrl+C
Alternatively, you can try to simulate keyboard input through Windows Input Simulator library


text:
Q: Logstash filtering I have a python script that writes JSON objects (line by line) to /var/log/myLog.json with following format:
{"timestamp":"2016-07-21T01:20:04.392799-0400","in_iface":"docker0","event_type":"alert","src_ip":"172.17.0.2","dest_ip":"172.17.0.3","proto":"ICMP","icmp_type":0,"icmp_code":0,"alert":{"action":"allowed","**gid**":2,"signature_id":2,"rev":0,"signature":"ICMP msg","category":"","severity":3},"payload":"hFuQVwAA","payload_printable":"kk"}

I'd like to use Logstash in order to:

*

*Read the json objects, line by line, from /var/log/myLog.json

*Parse the gid and forward to another machine as a udp msg (given a specific IP address+port) --  For example:   if gid==2  then forward this json object to 172.123.10.3:10001
Additionally, I'd like to be able to update that Logstash configuration file filter dynamically (Aka, to be able to add another rule like:   "if gid==x then forware this json object to another IP).
How can I do so?
How should the Logstash conf file(s) should look like?
And how the command to insert/delete dynamic filters look like?
Thanks, guys.

A: You can running the logstash as belows configuration.
and I have tested two sample json data.
{"timestamp":"2016-07-21T01:20:04.392799-0400","in_iface":"docker0","event_type":"alert","src_ip":"172.17.0.2","dest_ip":"172.17.0.3","proto":"ICMP","icmp_type":0,"icmp_code":0,"alert":{"action":"allowed","gid":2,"signature_id":2,"rev":0,"signature":"ICMP msg","category":"","severity":3},"payload":"hFuQVwAA","payload_printable":"kk"}
{"timestamp":"2016-07-21T01:20:04.392799-0400","in_iface":"docker0","event_type":"alert","src_ip":"172.17.0.2","dest_ip":"172.17.0.3","proto":"ICMP","icmp_type":0,"icmp_code":0,"alert":{"action":"allowed","gid":3,"signature_id":2,"rev":0,"signature":"ICMP msg","category":"","severity":3},"payload":"hFuQVwAA","payload_printable":"kk"}

input {
  file {
        path => "/etc/logstash/jsonSample.log"
       start_position => "beginning"
       sincedb_path => "/dev/null"
   }
}

filter {
                json {
                        source => "message"
                        target => "doc"
                        add_field => {"alert.gid" => "%{[doc][alert][gid]}"}
                        add_tag => ["tagName_%{[doc][alert][gid]}"]
                }

}

output {
if "tagName_2" in [tags] {
 stdout {codec => rubydebug}
}else if "tagName_3" in [tags] {
}

}

Then you can see the result
{
       "message" => "{\"timestamp\":\"2016-07-21T01:20:04.392799-0400\",\"in_iface\":\"docker0\",\"event_type\":\"alert\",\"src_ip\":\"172.17.0.2\",\"dest_ip\":\"172.17.0.3\",\"proto\":\"ICMP\",\"icmp_type\":0,\"icmp_code\":0,\"alert\":{\"action\":\"allowed\",\"gid\":2,\"signature_id\":2,\"rev\":0,\"signature\":\"ICMP msg\",\"category\":\"\",\"severity\":3},\"payload\":\"hFuQVwAA\",\"payload_printable\":\"kk\"}",
      "@version" => "1",
    "@timestamp" => "2016-07-25T04:41:11.980Z",
          "path" => "/etc/logstash/jsonSample.log",
          "host" => "baklava",
           "doc" => {
                "timestamp" => "2016-07-21T01:20:04.392799-0400",
                 "in_iface" => "docker0",
               "event_type" => "alert",
                   "src_ip" => "172.17.0.2",
                  "dest_ip" => "172.17.0.3",
                    "proto" => "ICMP",
                "icmp_type" => 0,
                "icmp_code" => 0,
                    "alert" => {
                  "action" => "allowed",
                     "gid" => 2,
            "signature_id" => 2,
                     "rev" => 0,
               "signature" => "ICMP msg",
                "category" => "",
                "severity" => 3
        },
                  "payload" => "hFuQVwAA",
        "payload_printable" => "kk"
    },
     "alert.gid" => 2,
          "tags" => [
        [0] "tagName_2"
    ]
}

You can also change the configuration applied as above it.
Regards.
You can refer the configuration of event and json filter
https://www.elastic.co/guide/en/logstash/current/event-dependent-configuration.html
https://www.elastic.co/guide/en/logstash/current/plugins-filters-json.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to display callstack line numbers when my program is broken in Rust? I use RUST_BACKTRACE=full ./my-program to run my compiled program.
However, I get a message like below which has only the function address without line numbers.
thread 'main' panicked at 'index out of bounds: the len is 6 but the index is 6', src/libcore/slice/mod.rs:734
stack backtrace:
   0:        0x100a26463 - std::sys::imp::backtrace::tracing::imp::unwind_backtrace::hbdeac7eba2f064c6
   1:        0x100a2786d - std::panicking::default_hook::{{closure}}::h9e0a6ca9bb64b479
   2:        0x100a27434 - std::panicking::default_hook::h9043ae80af471c9f
   3:        0x100a29f17 - std::panicking::rust_panic_with_hook::h05996066754c6be9
   4:        0x100a29e04 - std::panicking::begin_panic::h9fecf34da42eb910
   5:        0x100a29d22 - std::panicking::begin_panic_fmt::he5aad713258a67c3
   6:        0x100a29c87 - rust_begin_unwind
   7:        0x100a4a5f0 - core::panicking::panic_fmt::he26d734b771c5b2c
   8:        0x100a4a568 - core::panicking::panic_bounds_check::h19dd3f615b4fea05
   9:        0x100a1fc76 - <usize as core::slice::SliceIndex<[T]>>::index::h1f41340feec36937
  10:        0x100a1f744 - core::slice::<impl core::ops::Index<I> for [T]>::index::h3246d2321fb7f789
  11:        0x100a205b6 - sort::merge::h697218a53d5049aa
  12:        0x100a20227 - sort::merge_sort::h10fe012581f48b43
  13:        0x100a201e5 - sort::merge_sort::h10fe012581f48b43
  14:        0x100a201e5 - sort::merge_sort::h10fe012581f48b43
  15:        0x100a20159 - sort::merge_sort_pub::hb18b616b61510f3b
  16:        0x100a20e24 - sort::main::hffac78b51f3ea2c3
  17:        0x100a29c45 - std::panicking::try::do_call::h24a2756282b9a31c
  18:        0x100a2ba2a - __rust_maybe_catch_panic
  19:        0x100a2a1d0 - std::rt::lang_start::hd19f94db0c6a490e
  20:        0x100a20fc9 - main

Is there any method to add the line numbers at the break spot?

A: This problem is a cross-platform issue and is tracked as Rust issue 24346. My workspace is macOS 10.12.4:
>rustc -vV
rustc 1.18.0-nightly (2564711e8 2017-04-04)
binary: rustc
commit-hash: 2564711e803f62e04bebf10408cc1c11297c0caf
commit-date: 2017-04-04
host: x86_64-apple-darwin
release: 1.18.0-nightly
LLVM version: 3.9

The workaround is to use a debugger to get the callstack information.
I have a hellobugs.rs file only present several lines of buggy code. At line 3, I cause a panic due to accessing the vector out of bounds:
fn main() {                // 1
    let v = vec![1, 2, 3]; // 2
    println!("{}", v[4]);  // 3
}                          // 4

Compile this with rustc hellobugs.rs -g -o hellobugs Don't forget the -g argument.
Running with RUST_BACKTRACE=full ./hellobugs will get backtraces but without line numbers on my macOS. As the issue says, we can use rust-lldb hellobugs to debug it and get detailed backtraces. Of course, using lldb is okay as well:
>rust-lldb hellobugs
    ...lots of rust-lldb message...
(lldb) breakpoint set -b rust_begin_unwind
Breakpoint 1: where = hellobugs`std::panicking::rust_begin_panic + 4 at panicking.rs:468, address = 0x000000010000a5b4
(lldb) r
Process 41626 launched: '/Users/xxx/bin/hellobugs' (x86_64)
hellobugs was compiled with optimization - stepping may behave oddly; variables may not be available.
Process 41626 stopped
* thread #1: tid = 0x6c3e39, 0x000000010000a5b4 hellobugs`std::panicking::rust_begin_panic + 4 at panicking.rs:468, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
    frame #0: 0x000000010000a5b4 hellobugs`std::panicking::rust_begin_panic + 4 at panicking.rs:468 [opt]
(lldb) bt
* thread #1: tid = 0x6c3e39, 0x000000010000a5b4 hellobugs`std::panicking::rust_begin_panic + 4 at panicking.rs:468, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
  * frame #0: 0x000000010000a5b4 hellobugs`std::panicking::rust_begin_panic + 4 at panicking.rs:468 [opt]
    frame #1: 0x000000010002af51 hellobugs`core::panicking::panic_fmt + 129 at panicking.rs:69 [opt]
    frame #2: 0x000000010002aec9 hellobugs`core::panicking::panic_bounds_check + 105 at panicking.rs:56 [opt]
    frame #3: 0x0000000100001726 hellobugs`collections::vec::{{impl}}::index<i32>(self=0x00007fff5fbff720, index=4) + 118 at vec.rs:1426
    frame #4: 0x0000000100001826 hellobugs`hellobugs::main + 182 at hellobugs.rs:3
    frame #5: 0x000000010000a5a6 hellobugs`std::panicking::try::do_call<fn(),()> [inlined] core::ops::FnOnce::call_once<fn(),()> + 6 at ops.rs:2606 [opt]
    frame #6: 0x000000010000a5a4 hellobugs`std::panicking::try::do_call<fn(),()> + 4 at panicking.rs:454 [opt]
    frame #7: 0x000000010000c38b hellobugs`panic_unwind::__rust_maybe_catch_panic + 27 at lib.rs:98 [opt]
    frame #8: 0x000000010000ab31 hellobugs`std::rt::lang_start [inlined] std::panicking::try<(),fn()> + 44 at panicking.rs:433 [opt]
    frame #9: 0x000000010000ab05 hellobugs`std::rt::lang_start [inlined] std::panic::catch_unwind<fn(),()> at panic.rs:361 [opt]
    frame #10: 0x000000010000ab05 hellobugs`std::rt::lang_start + 325 at rt.rs:57 [opt]
    frame #11: 0x000000010000192a hellobugs`main + 42
    frame #12: 0x00007fffdfc5f235 libdyld.dylib`start + 1
(lldb)

My results are as above. You can see at frame #4 there comes the buggy result of at hellobug.rs:3. This informs us the 3rd line has a bug. It is a little bother to use lldb and trace, but it's accurate!


text:
Q: SQL Server Reference/Lookup Tables and Updates I have two SQL tables: TableA and LookupTable. TableA stores LookupTableID (PK) as a foreign key and some other fields. The LookupTable stores LookupTableID, PharmacyName, PharmacyAddress, PostCode, PharmacyTelephone, PharmacyFax, PharmacyEmail etc.
The data from TableA is displayed in an Asp.net form. The form has two buttons for each row of the grid: Print button and Preview button. When user clicks Print button, a pdf document containing the pharmacy information from LookupTable (for LookupTableID in TableA) along with some other information from TableA is produced in the document. Moreover, the Printed field in TableA is set to true, and a new record in TableA is created, the only difference between the printed and the newly created record is in the following fields: StartDate, EndDate and Printed. In the newly created record, StartDate becomes "EndDate from printed record + 1 Day", EndDate becomes "EndDate from printed record + 7 days", and Printed is false for the newly created record.
When user clicks Preview button, a pdf document containing the pharmacy information from LookupTable (for LookupTableID in TableA) along with some other information from TableA is produced in the document. Note that the system doesn't create a new record or set printed to true in this case.
The issue that I have with above database design is: if one of the columns lets say PostCode in the Lookup Table is amended and user clicks on Preview button for historical/printed records then the preview pdf document will display up to date information i.e. new post code rather than the post code at the time of the printing. I know, this is an expected behaviour. However, I would like to display the information for historical records as they were printed, and the up to date information for only those records which are not yet printed.
One work around that I have is to treat LookupTable as a library table for the user to select a pharmacy and then copy everything (all fields from the lookup table) across to the TableA for the selected pharmacy. This will create a lot of duplicate data in the database. Is there a better way to achieve my objective? Any help would be appreciated.

A: For historical data there are (at least) two approaches:

*

*You store your information with a ValidUntil date. The one with a NULL is the current.

Older data can be found with something similar to:
DECLARE @test TABLE(id INT,ValidUntil DATETIME);
INSERT INTO @test VALUES(1,{d'2015-01-01'})
                       ,(2,{d'2015-02-01'})
                       ,(3,{d'2015-03-01'})
                       ,(4,NULL);

DECLARE @ValidOn DATETIME={d'2015-01-02'}; --set any value you like, even NULL

WITH HelperDates AS
(
    SELECT ISNULL(@ValidOn,GETDATE()) AS ValidOn
          ,(SELECT MAX(ValidUntil) FROM @test) AS MaxDate
)
SELECT TOP 1 tbl.*
FROM @test AS tbl
CROSS JOIN HelperDates AS hd
WHERE hd.MaxDate IS NULL OR hd.ValidOn > hd.MaxDate OR  hd.ValidOn <= tbl.ValidUntil
ORDER BY tbl.ValidUntil ASC

Especially with out-prints I'd prefer this way

*Store the necessary data in the moment of creation of your document. Best in my eyes is an XML column together with the created document.

Good luck in finding the best approach!

A: This seems like a needlessly complicated and inflexible way of taking a snapshot of your data every time it is printed. It would seem like a much better alternative would be to version both tables and create a third table which would just contain the TableA ID and the date it was printed. There is no need to make a copy of the data. To reproduce the data as it was on the date of any particular print, just use the print date to query the versioned data as of that date. You would get back the data as it appeared on that date, no matter how much it changed since then.
One answer I have given for a similar situation is here:
https://dba.stackexchange.com/questions/114580/best-way-to-design-a-database-and-table-to-keep-records-of-changes/114738#114738
Hope it helps.


text:
Q: Modify scale of Datadog metric I have a time series presenting time values like this one:

I want to change the y-axis to represent hours instead of milliseconds, i.e. divide by 3600. Any idea how to do it?

A: This can be achieved in two ways.
If you only want this logic to applied on this one graph, you can divide metric either using the UI editor and clicking advanced or using the JSON editor:
UI Editor: http://cl.ly/1c0K2O3P1E2K
Or JSON editor: https://help.datadoghq.com/hc/en-us/articles/203764925-How-do-I-use-arithmetic-for-my-time-series-data-
Alternatively, you can use the Metric Summary page to edit this metric's metadata and alter this metric's unit throughout the application as seen here: http://cl.ly/2x0Z290w2I3V
https://app.datadoghq.com/metric/summary
Hope this helps.  Also, you can reach out to support@datadoghq.com if you run into any other issues in the future.

A: You can update metric unit to correct type on Metric details sidepanel of Metrics Summary page: https://docs.datadoghq.com/metrics/summary/#metric-unit.

You can get to Metrics Summary page by opening edit tab of your dashboard, clicking on your metric, and clicking on Edit in Metrics Summary link.


text:
Q: Creating a before and after from a Registry key value on a remote server I'm a little lost as to why I'm unable to get a registry key value before, make a change then collect the value after the change to confirm the change was successful.
I'm using the following code which gets the correct values but doesn't reflect any changes I make to LogMaxHistory or LogLevel.
Am I doing something incorrect?
foreach ($server in $servers) {
    $Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", $server)

    $RegSubKey = $Reg.OpenSubKey("SOFTWARE\\Microsoft\\CCM\\Logging\\@Global", $true)

    $LogLevelBefore      = $RegSubKey.GetValue('LogLevel')
    $LogMaxHistoryBefore = $RegSubKey.GetValue('LogMaxHistory')

    $RegSubKey = $Reg.SetValue('LogLevel', '0', [Microsoft.Win32.RegistryValueKind]::DWORD)
    $RegSubKey = $Reg.SetValue('LogMaxHistory', '6', [Microsoft.Win32.RegistryValueKind]::DWORD)

    $RegCheck = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", $server)
    $RegCheck = $RegCheck.OpenSubKey("SOFTWARE\\Microsoft\\CCM\\Logging\\@Global")

    $LogLevelAfter      = $RegCheck.GetValue('LogLevel')
    $LogMaxHistoryAfter = $RegCheck.GetValue('LogMaxHistory')

    [pscustomobject]@{
        ComputerName        = $server
        LogLevelBefore      = $LogLevelBefore
        LogMaxHistoryBefore = $LogMaxHistoryBefore
        LogLevelAfter       = $LogLevelAfter
        LogMaxHistoryAfter  = $LogMaxHistoryAfter
    }
    $Reg.Close()
    $RegCheck.Close()
    GSV -ComputerName $server -Name CcmExec | Restart-Service
}

A: You can use Regquery
example
$before=reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\" /ve /s

$after=reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\" /ve /s

write-host "registry value $before and $after" -F green

A: Have you tried overloaded method OpenSubKey with RegistryKeyPermissionCheck type and RegistryKeyPermissionCheck.ReadWriteSubTree argument (see: MSDN)?
Another aproach is to use registry drives as follows (simplified, you must change keys and properties):
$server = '.'
Invoke-Command -ComputerName $server {
    $before = Get-ItemProperty HKLM:\SOFTWARE\PDProgs -Name Property1
    Set-ItemProperty HKLM:\SOFTWARE\PDProgs -Name Property1 -Value (Get-Random)
    $after = Get-ItemProperty HKLM:\SOFTWARE\PDProgs -Name Property1
    [psobject]@{Before = $before.Property1; After = $after.Property1}
} `
   | % { "Before = $($_.Before), After = $($_.After)" }


text:
Q: is there a way to find out if the user has given permision to notification? After I ask_for_permission the user of the site I would like to know if he gave the permission so I can fire the send() function.
What is the most elegant way to do it ?

A: Check the permission property of the Notification object:
if (Notification.permission === "granted") {
    // your code here


text:
Q: Is it possible to implement (in Scala) a polymorphic wrapper class that automatically implements the methods of the wrapped class? I would like to implement a wrapper class similar to this:
class Wrapper[A](wrapped: A) {
  ...
}

And I would like it to behave like this:
val a: Wrapper[Int] = new Wrapper(2)
val b: Wrapper[Int] = new Wrapper(3)

val c = a + b  // "c" should be equal to Wrapper(5)
val d = a * b  // "d" should be equal to Wrapper(6)

val e: Wrapper[String] = new Wrapper("Hello ")
val f: Wrapper[String] = new Wrapper("World")

val g = e + f // "g" should be equal to Wrapper("Hello World")

But I do not want to manually implement the "+" and "*" methods inside the Wrapper class; because in general I do not know which methods the class A will have, and I want Wrapper to have all methods that A has, for any A.
Is this possible at all (in Scala)?
I suspect the answer is "no", but I would like to confirm. And if so, is there any alternative way to achieve this sort of generic behaviour?

A: Yes, it's possible in Scala, and Monoid can help you implement this.

*

*Create Monoid that help lift type with some method

*implement the specify type Monoid  with extend from Monoid trait in Monoid Object

*implement the custom method like the below IntMonoid StringMonoid.

*Create the MonoidOp it's used for implicit convert type to the MonoidOp, like the below: WrapperMonoIdOp and implicit def wrapperMonoid.
Code Example:
//It's a Monoid that lift a type to Monoid
trait Monoid[A] {
  def mappend(a1: A, a2: A): A
}
object Monoid {
  implicit object IntMonoid extends Monoid[Int] { //Implement method with type
    override def mappend(a1: Int, a2: Int): Int = a1 + a2
  }
  implicit object StringMonoid extends Monoid[String] {
    override def mappend(a1: String, a2: String): String = a1 + "" + a2
  }
}
trait WrapperMonoIdOp[A] {  //MonoidOp it will be used to implicit convert type to the MonoIdOp
  val F: Monoid[A]
  val value: A
  def +(a2: Wrapper[A]): Wrapper[A] = {
    new Wrapper[A](F.mappend(value, a2.wrapped))
  }
}
class Wrapper[A](val wrapped: A) {
  override def toString: String = wrapped.toString
}
object TmpTest {
  implicit def wrapperMonoid[A: Monoid](a: Wrapper[A]): WrapperMonoIdOp[A] = new WrapperMonoIdOp[A] { //implicit convert the wrapper class to MonoidOp
    override val F: Monoid[A] = implicitly[Monoid[A]] //implictly Monoiid
    override val value: A = a.wrapped
  }
  def main(args: Array[String]): Unit = {
    val a = new Wrapper(1)
    val b = new Wrapper(2)
    println(a + b)
    val c = new Wrapper("hello")
    val d = new Wrapper("world")
    println(c + d)
  }
}

and If we invoke + with not implemented type, the compiler will throw compile error, like:
val a = new Wrapper(1.1)
val b = new Wrapper(1.2)
a + b // compiler will throw type mismatch.

Tutorial for this: http://eed3si9n.com/learning-scalaz/7.0/sum+function.html

A: You can't do it fully automatic, you'll have to implement '+' function for each type anyway. One of the possible approaches is to use implicit functions:
case class Wrapper[A](wrapped:A) {
  def +(b:Wrapper[A])(implicit sm: (A, A) => A) = Wrapper(sm(wrapped, b.wrapped))
}

object Test {
  def main(args:Array[String]) = {
    implicit val smInt:(Int, Int) => Int = {_+_}
    implicit val smString: (String, String) => String = {_+_}
    val a = Wrapper(2)
    val b = Wrapper(5)
    println(a+b==Wrapper(7))
    val c = Wrapper("Hello ")
    val d = Wrapper("World!")
    println(c+d==Wrapper("Hello World!"))
  }
}

A: This is an answer to address the underlying question that got clarified in the comments: What we want is to have a 'secure context' where we can operate on any arbitrary type. Results of such operations should be captured in this secure context. Furthermore, we would like to apply operations on instances of the same type that are captured in such context and provide means to capture "free" values into that context.
I would argue that a Monadic context would address all these requirements. without the need to "implement the methods of the wrapped type".
Monads provide a context where computations can take place and such context is controlled by the monad implementation. Values in Monads are like the "Hotel California": can always check in, but they can never leave.
To illustrate the point, let's call this Monad "Context": Context[T]
Let's explore the examples provided in the question:
// Add two values in the context
val a: Context[Int] = Context(2)
val b: Context[Int] = Context(3)

val c = for {
           x <- a
           y <- b
        } yield x+y
// c:Context[Int] = Context(5)

//add a free value to a value in the context
val a: Context[Int] = Context(2)
val c = a.map(value => value + 3)
//c:Context[Int] = Context(5)

// We can transform types within the context and apply arbitrary functions
val transaction = for {
    user <- Context(user)
    amount <- Context(amount)
    account = user.account
    wallet = user.wallet
    funds <- account.withdraw(amount)
} yield wallet.deposit(funds)

The custom monad that needs to be developed will contain the  any computational strategy that is required to achieve our business or technical goals as well as methods to safely extract values from that custom context. See this answer for a concrete yet simple example.

A: It is possible, with some limitations.
It is actually possible to get the syntax you want. This solution will automatically 'implement' any method that exists in the wrapped class.
import scala.language.dynamics
import scala.reflect.ClassTag
import scala.collection.JavaConverters._

object Temp {

    def main(args: Array[String]): Unit = {
        val test = new Wrapper("foo")
        println(test + "bar")
    }
}

class Wrapper[T](value: T) extends Dynamic {

    private val valueClass = value.getClass

    def applyDynamic(id: String)(parameters: Any*) = {
        val objectParameters = parameters map (x => x.asInstanceOf[Object])
        val parameterClasses = objectParameters map (_.getClass)
        val method = valueClass.getMethod(id, parameterClasses:_*)
        val res = method.invoke(value, objectParameters:_*)
        new Wrapper(res)
    }

    override def toString = value.toString
}

This works through dynamic classes. When a method is not found in a dynamic class it will call applyDynamic with the method name and parameters. It could also be made to work with fields. This is just a proof of concept and has several limitations that may or may not be able to be fixed.


text:
Q: Trigger a Bootstrap .collapse('toggle') via an event I have a form that spans several out-of-the-box Bootstrap Collapse panes. They toggle correctly on a mouse click - now I'd like to implement a way to open a closed pane via whatever event fires when tabbing from the last input of the currently open pane.
IOW, as I step thru the input fields of the open pane I can tab from one input to the next - when I tab from the last input the focus goes to the subsequent header region of the next pane. I'd like the act of tabbing to that header region to fire .collapse('toggle');
I've tried a few variations on:
    $('#collapseAcct').focus(function () {
        $('#collapseAcct').collapse('toggle');
    });

and have also tried climbing the family tree with :parent but haven't found the key. Structure of my panes:I'm using 3 panes where the unique identifier is a nested one layer deep in the div structure - pretty much the same as BS's documentation. E.G. struc of 1 pane:

            Account

content
[and everything wraps out accordingly]

A: I had a situation where needed to make bootstrap panels behave like a form so open on focus or mouseover.
I just triggered the click event.
code:
$('.panel-title a').bind('mouseover focus',function(){
$(this).trigger('click');
});

A: What about doing it the other way around, and opening the next accordion when the last input in the current accordion blurs :
$('.accordion-inner input:last').on('blur', function() {
    $('#collapseAcct').collapse('show');
});

And you did of course give all the elements unique ID's, and not all collapseAcct

A: This should get you started: http://jsfiddle.net/Xbg4n/45/
The example doesn't use .collapse, but just .slideUp and .slideDown... should be easy enough to swap out with collapse but works for example purposes. What you are really getting out of this is the targeting, which I think is what you were mainly asking about. I also added a bit into this to cycle back to the first container, but stopped there. You should add better control over focus (avoid focus on anchor tags and force focus when cycling back to first container).
You didn't provide full HTML sample code, so I filled in the blanks:
<form id="myform">

 Account

                <input type="text" name="input1" />
                <input type="text" name="input11" />
                <input type="text" name="input12" />

 Settings

                <input type="text" name="input3" />
                <input type="text" name="input31" />
                <input type="text" name="input32" />

 Prefs

                <input type="text" name="input2" />
                <input type="text" name="input21" />
                <input type="text" name="input22" />

the JS:
$('.accordion-group').each(function(){
var topcontainer = $(this);
topcontainer.find('input:last').each(function(){
    $(this).blur(function(){
        //swap slideup and slidedown for 'collapse' as appropriate
        var nextag = topcontainer.next('.accordion-group');
        var lastag = $('.accordion-group').last();
        if(topcontainer.is(lastag)){
            var nextag = $('.accordion-group').first();
        }
        var showag = nextag.find('.collapse');
        var hideag = topcontainer.find('.collapse');
        showag.slideDown();
        hideag.slideUp();
    });
});

});
The CSS:
#collapseAcct2 {
    display:none;
}
#collapseAcct3 {
    display:none;
}

A: You can use bootstrap collapse events
show.bs.collapse

This event fires immediately when the show instance method is called.
shown.bs.collapse

This event is fired when a collapse element has been made visible to the user (will wait for CSS transitions to complete).
hide.bs.collapse

This event is fired immediately when the hide method has been called.
hidden.bs.collapse

This event is fired when a collapse element has been hidden from the user (will wait for CSS transitions to complete).
Copy
example:
$('#myCollapsible').on('hidden.bs.collapse', function () {
  // do something…
})


text:
Q: What is the proper date format for the document? I'm having trouble sorting my records with a timestamp field which contains data in the following form: "Thursday, September 13, 2018 10:01 AM".
I suspect there's a proper date & time format I should use so the MongoDB will treat it properly.
I'm generating the data like this: let timeStamp = moment().format('LLLL');


text:
Q: How to convert JSON key-value pairs to records in pyspark? I have a series of JSONs that look something like this:
{
    id: '121',
    values: {
        "Value A": 1,
        "Value B": 2,
        "Value C": 3
    }
}

The number of key-value pairs can vary.
I want to create a pyspark program that would take this and break this down into a DataFrame that looks something like this:
id  | key     | value
____ _________ ______
121 | Value A | 1
121 | Value B | 2
121 | Value C | 3

I was able to get the id and value columns using this:
df = sess.read.json('Projects/spark/data/*')
df.select('id',explode(array(expr('values.*'))).name('vals')).dropna().show()

But I haven't been able to find a method to extract the keys. Does anyone know how to do this?

A: I read the json which gives MapType as dtype for values. Then i simply extract keys using map_keys and values using map_values and then just explode the arrays.
 from pyspark.sql.functions import arrays_zip, col, explode, map_keys, map_values

json1={
          'id': '121',
          'values': {
              "Value A": 1,
              "Value B": 2,
              "Value C": 3
          }
      }
df2=spark.createDataFrame([(json1)])

df2.select(col('id'),col('values'), map_keys("values").alias("keys"),
           map_values("values").alias('inner_values'),
           ).withColumn("tmp",arrays_zip("keys","inner_values"))\
           .withColumn("tmp",explode("tmp")).select(col("id"),\
 col("tmp.keys"),col("tmp.inner_values")).show()

+---+-------+------------+
| id|   keys|inner_values|
+---+-------+------------+
|121|Value C|           3|
|121|Value A|           1|
|121|Value B|           2|
+---+-------+------------+

A: A more simpler solution would be to use  explode() and select() together
Create the DF here
a_json={
          'id': '121',
          'values': {
              "Value A": 1,
              "Value B": 2,
              "Value C": 3
          }
      }
df = spark.createDataFrame([(a_json)])
df.show(truncate=False)

Output
+---+------------------------------------------+
|id |values                                    |
+---+------------------------------------------+
|121|[Value C -> 3, Value A -> 1, Value B -> 2]|
+---+------------------------------------------+

logic Here : Select() with explode() together
df = df.select("id", "values", F.explode("values").alias("x", "y"))
df.show(truncate=False)
+---+------------------------------------------+-------+---+
|id |values                                    |x      |y  |
+---+------------------------------------------+-------+---+
|121|[Value C -> 3, Value A -> 1, Value B -> 2]|Value C|3  |
|121|[Value C -> 3, Value A -> 1, Value B -> 2]|Value A|1  |
|121|[Value C -> 3, Value A -> 1, Value B -> 2]|Value B|2  |
+---+------------------------------------------+-------+---+


text:
Q: Symfony embedded form has multiple buttons I have 2 entities and I've created 2 separate form types for them. Each form type has a few fields and a submit button.
One of the entity is just a basic table (address) and the form type for this is used on a page independently and works as expected showing all its field and the submit button.
The other entity has a relation to the address table. The form type for this embeds the address form type along with a few of its own field and a submit button. The problem is this form type when displayed in the view shows 2 buttons which is not desired. And I would assume that if I embedded multiple form types it would show a button for each one of them too.
Is it possible to hide the button for the embedded form type so only the button in the current form type is shown?

A: A good way to do this is to remove the submit buttons from the form type entirely and add the submit buttons through the twig files, forms are meant to be reused most of the time, and in your case you are reusing them, it would't be fit to put them in the controller as you would be mixing presentation with controller logic, so the best place to put the submit button is in the twig.
Best Practice
{{ form_start(form) }}
    {{ form_widget(form) }}

    <input type="submit" value="Create"
           class="btn btn-default pull-right" />
{{ form_end(form) }}

A: sure you can.  Just use..
$form->remove('buttonName');

in your controller.

or, if you prefer to handle it in the formtype
public function buildForm(FormBuilderInterface $builder, array $options)
{
    // ...
    if ($options['use_second_button']) {
        $builder->add('submit2', 'submit');
    }
    // ...
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'use_second_button' => true
    ));
}

and in the controller, pass in a false to turn it off
$form = $this-createForm(new someType(), $entity, ['use_second_button' => false]);

heres a good resource.


text:
Q: Install android apps on pepper´s tablet in Naoqi 2.5 I want to install an android app on Pepper with NaoQi 2.5. To achivie this is tried to use AlTabletService´s hidden method "_installApk". I built an APK in android studios and deployed it in pepper´s head, the APK file does exist in peppers head because when i ssh into pepper and use the "ls" command the file is listed. I then tried to install the apk:
qicli call ALTabletService._installApk /home/nao/.local/share/PackageManager/apps/helloWorld/src/android/app-debug.apk

When i open the ADB debugger in pepper I can see the error message that the command gives:
I/ALTabletService/TabletService( 1175): Install Apk : /home/nao/.local/share/PackageManager/apps/helloWorld/src/android/app-debug.apk
I/ALTabletService/APKHelper( 1175): Installing package /home/nao/.local/share/PackageManager/apps/helloWorld/src/android/app-debug.apk UMA: false
E/APKHelper( 1175): Unable to download /home/nao/.local/share/PackageManager/apps/helloWorld/src/android/app-debug.apk
E/APKHelper( 1175): java.net.MalformedURLException: Protocol not found: /home/nao/.local/share/PackageManager/apps/helloWorld/src/android/app-debug.apk
E/APKHelper( 1175):     at java.net.URL.<init>(URL.java:176)
E/APKHelper( 1175):     at java.net.URL.<init>(URL.java:125)
E/APKHelper( 1175):     at jp.softbank.tabletbrowser.helper.APKHelper.downloadUrl(APKHelper.java:239)
E/APKHelper( 1175):     at jp.softbank.tabletbrowser.helper.APKHelper.installApk(APKHelper.java:57)
E/APKHelper( 1175):     at jp.softbank.tabletbrowser.service.TabletService._installApk(TabletService.java:396)

It appears that there is a problem with the path to the file. However it should be right, when I press Tab to autocompleat the path to the file it does so successfully.

A: ALTabletService is running on the tablet, not on Pepper's head, so it cannot access the unix filesystem on Pepper's head; it can, however, access any file exposed on Pepper's internal webserver (the way it does for webpages shown on the tablet) - so you need to do something like:
1) copy the apk to /home/nao/.local/share/PackageManager/apps/helloWorld/html/app-debug.apk
2) qicli call ALTabletService._installApk http://198.18.0.1/apps/helloworld/app-debug.apk

A: I also wanted to install android application on the pepper tablet. First of all, it is worth being mentioned that aldebaran and softbank community is extremely poor as far as I know. Besides, their documentation is also outdated. However, you need to jailbreak the tablet and root it in order to be able to connect android studio adb in to the robot tablet.
More details are available here: pepper-tablet-jailbreak


text:
Q: Shimmer effect with DYNAMIC background position? I have found that solution on this page. However, the background-position prop is... hardcoded (static). It will fail on different screen sizes (its too narrow for 4K screens - will start over in a half, and it's too wide for small screens - it will animate too quickly).
Is there a way to somehow make it dynamic, so it will work properly for every screen size? And if you ask, 100% do not work unfortunately.

@keyframes shimmerBackground {
  0% {
    background-position: -1000px 0
  }
  100% {
    background-position: 1000px 0
  }
}

.shimmer {
  background-image: -moz-linear-gradient(160deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0) 25%, rgba(255, 255, 255, 0.85) 60%, rgba(255, 255, 255, 0) 100%);
  background-image: -webkit-gradient(linear, left top, right top, color-stop(0%, rgba(255, 255, 255, 0)), color-stop(25%, rgba(255, 255, 255, 0)), color-stop(60%, rgba(255, 255, 255, 0.85)), color-stop(100%, rgba(255, 255, 255, 0)));
  background-image: -webkit-linear-gradient(160deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0) 25%, rgba(255, 255, 255, 0.85) 60%, rgba(255, 255, 255, 0) 100%);
  background-image: -o-linear-gradient(160deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0) 25%, rgba(255, 255, 255, 0.85) 60%, rgba(255, 255, 255, 0) 100%);
  background-image: -ms-linear-gradient(160deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0) 25%, rgba(255, 255, 255, 0.85) 60%, rgba(255, 255, 255, 0) 100%);
  background-image: linear-gradient(160deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0) 25%, rgba(255, 255, 255, 0.85) 60%, rgba(255, 255, 255, 0) 100%);
  background-repeat: repeat-y;
  animation: shimmerBackground 1s linear infinite;
  width: 100%;
  height: 100px;
  background-color: blue;
}
<div class='shimmer' />

A: You could try the vw (viewport width) / vh (viewport height) / vmin (viewport shorter edge) / vmax (viewport longer edge) units.
@keyframes shimmerBackground {
  0% {
    background-position: -100vw 0;
  }
  100% {
    background-position: 100vw 0;
  }
}

A: As I understand
when changing screen size shimer div height is not changing according
here height is fixed height: 100px;
It can be dynamic like  height:20%  or something you like
If you want to change animation speed
animation: shimmerBackground 1s linear infinite;

You can change 1s to 3s or something you like


text:
Q: How does zoneinfo get updated if at all? I have been installing several systems lately have noticed a difference of opinion on how to set time-zones.
Arch Linux Beginners' Guide says to use a symlink and the Gentoo HOW TO Guide says to copy from the shared folder
While this preference might be better for meta I am wondering if these time-zone files get updated.  If they were updated would the new replace the old or would my zone move from America/Dawson_Creek to America/Dawson_Creek.old?
I am wondering as my little pocket time-zone is an oddity and I constantly worry that since Microsoft refuses to acknowledge it we will be absorbed by the Arizona time zone.

A: A couple of things:

*

*Microsoft has no control over the TZDB used by Linux.  The time zones you're using are from the IANA TZDB, which is managed by a community.  Microsoft time zones are very different.  You can find more details in the timezone tag wiki on StackOverlow.

*You don't have any danger of America/Dawson_Creek being deprecated.  That would go against the policies and principles of this database.  If for some reason it was determined that it was no longer needed, then this zone would be converted into a link to the new one to maintain backwards compatibility.  If this were to happen, it is highly unlikely that you'd be merged with America/Phoenix, because zones in this database don't typically span multiple countries.

*In general, the tzdata package is available on most distributions, and gets updated in the same way that other packages get updated.  The changes originate with IANA, and then get packaged up by the tzdata maintainers for linux, and by many others for various systems.  You can find tzdata updates for ArchLinux here, for Ubuntu here, as an RPM package here, and several others.  On Gentoo, it's in the sys-libs/timezone-data package.

*I am not 100% familiar with the differences between those two distributions of Linux with regards to how to set the time zone, but it's certainly possible that different distros could have different mechanisms for that.  Perhaps someone else can answer this part of the question more specifically.


text:
Q: Mid-2007 MacBook (MacBook2,1) - Software Restore disks I picked up an old Mid-2007 MacBook a few months back, and I have been playing around with it. But, the one thing that I have not found are the original software restore disks, in iso or physical media. I been looking online, and in forums.
I currently have 1.5 GB of RAM on installed.
Any help finding the software restore disks would be appreciated.
**UPDATE
I know that it has been a few months but here is a quick update and a question.
So I did a lot of poking around and I found out how to install OS X Mavericks on this computer. LINK
But, I am trying to install Windows Vista on the computer and every time that I boot from the install it says CD-DVD Driver Missing. So I tried putting the drivers on the installation drive but it did nothing. Any Help Appreciated.

A: The last version of OS X compatible with your Mac is OS X Lion 10.7.5. I assume that you have not purchased Lion from the Apple App Store and therefore can not download a copy. The path to store the Mac from scratch would be as follows.

*

*Install OS X Snow Leopard 10.6. AFAIK, Apple no longer sells this DVD. You can try to purchase a used copy. A free ISO can be downloaded from the internet. You can then either burn to a DVD or create a bootable USB flash drive installer.

*Upgrade to OS X 10.6.8. This is a free download from Apple. I should point out you probably will not be able to download this update from a OS X 10.6 install. In other words, the version of Safari is to old. You should attempt to download to a flash drive in advance or use another machine to download to a flash drive.

*Upgrade to OS X 10.7. This is available from Apple for 20 USD. This purchase is for a download of the software to upgrade from Snow Leopard.

*Upgrade to OS X 10.7.5. This is a free download from Apple.
Because of the age of the Mac, you should consider abandoning OS X altogether in favor of version of Linux. What would be available for your Mac depends on the amount of RAM installed.
Debian with desktop has a 512 MB minimum and recommends 2 GB or RAM.
Xubuntu with desktop has a has a 512 MB minimum and recommends 2 GB or RAM.
The current Debian ISO can be downloaded from here.
Ubuntu is a popular Linux. However installing requires 4 GB of RAM. Xubuntu is basically the same, but with a Desktop interface that requires less RAM.
Note: Due to the age of your Mac, Linux probably should be installed to BIOS boot. I have installed both Debian and Xubuntu on a 2007 iMac with 4 GB of RAM.
I assume you have the memory split as 1 GB + 512 MB. The maximum memory is 3 GB. You could upgrade by replacing the 512 MB with either 1 GB or 2 GB. OWC seems to still sell memory for your model.
You probably could install 32 bit Windows 10. The 64 bit version would require a memory upgrade to at least 2 GB. The drivers can be downloaded from this Apple website. I was able to install 64 bit Windows 10 on a 2007 iMac using the 32 bit Windows 7 drivers. You can download and try Windows 10 without a purchase, but to keep using requires purchasing a license. IMO, Windows probably would run to slow to justify the purchase of a license.

If you attempt to install a current release of either Linux or Windows 10, you should expect to run into unforeseen problems which may be solved by posting a new question.

A: EveryMac.com says:

Pre-Installed MacOS:  X 10.4.9 (8P4112)   Maximum MacOS:  X 10.7.5*
*This system can run the last version of OS X 10.7 "Lion" if upgraded to at least 2 GB of RAM.

All versions of MacOS from 10.4 to 10.7 were sold. They are not available for free download. You may be able to buy the disks from someone.
If you're already running Lion, then you can at least create OS X Recovery on an external drive using the OS X Recovery Disk Assistant.


text:
Q: Lazyload inside bootstrap panel group I am using a collapsible bootstrap panel group and one extra div I added with a class name jscroll-inner just after the panel-group start. Jscroll-inner is reuired to load more panels.
Now the problem is, collapse is not working properly. Means if I click one panel to open , then the other panel should get close. But here all panels are getting open.
Please let me know if know if anybody can help on this.
Here is the code

            Collapsible Group 1

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
          sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
          minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
          commodo consequat.

            Collapsible Group 2

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
          sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
          minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
          commodo consequat.

            Collapsible Group 3

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
          sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
          minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
          commodo consequat.

A:

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

            Collapsible Group 1

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
          sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
          minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
          commodo consequat.

            Collapsible Group 2

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
          sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
          minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
          commodo consequat.

            Collapsible Group 3

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
          sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
          minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
          commodo consequat.


text:
Q: How can 'const' have an influence on the type of the variable? I've had this little problem where I wanted to check all checkboxes inside a specific area with the help of some javascript and a few jquery functions. I retrieved the value of the "select-all" checkbox and wanted to check/uncheck all other checkboxes under it.
Case 1: status = (elt.checked == true);
This gives me a string with the value "true" or "false" which, when put into a conditional statement, will always be seen as true since it's not an empty string.
Case 2: const status = (elt.checked == true);
This gives me a boolean with the value true or false which can actually be used in the conditional statement.
$(document).on('change', '.select-all input', function(e) {
    elt = e.target;
    status = (elt.checked == true);
    $(elt).closest('.files-list').find('input').each(function(i, e) {
        if (status)
            $(e).attr('checked', true);
        else
            $(e).removeAttr('checked');
    });
});

Why does this const modifier have any influence on the data type of the variable?


text:
Q: Singleton cluster actor is not starting up The following cluster singleton is not starting up.
commander = system.actorOf(
  ClusterSingletonManager.props(Commander.props(this),
    terminationMessage = PoisonPill.getInstance,
    settings = ClusterSingletonManagerSettings.create(system).withRole("commander")
  ), name = "Commander")

No error messages are thrown.
Logs are:

[INFO] [08/03/2016 11:43:58.656] [ScalaTest-run-running-ClusterSuite] [akka.remote.Remoting] Starting remoting
  [INFO] [08/03/2016 11:43:59.007] [ScalaTest-run-running-ClusterSuite] [akka.remote.Remoting] Remoting started; listening on addresses :[akka.tcp://galaxyFarFarAway@127.0.0.1:59592]
  [INFO] [08/03/2016 11:43:59.035] [ScalaTest-run-running-ClusterSuite] [akka.cluster.Cluster(akka://galaxyFarFarAway)] Cluster Node [akka.tcp://galaxyFarFarAway@127.0.0.1:59592] - Starting up...
  [INFO] [08/03/2016 11:43:59.218] [ScalaTest-run-running-ClusterSuite] [akka.cluster.Cluster(akka://galaxyFarFarAway)] Cluster Node [akka.tcp://galaxyFarFarAway@127.0.0.1:59592] - Registered cluster JMX MBean [akka:type=Cluster]
  [INFO] [08/03/2016 11:43:59.218] [ScalaTest-run-running-ClusterSuite] [akka.cluster.Cluster(akka://galaxyFarFarAway)] Cluster Node [akka.tcp://galaxyFarFarAway@127.0.0.1:59592] - Started up successfully
  [INFO] [08/03/2016 11:43:59.247] [galaxyFarFarAway-akka.actor.default-dispatcher-2] [akka.cluster.Cluster(akka://galaxyFarFarAway)] Cluster Node [akka.tcp://galaxyFarFarAway@127.0.0.1:59592] - Metrics will be retreived from MBeans, and may be incorrect on some platforms. To increase metric accuracy add the 'sigar.jar' to the classpath and the appropriate platform-specific native libary to 'java.library.path'. Reason: java.lang.ClassNotFoundException: org.hyperic.sigar.Sigar
  [INFO] [08/03/2016 11:43:59.257] [galaxyFarFarAway-akka.actor.default-dispatcher-2] [akka.cluster.Cluster(akka://galaxyFarFarAway)] Cluster Node [akka.tcp://galaxyFarFarAway@127.0.0.1:59592] - Metrics collection has started successfully
  [INFO] [08/03/2016 11:43:59.268] [galaxyFarFarAway-akka.actor.default-dispatcher-3] [akka.cluster.Cluster(akka://galaxyFarFarAway)] Cluster Node [akka.tcp://galaxyFarFarAway@127.0.0.1:59592] - No seed-nodes configured, manual cluster join required
  Disconnected from the target VM, address: '127.0.0.1:59574', transport: 'socket'

The configuration is:
akka {
 actor {
  provider = "akka.cluster.ClusterActorRefProvider"
  default-dispatcher {
  throughput = 10
  }
}
 cluster {
  roles = [commander]
}

 remote {
  log-remote-lifecycle-events = off
  netty.tcp {
     hostname = "127.0.0.1"
     port = 0
    }
 }
 akka.extensions=["akka.cluster.metrics.ClusterMetricsExtension"]
}

When I debug the code of Commander class, the constructor is not even called anywhere. When I omit the ClusterSingletonManager and just create it with Props it does work however, the Commander actor is going to be created.
I sense incorrect configuration behind this issue. Do you guys have any remarks about this?

A: You've sensed quite right: you haven't specified the seed node configuration for the Akka clustering. You can see this in the last line of the log:

[akka.tcp://galaxyFarFarAway@127.0.0.1:59592] - No seed-nodes configured, manual cluster join required Disconnected from the target VM, address: '127.0.0.1:59574', transport: 'socket'

Because you haven't specified any seed nodes in the configuration file, Akka will wait for you to specify the seed nodes programmatically. You can specify the seed nodes in the config like this:
akka.cluster.seed-nodes = [
  "akka.tcp://yourClusterSystem@127.0.0.1:2551",
  "akka.tcp://yourClusterSystem@127.0.0.1:2552"
]

Alternatively, you can call the joinSeedNodes method to join the cluster programmatically. In both cases, you have to specify at least one seed node that is available. The actor system itself can also act as a seed node.
Once the seed nodes have been specified and the actor system has joined the cluster, Akka features depending on clustering (cluster singletons, sharding etc.) will boot up. This is why you can launch an ordinary actor, but not the singleton.
For more information on setting up seed nodes see Akka cluster documentation.


text:
Q: why does scanf in while loop spam console? The goal behind the following is asking the user for input until an exit string is entered but the preferred execution is not met because this function spams the printf strings and does not take user input more than one time
void test()
{
    int res=0;
    while (res >=0)
    {
        char buffer[1024];
        printf("Enter input: ");
        res = scanf("%[^\n]", buffer);
        printf("\n[%d]you entered: %s\n",res , buffer);
        if (strcmp(buffer, "exit") == 0)
            return ;
    }
}

int main()
{
    test();
    return 0;
}

How to use scanf so that it waits until a user inputs something?


text:
Q: What's the difference between "xxx-compliant" and "xxx-compatible"? I always see these phrases, what's the meaning and difference?

A: Compliant means it is working like it should as defined by some spec or standard or rules.
Compatible means it works, but not necessary setup as defined by the rules.

A: Compliant with a standard or a spec.
Compatible with a piece of hardware or software.

A: For example, we had an issue with google ads in our company (has alot of in app ads) that weren't compliant(don't match all their rules) with their rules,
but were compatible(were working fine but not a must match their rules) and displaying well


text:
Q: Getting TypeError: Network request failed while POSTing to my node server from Physical Device What I Want:

*

*POST some credentials to my node server on Signup and save the user in MongoDB

What's Wrong:

*

*TypeError: Network request failed on POST Request from React Native

What I have Done:

*

*Change Local Host to my machine's IP

*Add android:usesCleartextTraffic="true" in Android Manifest

*Used IP generated by ngork

*Checked my server code using POSTMAN, its working fine!

React Native CODE:
POST Request:
fetch('http://MY_MACHINE_IPv4:3001/signup', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    fullName: fullName,
    email: email,
    phone: phone,
    password: pass,
  }),
})
  .then(response => response.json())
  .then(data => console.log(data));

Node's Code:
router.post("/signup", async (req, res) => {
    const { fullName, email, phone, password } = req.body
  console.log("The Email in request is ", email)
  console.log("The Password in request is ", password)
  try {
    const user = new User({ fullName, email, phone, password })
    console.log("USER BEING SAVED")
    await user.save()
    const token = jwt.sign({ userId: user._id }, jwtKey)
    res.send({ token: token })
  } catch (err) {
    res.status(422).send(err.message)
  }
})

Error:
WARN  Possible Unhandled Promise Rejection (id: 0):
TypeError: Network request failed
TypeError: Network request failed
at anonymous (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.healthapp&modulesOnly=false&runModule=true:25389:33)
at apply (native)
at anonymous (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.healthapp&modulesOnly=false&runModule=true:29526:26)
at _callTimer (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.healthapp&modulesOnly=false&runModule=true:29446:17)
at callTimers (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.healthapp&modulesOnly=false&runModule=true:29647:19)
at apply (native)
at __callFunction (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.healthapp&modulesOnly=false&runModule=true:6319:36)
at anonymous (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.healthapp&modulesOnly=false&runModule=true:6043:31)
at __guard (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.healthapp&modulesOnly=false&runModule=true:6270:15)
at callFunctionReturnFlushedQueue (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.healthapp&modulesOnly=false&runModule=true:6042:21)

A: If you are using an android emulator,Android emulator always sent charset: utf-8 on the header. so you need to changed the nginx setting to allow that additional header


text:
Q: How to count number of times a date has been used? How can I count how many times a date is in a table column using php and mysql?
I am trying to figure out a way to limit the amount of dates can be used for rows
for example:
1   1   0000-00-00  2   yes     2013-10-06 20:07:17 2013-10-06 20:07:17
2   1   0000-00-00  4   yes 1   2013-10-06 20:19:31 2013-10-06 20:19:31
3   1   2013-10-15  2   yes 1   2013-10-06 20:22:14 2013-10-06 20:22:14
4   1   2013-10-30  3   yes 1   2013-10-06 21:07:28 2013-10-06 21:07:28

I want to return an error if 2013-10-30 has been used 5 times.
I am using Laravel 4 and saving the data using a model
    if (<<<<code goes here???>>>>>){
        return Redirect::to('')->withErrors($full)->withInput();
    }

    $schedule->userID = $user->id;
    $schedule->date = $dateFormat;
    $schedule->block = $input['timeslot'];
    $schedule->status = "1";

    $schedule->save();

A: The sql statement you want it is
SELECT COUNT (id) FROM table WHERE DATE(date_field) = :date

don't use rowCount that should be used to count row affected (like in a delete or update)

A: You could also do something like this:
Schedule::where('timeslot', '=', $date)->count() in addition, if that piece of code is used here and there you could create it as a query scope so you can call it in fashion like Schedule::countForTimeslot($date) anywhere or as a part of more complex query on top of the model.


text:
Q: Can an optional property value be null? I thought optional properties in TypeScript covered both undefined and null cases.  Am I wrong?
If I have the following interface
export interface student {
   id: string;
   major?: string;
}

and API returns
{
   id: '1234',
   major: null
}

will this cause an error?

A: That will be incorrect, type-wise.
An optional property means that the property may either be of the type on the right (here, string), or it may be undefined.
interface student {
   id: string;
   major?: string;
}

is very similar to
interface student {
   id: string;
   major: string | undefined;
}

null is not included.
https://www.typescriptlang.org/play?#code/C4TwDgpgBAzsCuATCA7YUC8UDeAoKBAlogFyzABOhKA5gNz4EC2AhgFYD2FA-GXFbQYBfXLgDGHFHFh8EyNJhyMoxMgHIAjACYAzABY1AGmWtOFMingAbK7iFA
(They're not exactly the same though, thanks Patrick Roberts - a type with optional property can be applied to an object which lacks the property entirely, but a required property with | undefined can only be applied to an object which has that property, and the value of the property may be undefined)


text:
Q: Importing data from JSON using python Hi I am new to python and I am trying to import a Dataset from JSON file in the repository using Python
import json
with open ('dataforms.json','r') as f:
    data = json.load(f)
    for row in data:
        print (row[Flood])

this code is throwing the following error:
Traceback (most recent call last):
  File "C:\Users\Ayush\Desktop\js2.py", line 5, in <module>
    print (row[Flood])
NameError: name 'Flood' is not defined

A: I'm assuming Flood is a string? In which case you need to put quotes around it, or Python thinks it is a variable name.
print (row['Flood'])


text:
Q: Import Excel Spread Sheet into Access - Format Issue with [h]:mm:ss I need to import an Excel spread sheet into Microsoft Access. I have a column which is in the format [h]:mm:ss. When I import it with Access I have specified the column to be in Date/Time format but it displays incorrectly.
For example in Excel it would show 452:32:00 but in Access it would show 18/01/1900 20:32:00. I need to write a query in Access to display this in the same format it is shown in Excel.
I'd appreciate if someone could show me the SQL to do this. Thanks

A: Update 1: a new approach to storing durations--store everything in seconds, instead of three separate columns for hours, minutes and seconds. Access' double type allows us to store durations in the scale of geological ages.
Steps:

*

*Import spreadsheet into an Access table of durations--say, tblDurations.

*Perform arithmetic operations on the durations, e.g. add (the corresponding columns in) two rows together, multiple a row by 2, sum all the rows, etc.

*Format and display the output.

Below, I'll be using mostly Access's ANSI-92 SQL syntax which works through the DAO CurrentProject.Connection.Execute method. You'll have to use DAO for best results here instead of the Access GUI query editor(s). Let me know if you need any clarification on this.
Import Spreadsheet
Create Table
create table tblDurations (
  ID autoincrement primary key
, durSeconds double not null
)

Import Durations
I like to import data from a simple CSV file. I'll show you that approach here. Say you have a CSV file durations.csv that looks like this in Excel:
Duration
01:59:59
02:01:57
00:00:04

You can run the following to import it:
insert into tblDurations (durSeconds)
select
  hour(Duration) * 60 * 60
+ minute(Duration) * 60
+ second(Duration)
from [Text;FMT=CSVDelimited;HDR=Yes;DATABASE=C:\Users\YourName\Documents;].[durations.csv]

Note that in the last line above you substitute your own file path and name.
Arithmetic on Durations
Now you can switch to Access' GUI SQL editor. Let's say we want to multiply a certain duration by 2.5:
select
  2.5 as multiplier
, multiplier * durSeconds as s
from tblDurations
where ID = 1

Format and Display Output
The trick here is to convert a duration expressed in seconds into hours, minutes and seconds:
select
  int(sq.s / (60 * 60)) as Hours
, int((sq.s - Hours * 60 * 60) / 60) as Minutes
, sq.s - Hours * 60 * 60 - Minutes * 60 as Seconds
from (
  select
    2.5 as multiplier
  , multiplier * durSeconds as s
  from tblDurations
  where ID = 1
) as sq

Finally, you format the output hours, minutes and seconds as hh:mm:ss, which I leave as an exercise for the reader.


text:
Q: Jquery append() on another line? I thought this would be simple but this code outputs my spans on the same line.
$("
")
    .append($("", {
        class:"time",
        text: content.time }))
    .append($("", {
        class: "content",
        text: content.message
    }));

But since it append these elements without a newline, my spans end up needing manual spacing, which just isn't possible at my current scale.

nowLorem Ipsum ...

How can I force jQuery to manually append my spans on a new line? I've tried using .after to.
EDIT:
I guess I was a bit unclear, so far .append("\n") is what I'm looking for, if there are any better ways, I'm all ears but appending a
 tag is definitely not what I was looking for.

   now
   Lorem Ipsum ...

A: If you want the HTML element to be appeneded to a newline, you can insert a newline character, \n, using the .after() method before appending the second span. In doing so, there will be a space between the words (since inline span elements respect the whitespace in the markup).
Example Here
$("p").append($("", {
    class: "time",
    text: content.time
}).after('\n')).append($("", {
    class: "content",
    text: content.message
}));

A: This should work
$("
")
    .append($("", {
        class:"time",
        text: content.time }))
    .append("
")
    .append($("", {
        class: "content",
        text: content.message
    }));

A: Append line break separately, not by joining it to text, then it works:
$("
")
    .append($("", {
        class:"time",
        text: content.time }))
    .append($("
"))
    .append($("", {
        class: "content",
        text: content.message
    }))
    .append($("
"));

working fiddle

A:  is inline element. You can change it to block with CSS:
span {
    display: block;
}

or use after pseudoelement:
span::after {
    content: "\A";
    white-space: pre;
}

or use


text:
Q: Adding a view to Navigation bar My navigationBar contains default titleView and a shawdowImage as its content. During run time, I want to add a view to the navigationBar below the shadowImage and make the size adjustments accordingly. I do not see a direct way to do that.
I could also add the view to self.view, but I want this view to be part of the navigationBar as it must be maintained also on top of other viewControllers in the navigation stack. Else, I must insert the view between navigationBar and self.view, but it can't be maintained across other viewControllers.


text:
Q: Adding a list of libraries in cmake I have a list of libraries that I an trying to add to target_link_libraries(). Is it possible?
 set(list1 x.a y.a z.a)
 target_link_libraries(main ${list1})

Is it a right way to do it?

A: Yes, that's the usual way to do this.
To be more precise, usually the list is set by first using find_library to get the x.a location first, and then putting them in a list.


text:
Q: Entity with field Array of objects. How to correctly describe this Entity use Hibernate ogm? I am a tester. I 'm doing my first java automation project using Hibernate ogm. I 've been thinking about this problem several days, but I can 't find a solution.
This is my document in bd:
enter image description here
This is Entity:
enter image description here
I have difficulty describing the fields from the red frame. Without these fields there are no problems, my test works. As soon as I add fields from the red frame, my SessionFactory falls. I have no idea how to do it right. I will be glad of any help and advice.


text:
Q: String expansion in openCL I have a simple task of expanding the string FX according to the following rules:
X -> X+YF+
Y-> -FX-Y

In OpenCL, string manipulation is not supported but the use of an array of characters is. How would a kernel program that expands this string in parallel look like in openCL?
More details:
Consider the expansion of 'FX' in the python code below.
axiom = "FX"
def expand(s):
    switch = {
        "X": "X+YF+",
        "Y": "-FX-Y",
    }
    return switch.get(s, s)

def expand_once(string):
    return [expand(c) for c in string]

def expand_n(s, n):
    for i in range(n):
        s = ''.join(expand_once(s))
    return s

expanded = expand_n(axiom, 200)

The result expanded will be a result of expanding the axiom 'FX' 200 times. This is a rather slow process thus the need to do it on openCL for parallelization.
This process results in an array of strings which I will then use to draw a dragon curve.
below is an example of how I would come up with such a dragon curve: This part is not of much importance. The expansion on OpenCL is the crucial part.
 import turtles
    from PIL import Image
turtles.setposition(5000, 5000)
turtles.left(90)  # Go up to start.

for c in expanded:
    if c == "F":
        turtles.forward(10)
    elif c == "-":
        turtles.left(90)
    elif c == "+":
        turtles.right(90)

# Write out the image.
im = Image.fromarray(turtles.canvas)
im.save("dragon_curve.jpg")

A: Recursive algorithms like this don't especially lend themselves to GPU acceleration, especially as the data set changes its size on each iteration.
If you do really need to do this iteratively, the challenge is for each work-item to know where in the output string to place its result. One way to do this would be to assign work groups a specific substring of the input, and on every iteration, keep count of the total number of Xs and Ys in each workgroup-sized substring of the output. From this you can calculate how much that substring will expand in one iteration, and if you accumulate those values, you'll know the offset of the output of each substring expansion. Whether this is efficient is another question. :-)
However, your algorithm is actually fairly predictable: you can calculate precisely how large the final string will be given the initial string and number of iterations. The best way to generate this string with OpenCL would be to come up with a non-recursive function which analytically calculates the character at position N given M iterations, and then call that function once per work-item, with the (known!) final length of the string as the work size. I don't know if it's possible to come up with such a function, but it seems like it might be, and if it is possible, this is probably the most efficient way to do it on a GPU.
It seems like this might be possible: as far as I can tell, the result will be highly periodic:
FX
FX+YF+
FX+YF++-FX-YF+
FX+YF++-FX-YF++-FX+YF+--FX-YF+
FX+YF++-FX-YF++-FX+YF+--FX-YF++-FX+YF++-FX-YF+--FX+YF+--FX-YF+
^^^^^^ ^^^^^^^ ^^^^^^^ ^^^^^^^ ^^^^^^^ ^^^^^^^ ^^^^^^^ ^^^^^^^
  A*      B       A       B       A       B       A       B

As far as I can see, those A blocks are all identical, and so are the Bs. (apart from the first A which is effectively at position -1) You can therefore determine the characters at 14 positions out of every 16 completely deterministically. I strongly suspect it's possible to work out the pattern of +s and -s that connects them too. If you figure that out, the solution becomes pretty easy.
Note though that when you have that function, you probably don't even need to put the result in a giant string: you can just feed your drawing algorithm with that function directly.


text:
Q: Is it possible to upload a video while still letting the user interact with app? I'm using AWS's transferUtility.uploadData which uses the background transfer feature in iOS to upload videos
Basically when a user presses a button to start transferUtility.uploadData, a new screen is pushed on the navigationController. So while the video is uploading, they can interact with the new screen.
The problem is there a huge delay when the screen is pushed on the navigation, and I was wondering if there was a way to push a screen on the navigationController (like instagram after taking a video a new screen appears to customize or send to friends) instantly.
 transferUtility.uploadData(
        data,
        bucket: S3BucketName,
        key: videoName,
        contentType: "movie/mov",
        expression: expression,
        completionHandler: completionHandler).continueWith { (task) -> AnyObject! in
            if let error = task.error {
                print(error)
                print("Error: \(error.localizedDescription)")
            }

            if let _ = task.result {
                print("Upload Starting!----")

                // Do something with uploadTask.

                //Open new screen
                self.navigationController?.pushViewController(CameraDetailTableViewController(videoURL: AWS_URL + videoName), animated: false)

            }

            return nil;
    }

A: Use dispatch_async to upload y our video. That way the upload is on a different thread in the app and will run in the background, thus the user can work fine. In the completion handler of the upload you can then notify the user via popup that the upload succeeded.
Here is the code for dispatch async:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { // in half a second...
    //upload your video here
}

A: You need to either use Grand Central Dispatch or AWSExecutor.
See the documentation for AWSTask for full details on how to implement.
http://docs.aws.amazon.com/mobile/sdkforios/developerguide/awstask.html


text:
Q: SQL Server database connection using System DSN in C# I am a .NET developer using C#. I have configured DSN in my machine of remote SQL Server database. I have provided database name, user name and password while System DSN creation. I am trying to connect to that database in our Windows based application using DSN but doesn't want to provide user name and password because I have already defined in DSN but unable to connect.
Application throws an error

[Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user ''. The user is not associated with a trusted SQL Server connection.

When I provide DB user name and password along with DSN in connection string then it works but I don't want to give DB user name and password again.
My sample code:
 string connString = "Dsn=TMagic";

    OdbcConnection OdbcConn = new OdbcConnection(connString);

    //open connection
    if (OdbcConn.State != ConnectionState.Open)
    {
          OdbcConn.Open();
    }

    string sqlQuery = "select * from userinfo";
    DataSet dataSet = new System.Data.DataSet();
    OdbcDataAdapter dataAdapter =    new OdbcDataAdapter(sqlQuery, OdbcConn);
    dataAdapter.Fill(dataSet);
    dataAdapter.Dispose();
    dataAdapter = null;

Please let me how to solve this issue.
Thanks in advance.


text:
Q: Get the index of a particular string in a redis list? I have a list container the current players for a game, and I keep track of the current turn with another integer. When a player leaves, I remove them from the players list. However, there are cases where I need to also adjust the turn value (when a player leaves).
I've found that if the index of a particular player is LESS than the turn value, then I need to decrement the turn variable. For example
1) A B C(t=2) D E => B leaves
2) A C(t=1) D E

Since B's index was before turn, turn is decremented. Conversely
1) A B C(t=2) D E => D leaves
2) A B C(t=2) E

Here, we do not have to change the turn value, since the player that left is AFTER turn.
So my question is, how can I determine the index of a particular string in a list? (non-blocking). If this is not possible, is there maybe another solution?

A: There is no way to do it with non-blocking algorithm. You have to traverse a list with first item to the turn'th item.
Because, you cannot reach any item with its value in such a list, there is only way I can see for now.


text:
Q: how to put PostgreSQL project/scripts under Azure DevOps We Are planning on using PostgreSQL to replace SQL Server for our in house applications.
SQL Server has the option to create a database project under Visual studio and manage the changes under Azure DevOps.
I can't seem to find a way to do the same with PostgreSQL, there no project type and no clear path on how to host the project/files under Azure DevOps.

A: I think you would need to use JavaScript on Azure PostgreSQL
As a newbie, I apologize if my answer was not appropriate.
Indeed to create or move your PostgreSQL database to Azure, you need a PostgreSQL resource.
Develop a JavaScript application with PostgreSQL on Azure
To create, move, or use a PostgreSQL database to Azure, you need an Azure Database for PostgreSQL server resource. Learn how to create the resource and use your database.
Create an Azure Database for PostgreSQL resource
Create a resource with:
Azure CLI command = az postgres server create
Visual Studio Code
Azure portal
View and use your PostgreSQL server on Azure
While developing your PostgreSQL database with JavaScript, use one of the following tools:
Azure Cloud Shell - psql CLI is available
pgAdmin
Visual Studio Code extension
Use SDK packages to develop your PostgreSQL server on Azure
The Azure PostgreSQL uses npm packages already available, such as:
pg
Use pg SDK to connect to PostgreSQL on Azure
To connect and use your PostgreSQL on Azure with JavaScript, use the following procedure.
Make sure Node.js and npm are installed.
Create a Node.js project in a new folder:
mkdir DbDemo && \
    cd DbDemo && \
    npm init -y && \
    npm install pg && \
    touch index.js && \
    code .

The command:
Creates a project folder named DbDemo
Changes the Bash terminal into that folder
Initializes the project, which creates the package.json file
Installs the pg npm package - to use async/await
Creates the index.js script file
Opens the project in Visual Studio Code
Copy the following JavaScript code into index.js:
:::code language="JavaScript" source="~/../js-e2e/database/postgresql/index.js" :::
Replace the YOUR-ADMIN-USER, YOURRESOURCENAME, and YOUR-PASSWORD with your values in the script for your connection string.
Run the script to connect to the postgres server and see the base tables and users.
node index.js

View the results.
[
  { table_name: 'pg_statistic' },
  { table_name: 'pg_type' },
  { table_name: 'pg_authid' },
  { table_name: 'pg_user_mapping' },
  { table_name: 'pg_attribute' },
  { table_name: 'pg_proc' },
  { table_name: 'pg_class' },
  { table_name: 'pg_attrdef' },
  { table_name: 'pg_constraint' },
  { table_name: 'pg_inherits' },
  { table_name: 'pg_index' },
  { table_name: 'pg_operator' },
  { table_name: 'pg_opfamily' },
  { table_name: 'pg_opclass' },
  { table_name: 'pg_am' },
  { table_name: 'pg_amop' },
  { table_name: 'pg_amproc' },
  { table_name: 'pg_language' },
  { table_name: 'pg_largeobject_metadata' },
  { table_name: 'pg_aggregate' },
  { table_name: 'pg_rewrite' },
  { table_name: 'pg_largeobject' },
  { table_name: 'pg_trigger' },
  { table_name: 'pg_event_trigger' },
  { table_name: 'pg_description' },
  { table_name: 'pg_cast' },
  { table_name: 'pg_enum' },
  { table_name: 'pg_namespace' },
  { table_name: 'pg_conversion' },
  { table_name: 'pg_depend' },
  { table_name: 'pg_database' },
  { table_name: 'pg_db_role_setting' },
  { table_name: 'pg_tablespace' },
  { table_name: 'pg_pltemplate' },
  { table_name: 'pg_auth_members' },
  { table_name: 'pg_shdepend' },
  { table_name: 'pg_shdescription' },
  { table_name: 'pg_ts_config' },
  { table_name: 'pg_ts_config_map' },
  { table_name: 'pg_ts_dict' },
  { table_name: 'pg_ts_parser' },
  { table_name: 'pg_ts_template' },
  { table_name: 'pg_extension' },
  { table_name: 'pg_foreign_data_wrapper' },
  { table_name: 'pg_foreign_server' },
  { table_name: 'pg_foreign_table' },
  { table_name: 'pg_policy' },
  { table_name: 'pg_replication_origin' },
  { table_name: 'pg_default_acl' },
  { table_name: 'pg_init_privs' },
  { table_name: 'pg_seclabel' },
  { table_name: 'pg_shseclabel' },
  { table_name: 'pg_collation' },
  { table_name: 'pg_range' },
  { table_name: 'pg_transform' },
  { table_name: 'sql_features' },
  { table_name: 'sql_implementation_info' },
  { table_name: 'sql_languages' },
  { table_name: 'sql_packages' },
  { table_name: 'sql_parts' },
  { table_name: 'sql_sizing' },
  { table_name: 'sql_sizing_profiles' }
]
[ { usename: 'azure_superuser' }, { usename: 'YOUR-ADMIN-USER' } ]
done


text:
Q: Setting the JVM to use with Ant when using the command line I have to build a project using Ant from the command line. It is an EAR to be deployed on weblogic 8.1 and as such the classpath is set on the correct jrockit, shipped with the 8.1 server. However, the tool keeps using the jre7 (also installed on my machine), going as far as not even starting if i uninstall the jre7 and leading to problems such as "Cannot find class Object", and so on.
Before running ant, I run the %WEBLOGIC_HOME%/server/bin/setWLSenv.cmd file in the same console session. Both %WEBLOGIC_HOME% and %JAVA_HOME% are correctly set. The jre7, as far as I know, is not referenced in any environment variable nor in any of the build files. I am not permitted to modify the build.xml file, also I can't use Eclipse or any other GUI to build the project.
So, how can I persuade ant to use the correct JVM?


text:
Q: Deserializing json from client in json.net 3.5b2 in vb.net I have a test case of a problem I'm having, basically I create a json object on the server and provide it back to an AJAX called made on the client side. That works fine, however, when I try to send it back and deserialize it server side I get the following exception:

No parameterless constructor defined for type of 'System.String'.
System.MissingMethodException at
  System.Web.Script.Serialization.ObjectConverter.ConvertDictionaryToObject(IDictionary2
  dictionary, Type type,
  JavaScriptSerializer serializer,
  Boolean throwOnError, Object&
  convertedObject) at
  system.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object
  o, Type type, JavaScriptSerializer
  serializer, Boolean throwOnError,
  Object& convertedObject) at
  system.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object
  o, Type type, JavaScriptSerializer
  serializer, Boolean throwOnError,
  Object& convertedObject) at
  System.Web.Script.Serialization.ObjectConverter.ConvertObjectToType(Object
  o, Type type, JavaScriptSerializer
  serializer) at
  System.Web.Script.Services.WebServiceMethodData.StrongTypeParameters(IDictionary2
  rawParams) at
  System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object
  target, IDictionary2 parameters) at
  System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext
  context, WebServiceMethodData
  methodData, IDictionary2 rawParams)
  at
  System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext
  context, WebServiceMethodData
  methodData)

Default.aspx
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Untitled Page</title>

    <form id="form1" runat="server">

        <input id="Button1" type="button" value="Get Date" />

        date.now: <input type="text" id="now" value="" style="width:20em" />

        date.now processed: <input type="text" id="pnow" value="" style="width:30em">

        date.strnow: <input type="text" id="strnow" value=""  style="width:20em"/>
        <input id="Button2" type="button" value="Send Date" />

    </form>

Default.aspx.vb
Imports System.Web.Services
Imports Newtonsoft.Json

Partial Class _Default
    Inherits System.Web.UI.Page

    Private Class _date
        <JsonProperty()> Public now As New Date
        <JsonProperty()> Public strnow As String
        Public Sub New()
            now = Date.Today
            strnow = Date.Today.ToLongDateString
        End Sub
    End Class

    <WebMethod()> Public Shared Function getDate() As String
        Dim theDate As New _date
        Dim strJson As String

        strJson = JsonConvert.SerializeObject(theDate)

        Return strJson
    End Function

    <WebMethod()> Public Shared Function deserialize(ByVal json As String) As String
        Dim newDate As _date
        Try
            newDate = JsonConvert.DeserializeObject(json, GetType(_date))
            Return "{""done"":true}"
        Catch ex As Exception
            Throw ex
        End Try
    End Function
End Class

I'd greatly appreciate help on what I'm doing wrong here. Thanks in advance.

A: Had to change
Private Class _date

to
Public Class _date

and
<WebMethod()> Public Shared Function deserialize(ByVal json As String) As String

to
<WebMethod()> Public Shared Function deserialize(ByVal json As _date) As String


text:
Q: How to relate two arrays in PHP I have two arrays like A & B.

A=[1,2,3,4] , B=[10,20,30,40]

I want to execute a mysql update query in a way like this.

$abc1=mysql_query("update table set corr='1' WHERE id=10");
$abc1=mysql_query("update table set corr='2' WHERE id=20");
$abc1=mysql_query("update table set corr='3' WHERE id=30");
$abc1=mysql_query("update table set corr='4' WHERE id=40");

all these query execution in one go.

A: Just loop em and use the index for the second array
$as=[1,2,3,4] , $bs=[10,20,30,40];
foreach ($as as $key=>$val) {
    $abc1=mysql_query("update table set corr='".$val."' WHERE id=".$bs[$key]);
}

Note: You shouldn't use mysqluse mysqliinstead
Note: Always escape

A: Using array_combine(), you can create a new array, specify one array as the keys, the other as values in the new array. Then it's just a matter of looping the resulting array, and execute queries. Since you now have one array, use a foreach loop and use the keys (in this case, all the values from $a) and values (in this case, all the values from $b) as the values you're setting.
This assumes that the amount of entries in both array is always the same. If they are not of the same size, array_combine() will return false - you can use that as a check before performing the queries.
$a = [1, 2, 3, 4];
$b = [10, 20, 30, 40];
$result = array_combine($a, $b);

foreach ($result as $k=>$v) {
    mysql_query("UPDATE table SET corr='$k' WHERE id = '$v'");
}

That being said, this query is vulnerable to SQL injection, and you should upgrade to a newer API which supports parameterized queries with placeholders (mysqli_* or PDO). The mysql_* API was deprecated in PHP 5.6 and removed entirely in PHP7.

*

*Why shouldn't I use mysql_* functions in PHP?

*How can I prevent SQL injection in PHP?

*Manual for array_combine()

A: $a=[1,2,3,4];$b=[10,20,30,40];
$res=array_combine($a, $b );
foreach ($res as $key => $value) {
    $abc1=mysql_query("update table set corr='".$key."' WHERE id=".$value);
}


text:
Q: Using jQuery to find certain text, and if exists, then append element to certain element nearby I'm trying to get jQuery to detect a certain text such as "add-canvas-snow" within a article, and if it finds it, append <canvas class="add-canvas-snow" /> to the a.featured-image-link, only within that same article, not all of the articles listed.
I tried using the jQuery .closest('.featured-image-link') method, but it doesn't seem to work. There is no Chrome console error.
How do I get this to work?
Also is .closest() the best method of doing this, or should I be grabbing the article ID as using it as a variable. Or should I be using the .sibling('featured-image-link') method? Which is better from a performance stand-point?
HTML:

      example-1
      example-2

    content

    content

      example-3
      add-canvas-snow
      example-4

    content

    content

      example-5
      example-6

    content

    content

JQUERY:
$('#main-content #Blog1 article').each(function() {
  if ($('#main-content #Blog1 article .post-header .post-category-label:contains("add-canvas-snow")').length > 0) {
    $(this).closest('.featured-image-link').append('<canvas class="add-canvas-snow" />');
  }
});

FYI: articles that contain "add-canvas-snow" are dynamic, as well as the number of articles that will appear on a page.
EDIT: I also tried:
$('#main-content #Blog1 article').each(function() {
  if ($('#main-content #Blog1 article .post-header .post-category-label > span:contains("add-canvas-snow")').length > 0) {
    $(this).parent().siblings('.featured-image-link').append('<canvas class="add-canvas-snow" />');
  }
});

A: The $(this) in your each() function does not refer to the  that contains add-canvas-snow, but to the
. Therefore closest() and prev().siblings() won't work, instead you have to use find('.featured-image-link'). Note that I also replaced the selector #main-content #Blog1 article inside the each() function with $(this).find() because inside the each() function the current element is already the
 in which you want to search for add-canvas-snow.

$('#main-content #Blog1 article').each(function() {
  if ($(this).find('.post-header .post-category-label:contains("add-canvas-snow")').length > 0) {
    $(this).find('.featured-image-link').append('<canvas class="add-canvas-snow" />');
  }
});

          example-1
          example-2

        content

        content

          example-3
          add-canvas-snow
          example-4

        content

        content

          example-5
          example-6

        content

        content


text:
Q: Binding issue with smpp server using jsmpp I have a java application which uses jsmpp library to send SMSs to SMSC. Application connects successfully and sends SMSs. Connection issue occurs after a week or so up time, during this up time it sends thousands of SMSs. But suddenly after few days application starts facing connection issues, some time 'Negative bind response 0x00045' and some time waiting bind response. When I check from wireshark, Application constantly sends enquire line packets and receives responses for them with status 'OK'. This means that application is connected but still it is attempting for new connection. Below is code for connection management.
I call newSession method to get session for SMS sending..
 private SMPPSession newSession(BindParameter bindParam) {
        SMPPSession tmpSession = null;
        dbOperations = new DBOperations();
        Settings settings = dbOperations.getSettings();
        if (settings == null)
            logger.error("ERROR: No settings found to connect to SMSC!");
        else {
            try {
                tmpSession = new SMPPSession(remoteIpAddress, remotePort, bindParam);
                tmpSession.addSessionStateListener(new MySessionStateListener());
                tmpSession.setMessageReceiverListener(new DeliverReceiptListener());
                tmpSession.setEnquireLinkTimer(50000);
                tmpSession.setTransactionTimer(5000L);
                logger.info("New session established with " + remoteIpAddress + " on port " + remotePort + " as Transmitter");
            } catch (Exception er) {
                gateway=null;
                logger.error("Exception Occurred While making Connection with SMPP Server with IP: " + remoteIpAddress + " and port " + remotePort+" and Error is:"+er.getMessage());
            }

        }
        return tmpSession;
    }

public void reconnectAfter(final long timeInMillis) {
        final Settings settings = dbOperations.getSettings();
        if (settings == null) {
            logger.error("No settings found to connect to SMSC!");
            return;
        }
        new Thread() {
            @Override
            public void run() {
                logger.info("Schedule reconnect after " + timeInMillis + " milliseconds");
                try {
                    Thread.sleep(timeInMillis);
                } catch (InterruptedException e) {
                    logger.error(e.getMessage());
                }

                int attempt = 0;
                while (session == null || session.getSessionState().equals(SessionState.CLOSED)) {
                    try {
                        logger.info("Reconnecting attempt #" + (++attempt) + "...");
                        session = newSession(bindParam);
                    } catch (Exception e) {
                        logger.error("Failed opening Transmitter connection and bind to " + remoteIpAddress + ":" + remotePort + " ");
                        logger.error(e.getMessage());
                        // wait for a second
                        try {
                            Thread.sleep(reconnectInterval);
                        } catch (InterruptedException ee) {
                            logger.error(e.getMessage());
                        }
                    }
                }
            }
        }.start();
    }
    private class MySessionStateListener implements SessionStateListener {

        public void onStateChange(SessionState newState, SessionState oldState, Object o) {
            if (newState.equals(SessionState.OPEN)) {
                logger.info("TCP connection established with SMSC at address " + remoteIpAddress);
            }
            if (newState.equals(SessionState.BOUND_TRX)) {
                logger.info("SMPP Transceiver connection established with SMSC at address " + remoteIpAddress + " and port " + remotePort);
            }
            if (newState.equals(SessionState.CLOSED) || newState.equals(SessionState.UNBOUND)) {

                logger.error("Connection closed, either by SMSC or there is network problem");
                if(newState.equals(SessionState.CLOSED))
                    logger.error("Connection closed");
                else
                    logger.error("Connection unbound");
                logger.info("Reconnecting.......");
                reconnectAfter(reconnectInterval);
            }
        }
    }

I don't why this code retries for fresh connection when it is already connected. Any clue is appreciated.

A: It seems the session still valid.
Make sure there are no zombie session, if there are any then close them all. It make sure the enquire link sending stop.


text:
Q: Huge point cloud laser data in PostGIS - Storing and Processing it I wonder, how it's possible to store huge sets of laser scanned point cloud data in PostGIS, with the time-aspect for processing it in mind. I know, there exists a geometry-object Point in PostGIS. But as far as I know it saves each point in a new tupel, which can make searching for any certain point a very slow process, if a few millions or more of them are stored.
I found a paper from HSR Universtiy of Applied Sciences Rapperswill, discussing this topic. It suggests three ways to store such data: Whole data in one tupel, Each point in one tupel or Splitting Data into Blocks which are referenced by info-tables, holding the extends of each block. As the third way seems the most useful for locating stored points, I wonder if anyone already has made some experiences with it?
The paper can be found here: http://wiki.hsr.ch/Datenbanken/files/pgsql_point_cloud.pdf
Last but not least, I stumpled across a project on github, which seems to deal with point cloud manners in PostgeSQL. Unfortunately not much information about it around the net. So the same question here: Has someone already made some experiences with it? Is it usable for such purposes?
Project can be found here: https://github.com/pramsey/pointcloud
I would also be glad to hear about other suggestions, ideas or experiences, if there are any. But i must admit, that non-commercial solutions are prefered.

A: (The answer is based on my and others' comments above; haven't really tested it)
Store the points as MultiPointZM. The best grid size would probably be dependent on access patterns and you need to do some testing on this. A regular grid with a spatial index should make queries quite fast. If 3d access is important then MultiPointZM could be 3D block based(1) instead of a 2D plane grid, then (if you have PostGIS >= 2.0) you would be able to use &&& for fast 3D queries.
You could also store the grid pattern in a separate table, which might be useful e.g. when updating the data and validating that the MultiPointZM blocks stay within their bounds after edits etc.
Storing timestamps or other data would only be possible for a block at a time, but some binary / category data could be stored by disaggregating each block by attribute if there are not too many categories and/or attributes.
If you end up having to store the data as separate PointZM, then a foreign key on the grid table + B-Tree index would make loading only the specific points (probably) a lot faster than just queyrying the table directly, even with a spatial index.
(1) If the range of Z-values is small (it's a road, after all), this probably does not make sense.

A: There is a lot in your question. The short answer is yes, it is completely possible to store huge point cloud data in PostGIS and use it for processing. We've built such a full system that does this.
This video is a little out of date with it's numbers but we had TBs of mobile/terrestrial and aerial data in postgis accessible through python for processing in the back end and with a web front end allowing 3D viewing and downloading of the data.
https://vimeo.com/39053196
It really comes down to how you choose to store the data in PostGIS and how you are going to be accessing it. A good solution for aerial data might well be to grid the data in some way and use multipoints for efficiency. However, if you are working with mobile or terrestrial data where the point density can be between 500-30000+ points per metre squared this approach doesn't work. Then it comes down to looking at your hardware and the number of concurrent users you expect.
Details about this can be found in some of our papers
http://www.mendeley.com/profiles/conor-mc-elhinney/