text:
Q: A recursive fibonacci function in bash I was perusing the sight for some help with my code and came across a thread from about 4 months ago, however the user's final revision doesn't work when posted into bash, and produces some strange results.  Here is my version, which also produces some strange results:
#!/bin/bash
fib()
{
ind=$1

if (( ind <= 0 ))
 then echo 0
elif (( ind = 1 ))
 then echo 1
else
  echo $(( $(fib $((ind - 1)) ) + $(fib $((ind - 2)) ) ))
fi
}
echo fibbonacci sequence number $1 is $(fib $1)

so this block of code will end up always outputting 1.  ./fib.sh 5 outputs
fibbonacci sequence number 5 is 1
so I tried to write the code a little closer to what the previous asker had,
#!/bin/bash

fib()
 {
  ind=$1

if (( ind <= 0 ))
 then echo 1
else
  echo $(( $(fib $((ind - 1)) ) + $(fib $((ind - 2)) ) ))
fi
 }
 echo fibbonacci sequence number $1 is $(fib $1)

While I don't understand the logic here, it actually starts to output fibonacci numbers,
but now I get a slightly different problem; ./fib.sh 3 outputs:
fibbonacci sequence number 3 is 5
./fib.sh 5 outputs :
fibbonacci sequence number 5 is 13
Well we know that the 3rd fibonacci number is 1, and the 5th is 3 so what gives? The code seems to skip ahead several fibonacci numbers, and I can't figure out what is logically wrong with my code.

A: Usually when writing Fibonacci sequence logic you have to special-case the first two numbers. That's what the first user has done: special-casing 0 and 1.
You've removed one instance of special-casing and shifted everything by one index, which explains one shift. The other is easy: the code is zero-indexed. That's why everything is "off by two".
What's wrong with the original code? This line:
elif ((ind = 1))

sets ind to 1. Otherwise it's fine.
A simple fix to your code is to replace this line:
if (( ind <= 0 ))

with
if (( ind <= 2 ))

and off you go. That gives you the one-indexed behavior you'd expect:
cternus@astarael ~/foo> for i in `seq 1 10`; do ./foo.sh $i; done
fibbonacci sequence number 1 is 1
fibbonacci sequence number 2 is 1
fibbonacci sequence number 3 is 2
fibbonacci sequence number 4 is 3
fibbonacci sequence number 5 is 5
fibbonacci sequence number 6 is 8
fibbonacci sequence number 7 is 13
fibbonacci sequence number 8 is 21
fibbonacci sequence number 9 is 34
fibbonacci sequence number 10 is 55

A: #!/bin/bash

function fib(){
    if [ $1 -le 0 ]; then
        echo 0
    elif [ $1 -eq 1 ]; then
        echo 1
    else
        echo $[`fib $[$1-2]` + `fib $[$1 - 1]` ]
    fi

}

fib $1

A: #!/bin/bash
#fibonacci sequence function
fib()
{
ind=$1

if (( ind <= 0 ))
 then echo 0
elif (( ind == 2 ))
 then echo 1
else
  echo $(( $(fib $((ind - 1)) ) + $(fib $((ind - 2)) ) ))
fi
}
echo fibbonacci sequence number $1 is $(fib $1)

So my problem was with the equality check in
elif (( ind = 1 ))

I should have used the double =, and change the 1 to a 2, so it should have been
elif (( ind == 2 ))

Ultimately my correct script should look like this
#!/bin/bash
#fibonacci sequence function
fib()
{
ind=$1

if (( ind <= 1 ))
 then echo 0
elif (( ind == 2 ))
 then echo 1
else
  echo $(( $(fib $((ind - 1)) ) + $(fib $((ind - 2)) ) ))
fi
 }
echo fibbonacci sequence number $1 is $(fib $1)

Thanks a bajillion and one to Christian Ternus for the help, I've been programming for a few years now and totally should have seen the equality check error >.<

A: Interestingly enough, the Korn shell executes @christianternus' script much faster than other shells:

$ for a in sh bash zsh ksh; do echo "shell: $a"; time for i in $(seq 1 20); do $a bin/fib.sh $i; done | md5sum; done
shell: sh
5fece53a38f2df040bfaf9632c2b7f4b  -
real    0m29.508s
user    0m3.788s
sys     0m11.785s

shell: bash
5fece53a38f2df040bfaf9632c2b7f4b  -
real    0m29.906s
user    0m3.604s
sys     0m11.235s

shell: zsh
5fece53a38f2df040bfaf9632c2b7f4b  -
real    0m29.203s
user    0m2.505s
sys     0m14.377s

shell: ksh
5fece53a38f2df040bfaf9632c2b7f4b  -
real    0m0.942s
user    0m0.843s
sys     0m0.079s


text:
Q: Which is efficient: Switch, If or function? I will need to handle a piano key that can respond as fast as possible without high CPU load with repetitive key press and release on virtual piano in Flex application.
Is calling function much effective or Switch?
Example:
switch(keyNote)
case 'c4': keypress.button=down;
case 'c4': keypress.button=down;
case 'c4': keypress.button=down;
case 'c4': keypress.button=down;
case 'c4': keypress.button=down;
case 'c4': keypress.button=down;

or
function () {
if (keyNote=='c4'){keypress.button=down}
if (keyNote=='c4'){keypress.button=down}
if (keyNote=='c4'){keypress.button=down}
if (keyNote=='c4'){keypress.button=down}
}

or
function c4_Key() {
keypress.button=down;
}

I also wonder if there another method using dispatchevent to call a button by id and set button with down state?

A: Do not go with your own if, if, if function. The compiler does not like options ( eg. if can be either true or false )
I would make a dictionary object, so that you could get the response like:
var keyMap:Dictinary = new Dictionary()
//Here you would populate the dictionary with the diff. keys and values

//pseudo body of keyDown test funcion
keyMap[keyNote].keypress.down;

Or whatever your example code seeks to do :)

A: well, if you ask some OOP experts, the best thing to do is to avoid conditionals like the plague.
http://www.as3dp.com/2007/12/21/lets-get-rid-of-conditionals/
The idea is that each condition is in a separate class that overrides/extends the function which would do the switch.
While I personally have not eliminated the use of conditionals in my code, I do try to use this approach over the conditionals. And you really can replace all(just about) conditionals this way, sometimes the benefit does not outweigh the work that goes into it, especially if you know that you won't be extending the code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is React functional component state not retaining state value? In the following React functional component there is a local emailAttachments state. Initially it is an empty array. There is an event handler that accepts an instance of EmailAttachment which is to be appended to the emailAttachments array.
interface EmailAttachemnt {
  emailAttachmentID: number;
  fileName: string;
}

const MemberEmailForm: React.FC<MemberEmailProps> = (props) => {

  const [emailAttachments, setEmailAttachments] = React.useState<Array<EmailAttachment>>([]);

  const handleAttachmentAdded = (attachment: EmailAttachment) => {
    const a = [...emailAttachments];
    setEmailAttachments([...a, ...[attachment]]);
  }

}

When the handler is called with a new EmailAttachment instance the first time the instance is appended to the empty array. and the UI updated as React senses the state change. (below)
      <List>
        {emailAttachments.map((a: EmailAttachment) => (
          <ListItem key={a.emailAttachmentID}>
            <ListItemText primary={a.fileName} />
            <ListItemSecondaryAction>
              <IconButton edge="end" >
                <DeleteIcon />
              </IconButton>
            </ListItemSecondaryAction>
          </ListItem>
        ))}
      </List>

However, when the event handler is called the second and subsequent times the emailAttachments is an empty array to the emailAttachments array never contains more than one instance, the last one passed to the handler.
The handler initially updated the array using this
setEmailAttachments([...emailAttachments, ...[attachment]]);

then this approach
setEmailAttachments([...emailAttachments, attachment);

then after some research this approach where the original array is copied first
const a = [...emailAttachments];
setEmailAttachments([...a, ...[attachment]]);

However, in both approaches the behavior is the same, the emailAttachments array is always empty when the handler executes.
Is there a more appropriate approach that would result in the subsequent instances being appended and the array containing all instances?

A: Sounds like you are enqueueing state updates in a loop. Since component state is const and you enqueue a bunch of state updates within a render cycle, you should use a functional state update to update state from the previous state, not the state from the previous render cycle.
functional updates
setEmailAttachments(emailAttachments => [
  ...emailAttachments,
  ...[attachment],
]);


text:
Q: Which library is the best to use for MongoDB with Scala? I want to use MongoDB with Scala.
I found 2 libraries for it.

*

*lift-mongo

*mongo-scala-driver

Could you please tell me which library is the best to use?
And please tell me other one if you know.

A: As an unbiased user of Casbah for a while now, I say, use Casbah for sure.
Check it:
val mongo = MongoConnection()
val coll = mongo("myDB")("myCollection")
val builder = MongoDBObject.newBuilder
builder += "username" -> "Janx"
builder += "comment" -> "Casbah is cool!"
coll += builder.result.asDBObject

That's of course just a taste. It's so refreshing to use especially if you come from the Java driver. And since it's now the Scala driver supported by 10Gen and the talented Mr. McAdams, it's really a no-brainer. Cheers!

A: We were sort of unsatisfied with the way Casbah works for deep objects or simple maps and no real case class mapping support so we rolled our own MongoDB Synchronous Scala driver on top of the legacy java driver which I would like to shamelessly plug here with an example on how to store and retrieve a map and a simple case class. The driver does not have a lot of magic and is easy to setup and features a simple BSON implementation which was inspired by the Play2 JSON impl.
Here is how to use it with some simple values:
val client = MongoClient("hostname", 27017)
val db = client("dbname")
val coll = db("collectionname")

coll.save(Bson.doc("_id" -> 1, "vals" -> Map("key1" -> "val1")))
val docOpt = coll.findOneById(1)  // => Option[BsonDoc]

for(doc <- docOpt)
  println(doc.as[Map[String, String]]("vals")("key1"))  // => prints "val1"

And with a case class:
case class DnsRecord(host: String = "", ttl: Long = 0, otherProps: Map[String, String] = Map())

case object DnsRecord {
  implicit object DnsRecordToBsonElement extends ToBsonElement[DnsRecord] {
    def toBson(v: DnsRecord): BsonElement = DnsRecordToBsonDoc.toBson(v)
  }

  implicit object DnsRecordFromBsonElement extends FromBsonElement[DnsRecord] {
    def fromBson(v: BsonElement): DnsRecord = DnsRecordFromBsonDoc.fromBson(v.asInstanceOf[BsonDoc])
  }

  implicit object DnsRecordFromBsonDoc extends FromBsonDoc[DnsRecord] {
    def fromBson(d: BsonDoc): DnsRecord = DnsRecord(
      d[String]("host"),
      d[Long]("ttl"),
      d[Map[String, String]]("op")
    )
  }

  implicit object DnsRecordToBsonDoc extends ToBsonDoc[DnsRecord] {
    def toBson(m: DnsRecord): BsonDoc = Bson.doc(
      "host" -> m.host,
      "ttl" -> m.ttl,
      "op" -> m.otherProps
    )
  }
}

coll.save(DnsRecord("test.de", 4456, Map("p2" -> "val1")))
for (r <- coll.findAs[DnsRecord](Bson.doc("host" -> "test.de")))
  println(r.host)

A: You should take a close look at Casbah, which is the official(and fully supported ) MongoDB Scala driver:
http://api.mongodb.org/scala/casbah/latest
Im admittedly biased as the creator and maintainer of the project but the official support brings a lot of benefit including the fact that there is a fulltime developer behind it. There are solid type conversion wrappers built in for common Scala types and Scala collections style implementations of DBObject which are much better than the default Java objects many of the other drivers use. There is also a full query dsl which maps to Mongo query syntax.
I like the Lift stuff as well and have recently started working w/ the Lift team to help improve it.  Foursquare just released a query dsl for lift-mongo-record called Rogue which drives their own Scala+MongoDB system:
http://GitHub.com/foursquare/rogue
I have found most people are using either Lift or Casbah, but YMMV. Feel free to ping me if you need more help.


text:
Q: aligning a div Horizontal & Vertical using CSS in Safari I am trying to algn a div  in Horizontal & Vertical way using CSS. This approach is working on Chrome, but doesn't work in Safari.
.in-middle { min-height: 100%; min-height: 100vh; display: flex; align-items: center; justify-content: center; flex-direction: column; }

Code Working:
http://jsfiddle.net/gjrwndye/1/
Is there any suggestions how can I improve it to make it working on safari as well .

A: Use browser prefixes.
jsfiddle: http://jsfiddle.net/3gkh6gz3/
display: -webkit-flex;
-webkit-justify-content: center;
-webkit-align-items: center;

You can check if you need to use prefixes using Should I Prefix.
You can automatically prefix your CSS using Autoprefixer.


text:
Q: counter-example: aboslute convergence => convergence in incomplete vector space Is the following statement true?
Let $X$ be a normed linear space, $x_k \in X$, $k \in \mathbb{N}$ and $\sum_{k=0}^\infty \lVert x_k\rVert$ convergent. Then $\sum_{k=0}^\infty x_k$ is also convergent.
I dont think so (for the incomplete case). However, I could not find a counterexample.
Thanks for your help!

A: It is slightly more interesting to show that for any incomplete space, there is a divergent series $\sum x_n$ with $\sum\|x_n\|<\infty$.
To see this, start with a non-convergent Cauchy sequence $(u_n)$. For each natural number $k$, pick $n_k$ so that $i,j\ge n_k$ implies $\|u_i-u_j\|<2^{-k}$. Also, make sure you pick them so $n_{k+1}>n_k$ for every $k$.
Now let $x_1=u_{n_1}$, and $x_k=u_{n_{k+1}}-u_{n_k}$ for $k\ge2$. Then $\|x_k\|<2^{-k}$, so $\sum\|x_n\|<\infty$. And yet $\sum_{j=1}^kx_j=u_{n_{k+1}}$, and that does not have a limit as $k\to\infty$.
(You need the fact that even in a non-complete space, if a Cauchy sequence has any convergent subsequence then the total sequence is convergent as well.)

A: Let
$$X:=\left\{\;\{x_n\}_{n\in\Bbb N}\subset\Bbb R\;;\; \exists N\in\Bbb N\;\;s.t.\;\;x_n=0\;\;\forall n>N\;\right\}$$
The above is just the long way to say $\;X\;$ is the vector space of all real sequences with finite support, and this is normed space wrt
$$||\{x_n\}||=\max_{n\in\Bbb N}|x_n|$$
Take now the sequence
$$\left\{h_m:=\left(0,0,...,\overbrace{\frac1{m^2}}^{m-th\;\;\text{place}},0,\ldots\right)\right\}_{m\in\Bbb N}$$
and observe that
$$\sum_{n=1}^\infty ||h_n||=\sum_{n=1}^\infty\frac1{n^2}$$
converges.
Now show that for any element  $\;x\in X\; ,\;\;\; h_n\rlap{\;\;\;/}\longrightarrow x\;$


text:
Q: How to define Systick handler function Code Composer Studio for cc1310? I opened a new NoRTOS CCS project and modified as follows for using periodic systick interrupt:

*

*STCSR Register -> bit0 defined as 0  // Systick disabled

*STRVR Register -> RELOAD value defined  // 24MHz clock every step is 41.6ns

*NVIC_IPR3 Register -> bit24 priority is defined for Systick

*STCSR Register -> bit0, bit1, bit2 are set //Systick enabled

with this modification when the Current value of Systick is 0, COUNTFLAG(16th bit of STCSR Register) gets set as should be.
My problem is defining Systick handler.
There is no startup.s file in the project folder. So I can not find the vector table.
Where is the vector table is defined in CCS projects?
Any help will be appreciated.

Best Kind Regards,


text:
Q: What's a good name for "total wall clock time of all cpus?"
There are only two hard things in Computer Science: cache invalidation
  and naming things.
-- Phil Karlton

My app is reporting CPU time, and people reasonably want to know how much time this is out of, so they can compute % CPU utilized.  My question is, what's the name for the wall clock time times the number of CPUs?
If you add up the total user, system, idle, etc. time for a system, you get the total wall clock time, times the number of CPUs.  What's a good name for that?  According to Wikipedia, CPU time is:

CPU time (or CPU usage, process time) is the amount of time for which
  a central processing unit (CPU) was used for processing instructions
  of a computer program, as opposed to, for example, waiting for
  input/output (I/O) operations.

"total time" suggests just wall clock time, and doesn't connote that over a 10 second span, a four-cpu system would have 40 seconds of "total time."

A: Total Wall Clock Time of all CPUs
Naming things is hard, why waste a good 'un once you've found it ?

A: Aggregate time: 15 of 40 seconds.


text:
Q: Accessing files outside document root I want to access a directory full of mp3 files that is located outside my root directory of my virtual server.
I have tried numerous different configurations in the virtual host with no luck. The more I read, the more different solutions I see.  None of them work for me.
Here is the best I can manage
    DocumentRoot /var/www/www.dmdefd.com

    ServerName www.dmdefd.767

    <Directory "/var/www/www.dmdefd.com">
       allow from all
       Options Indexes FollowSymLinks MultiViews
       Require all granted
    </Directory>

alias /mp3music '/media/dmd/DUsers/music'

    <Directory "/media/dmd/DUsers/music">
       #Options Indexes MultiViews FollowSymLinks - no help
       Options +Indexes
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>

I restart Apache and I then try to access the files from PHP with
<?php
   $root = $_SERVER["DOCUMENT_ROOT"];
   $time = new Datetime();
   echo $time->format ("H:i:s")."
";

   echo $root."
";
   echo realpath ("$root/mp3music")."
";

   $biglist = scandir ("$root/mp3music/");

?>

and the result is
Warning: scandir(/var/www/www.dmdefd.com/mp3music/): failed to open dir: No such file or directory in /var/www/www.dmdefd.com/musicmanager/aliases.php on line 9

Warning: scandir(): (errno 2): No such file or directory in /var/www/www.dmdefd.com/musicmanager/aliases.php on line 9

Please note that the virtual server works fine, I just can't get to the files.

A: Your PHP code looks for your on-disk music under the DOCUMENT_ROOT CGI variable. There is only one DOCUMENT_ROOT -- it doesn't change if you happen to access files via an Alias or mod_userdir.
Apache has a relatively recent/priority addition in 2.4 called CONTEX_DOCUMENT_ROOT which would be the prefix supplied by an Alias directive.
Other then that, you could just set your own environment variable in the Apache config, or let your PHP code know where your music lives directly.


text:
Q: Can't figure out CSS Sticky Footer!
Possible Duplicate:
How do you get the footer to stay at the bottom of a Web page?

Hello,
I can't get my footer to stick to the bottom of my page!!  I have been trying everything and I can't get the sticky html/css code to work
No matter what I do, the footer is offset, or half way up the page... I have tried like 3 different versions of code to make it stick, no luck
could someone please help me??  If someone could please tell me the correct coding
My site is:
http://graves-incorporated.com/test/index.html
Css:
http://graves-incorporated.com/test/p7csslm/p7csslm10.css
Thanks,
Dan
mrlincoln89@hotmail.com

A: adding position: fixed to your footer usually does the trick(then set bottom: 0 )
something like this:
#footer {
  position: fixed;
  bottom: 0;
}

for more information try this link:
How do you get the footer to stay at the bottom of a Web page?

A: You may want to take a look at this site.
Hope it helps.


text:
Q: Wordpress homepage banner not appearing My homepage banner image is not appearing. I have done some troubleshooting:
1. I noticed on the back-end in visual composer that the revolution slider block had been deleted. I have re-added it, but its still not working
2. I have checked the revolution slider plugin but all appears ok
3. I have updated all plugins
4. I also noticed on the homepage that the 'Blog' post thumbnails aren't showing up either. the heading is there but the 3 latest blog posts are missing.
Maybe it is something to do with visual composer?
Can anyone suggest any other troubleshooting tips?
Website is:
www.skinmade.com.au


text:
Q: why is sideways tire slip separated from forward slip on Unity wheel collider? I finally understood why my car in unity can't drift/powerslide like cars do in other racing games. Feel free to skip the boring part and only read the question down below if you know this issue.
problem:
Not realistic car grip/drift happens because tire slip value (from which the tire grip is evaluated) is separately measured for forward and sideways friction of wheel. This means that when you are in a turn with RWD car and you give car more throttle, rear tires lose forward grip and start to slip forward but car won't start to drift sideways like in reality because even though rear tires started slipping forward, sideways slip is still the same thus there will be no change on sideways friction curve and car will not lose any sideways grip. For the same reason cars with unity wheel colliders can't do handbrake turns because rear wheels will start to slip forward but that only influences forward grip not sideways.
real tire physics:
From a physics standpoint it's obviously not realistic because when tire starts to slip it goes from static friction where it sits on road to kinetic friction where it is doing lots of little jumps and this "jumping state" of kinetic friction affects tire grip in all directions not just forward or sideways separately.
my theoretical solution:
So the obvious solution would be that we can keep separated friction curves (because of different tire tread designs) but the slip value for these friction curves must be only one, evaluated as magnitude of vector2 of sideways and forward tire movement (slip). Unfortunately we can't modify slip value only extremum, asymptote and stiffness of friction curve.
finally the question:
Is there something that I am missing with separated forward and sideways slips to make car drift realistically and if not, is there any workaround with friction curve parameters to fix this issue or can you suggest me some alternative wheel colliders which doesn't have this issue?
THX in advance :)

A: Turns out that this really is one of few current wheel collider's issues. Handbrake turning can easily be simulated with code that for example decreases rear wheel colliders sideways friction stiffness or extremum value (stiffness works better) when player uses handbrake.
Throttle controlled power-slides are more complicated to accomplish with wheelcolliders, I tried to linearly decrease sideways stiffness or extremum value on rear wheels sideways friction curve when their forward spin exceeded extremum spin which helped but car was hard to control however if you have time for optimizing this kind of algorithm, you probably could make it work at some point.
Another approach would be to apply a little side force on rear of the car to make it drift under specified circumstances.
But if you really want to have fun and a realistic vehicle physics I highly suggest getting some vehicle physics system from unity asset store or alternative wheelcolliders from github.


text:
Q: Parse java file in maven to create separate file with identifiers and line numbers I am trying to make it easy for my non-developers to locate certain exceptions in my code and so I want to figure out if there is a way I can have maven search through my source as it is being built, pick out these specific exceptions and add them with the source code file name and line number to a separate file.  For instance this code:
throw new MyException("1234-ABCDEF-1234-CDEF45");

would add an entry in a file in the JAR when I compiled that would look like this:
1234-ABCDEF-1234-CDEF45,com\me\test\MyJavaFile.java,267

With that information, if my support staff has "1234-ABCDEF-1234-CDEF45" as an error they could cross reference that value in the file and know the file/line number.  BTW I understand that printing the stack trace to the log would also give them this information, but I am purposely not printing the stack trace to the log file because these happen a lot and are excepted in the normal flow of the program.


text:
Q: É possivel verificar o tamanho de uma string que está dentro de um array? Eu tenho um array que é construido pelos resultados das chekbox selecionadas...
Ele retorna com um var_dump:
array(3) { [0]=> string(7) "BXT0022" [1]=> string(7) "BXT0010" [2]=> string(7) "BXT0024" }

Eu só quero chekar se tem algo no array ou se ele está vazia, mas não estou conseguindo porque se não tiver nada selecionado ela retorna isto:
string(0) ""

Como posso fazer um if (não tem nada no array) faz o implode... Tentei com o count do array mas dá sempre 1 mesmo sem nada escolhido , issset também tem lá algo e não funciona... Não sei o que mais usar...
Tem jeito de chekar o comprimento da string que o array retorna?

A: Use empty:
if(empty($variavel)) { ...

Ele retorna true tanto para strings vazias, quanto para arrays vazias.

A: Ao utilizar implode num array vazio vai dar 1 porque o array inicia na posição 0 então vc tem q diminuir 1 da variável q conta o tamanho do array

A: if(strlen($variavel) > 0)

Vai verifica quantos caracteres tem a string passada, se for maior que 0, é por que tem algo
Mas pode ser usado varios:
if(!isset($variavel))
if($variavel != "")
if($variavel != NULL)
if($variavel[1]) - uma string pode ser usada como array sem ter que fazer ela ser um array

A: Use o strlen (http://br1.php.net/manual/pt_BR/function.strlen.php) para saber se a stringé maior que 0.
O isset apenas vai dizer se a variável foi iniciada, que nesse caso foi, poré, foi iniciado vazia.
Abs


text:
Q: setCollectionBehavior not taking affect on already opened window A user clicks a "take screenshot in 10seconds" button in my application. Then user focuses another app and makes it full screen. While user is focused in this full screen app, my 10sec timer now hits 0. My application opens a window that is full size of monitor, it draws the screenshot on it. But now I want the window to show on all spaces. I tried this:
[window setCollectionBehavior:(16 | 1 | 256)];

But it is not making the window show over the users current space (Which is the full screen app) do you guys know whats up?
Just to verify, the magic numbers for these constants are:
var NSWindowCollectionBehaviorStationary = 1 << 4; // 16
var NSWindowCollectionBehaviorCanJoinAllSpaces = 1 << 0; // 1
var NSWindowCollectionBehaviorFullScreenAuxiliary = 1 << 8; // 256
var NSWindowCollectionBehaviorMoveToActiveSpace = 1 << 1;// 2

Is this correct? I am doing this via ctypes so have to use magic numbers.
I also tried:
 [window setCanBeVisibleOnAllSpaces:YES]

But it didnt work.
Thanks
Edit:
So this window is already opened and I dont have access to the storyboard etc as mentioned in a2's answer below, we discussed it in chat and we need to hook into it somehow to make this take affect, is there anyone with any ideas?

A: You need to add this code either in your xib / storyboard, either in your NSWindowController subclass -windowDidLoad method, either in your designated initialiser of your NSWindow subclass :
- (void) awakeFromNib {
    [self setCollectionBehavior:NSWindowCollectionBehaviorCanJoinAllSpaces];
}

OR
- (id)initWithContentRect:(NSRect)contentRect
                styleMask:(NSUInteger)styleMask
                  backing:(NSBackingStoreType)bufferingType
                    defer:(BOOL)flag {
    if (self = [super initWithContentRect:contentRect styleMask:styleMask  backing:bufferingType defer:flag]) {
        [self setCollectionBehavior:NSWindowCollectionBehaviorCanJoinAllSpaces];
    }
    return self;
}

OR if you have a NSWindowController
- (void)windowDidLoad {
    [super windowDidLoad];

    [[self window] setCollectionBehavior:NSWindowCollectionBehaviorCanJoinAllSpaces];
}

OR Edit the nib file and add this behaviour to your window in XCode.


text:
Q: Is it possible to use OpenGL ES on iOS through RubyMotion? I know RubyMotion is relatively new, but I'd like to find out if it's possible/easy to use OpenGL ES with it before I buy a license to make an iOS game I've been planning for a while.
The reason I'm wondering is that I understand RubyMotion wraps all the Cocoa/Objective-C stuff but OpenGL on iOS is a set of C functions (glBegin(), glEnd(), etc.)
If anyone that purchased RubyMotion could help me out in finding out or point me to a piece of documentation, I'd be extremely grateful.  Thank you.

A: Yes.
They have a working demo in the RubyMotionSample project https://github.com/HipByte/RubyMotionSamples/tree/master/HelloGL

A: Yes, it is. The official site says so.

Interfacing with C
You do not need to be a C programmer in order to use RubyMotion, however some basic notions, explained in this section, will be required.
  Objective-C is a superset of the C language. Objective-C methods can therefore accept and return C types.
  Also, while Objective-C is the main programming language used in the iOS SDK, some frameworks are only available in C APIs.
  RubyMotion comes with an interface that allows Ruby to deal with the C part of APIs.


text:
Q: ostringstream to vector
I've a strange error: I want to copy the content of an ostringstream into a vecotr of unsigned chars:

vector< uint8_t > buffer;
ostringstream os;
os << num1 << char1 << num2 << char2;

// 1. this will crash
buffer.insert( buffer.end(), os.str().begin(), os.str().end() );

// 2. this also crash
copy( os.str().begin(), os.str().end(), back_inserter( buffer );

string str = os.str();

// 4. this work
buffer.insert( buffer.end(), str().begin(), str().end() );

// 5. this also works
copy( str().begin(), tr().end(), back_inserter( buffer );

I can't understand why 1 and 2 crash on visual studio 2010.

Does someone has some suggest?

 EDIT
 The solution is:
vector< uint8_t > buffer;
ostringstream os;
os << num1 << char1 << num2 << char2;

const string& str = os.str();

// 4. this work
buffer.insert( buffer.end(), str().begin(), str().end() );

A: os.str().begin()

returns a new temporary string with the contents of os. You take an iterator to the beginning of it.
os.str().end()

returns another temporary string with the contents of os. You take an iterator to the end of it.
The two iterators are not valid since the temporary strings are out of scope now. In addition the iterators also do not belong to the same sequence (string here).
What you are doing is almost (not even considering the dangling iterators) equivalent to
string str1 = os.str();
string str2 = os.str();

buffer.insert( buffer.end(), str1.begin(), str2.end() );

A: ostringstream::str() returns a copy of the underlying buffer.
In your cases 1 & 2 you call str() twice (once for begin() and once for end()) so each resulting iterator relates to different copies of the buffer. Furthermore, those strings are temporaries so they go out of scope immediately, leaving the iterators "dangling".


text:
Q: SQLAlchemy session management in long-running process Scenario:

*

*A .NET-based application server (Wonderware IAS/System Platform) hosts automation objects that communicate with various equipment on the factory floor.

*CPython is hosted inside this application server (using Python for .NET).

*The automation objects have scripting functionality built-in (using a custom, .NET-based language). These scripts call Python functions.

The Python functions are part of a system to track Work-In-Progress on the factory floor. The purpose of the system is to track the produced widgets along the process, ensure that the widgets go through the process in the correct order, and check that certain conditions are met along the process. The widget production history and widget state is stored in a relational database, this is where SQLAlchemy plays its part.
For example, when a widget passes a scanner, the automation software triggers the following script (written in the application server's custom scripting language):
' wiget_id and scanner_id provided by automation object
' ExecFunction() takes care of calling a CPython function
retval = ExecFunction("WidgetScanned", widget_id, scanner_id);
' if the python function raises an Exception, ErrorOccured will be true
' in this case, any errors should cause the production line to stop.
if (retval.ErrorOccured) then
    ProductionLine.Running = False;
    InformationBoard.DisplayText = "ERROR: " + retval.Exception.Message;
    InformationBoard.SoundAlarm = True
end if;

The script calls the WidgetScanned python function:
# pywip/functions.py
from pywip.database import session
from pywip.model import Widget, WidgetHistoryItem
from pywip import validation, StatusMessage
from datetime import datetime

def WidgetScanned(widget_id, scanner_id):
    widget = session.query(Widget).get(widget_id)
    validation.validate_widget_passed_scanner(widget, scanner) # raises exception on error

    widget.history.append(WidgetHistoryItem(timestamp=datetime.now(), action=u"SCANNED", scanner_id=scanner_id))
    widget.last_scanner = scanner_id
    widget.last_update = datetime.now()

    return StatusMessage("OK")

# ... there are a dozen similar functions

My question is: How do I best manage SQLAlchemy sessions in this scenario? The application server is a long-running process, typically running months between restarts. The application server is single-threaded.
Currently, I do it the following way:
I apply a decorator to the functions I make avaliable to the application server:
# pywip/iasfunctions.py
from pywip import functions

def ias_session_handling(func):
    def _ias_session_handling(*args, **kwargs):
        try:
            retval = func(*args, **kwargs)
            session.commit()
            return retval
        except:
            session.rollback()
            raise
    return _ias_session_handling

# ... actually I populate this module with decorated versions of all the functions in pywip.functions dynamically
WidgetScanned = ias_session_handling(functions.WidgetScanned)

Question: Is the decorator above suitable for handling sessions in a long-running process? Should I call session.remove()?
The SQLAlchemy session object is a scoped session:
# pywip/database.py
from sqlalchemy.orm import scoped_session, sessionmaker

session = scoped_session(sessionmaker())

I want to keep the session management out of the basic functions. For two reasons:

*

*There is another family of functions, sequence functions. The sequence functions call several of the basic functions. One sequence function should equal one database transaction.

*I need to be able to use the library from other environments. a) From a TurboGears web application. In that case, session management is done by TurboGears. b) From an IPython shell. In that case, commit/rollback will be explicit.

(I am truly sorry for the long question. But I felt I needed to explain the scenario. Perhaps not necessary?)

A: The described decorator is suitable for long running applications, but you can run into trouble if you accidentally share objects between requests. To make the errors appear earlier and not corrupt anything it is better to discard the session with session.remove().
try:
    try:
        retval = func(*args, **kwargs)
        session.commit()
        return retval
    except:
        session.rollback()
        raise
finally:
    session.remove()

Or if you can use the with context manager:
try:
    with session.registry().transaction:
        return func(*args, **kwargs)
finally:
    session.remove()

By the way, you might want to use .with_lockmode('update') on the query so your validate doesn't run on stale data.

A: Ask your WonderWare administrator to give you access to the Wonderware Historian, you can track the values of the tags pretty easily via MSSQL calls over sqlalchemy that you can poll every so often.
Another option is to use the archestra toolkit to listen for the internal tag updates and have a server deployed as a platform in the galaxy which you can listen from.


text:
Q: how to increase vmware hard disk size i want to increase my vmware virtual pc harddisk size.....
i set default size of 8 gb but i want to increase its size.
there is no extend option in vmware but we can add an new hard disk..
i want to increase the existing hard disk size...
have an to it.... reply

A: There is a VMWare KB article that deals with this. As there are several ways of doing it I wont try and precis it here. Be aware that your host OS needs to be able to increase the size of the partition after the disk has been enlarged.

A: Option 1:
You should try to resize your VMWare drive using the VMDiskSize Tool.  As long as the disk doesn't contain snapshots, this should work just fine.
Option 2:
Also, I noticed that in my VMWare Player there is an option to expand the size of the disk, but it won't expand the filesystem.  You could in theory try that, and if the filesystem partition doesn't expand, you could always use a partitioning tool, like QtParted, to resize the partition to fit the new size.
If you do use this option, here are some instructions on Increasing Disk Space in VMWare.

A: You have two options:
1) shut machine down, extend disk (probably a CLI method) and then boot off an ISO that has an NTFS partition extender.
2) create a new virtual disk and assign it to the machine, boot the VM off a clonezilla ISO and duplicate and extend the smaller disk to the larger one.
Next time, thin provision and set the size pretty high, save you the pain later.


text:
Q: Turning Gabor Image Into Binary Image Currently I am doing a project that involves in extracting a fundus image. I am now (sort of) successful on achieving the Gabor image and now I am trying to turn it into a binary image based from the Gabored output.
My code are listed below:
%% Open all/selected fundus image from folder; Source: DIARETDB0
...
retG = retImg(:,:,2);   % Green Channel

%% Morphological Preprocessing - Gabor Filter
lambda = 8;
theta = 0;
psi = [0 pi/2];
gamma = 1.5;
sigma = 3;
bw = 1;
N = 12;
img_in = im2double(retG);
img_out = zeros(size(img_in,1), size(img_in,2), N);
orientation = {};
for n = 1:N
    gb = gabor_fn(bw,gamma,psi(1),lambda,theta,sigma)...
        + 1i * gabor_fn(bw,gamma,psi(2),lambda,theta,sigma);
    img_out(:,:,n) = imfilter(img_in, gb, 'symmetric');
    theta = theta + ((n-1)*pi/12);
end
img_out_disp = sum(abs(img_out).^2, 3).^0.5;
img_out_disp = img_out_disp./max(img_out_disp(:));
% Making it binary
bwImg = imbinarize(img_out_disp, 'global'); % Here I am using Otsu's

There's seems to be a problem for the result of bwImg (the binary of Gabor output) that it's not as close as I hoped for. I wanted to extract the retina feature, but in the binary image result, much of the retina roots aren't visible (some only made of specs). Thus the question, is there something that I miss or wrong in making of the program?
The images:


text:
Q: Selection sort algorithm is failing for some cases I am trying to implement selection sort algorithm. But i see that it is failing for some cases. I take two different arrays and get two different result.
Case 1: Integer [] arr= {100,90,6,43,12,1};   Result:{1,6,12,43,90,100}
Case 2: Integer [] arr= {100,90,6,43,12,7}; Result:{7,6,12,43,90,100}
Below is my code.
public class SelectionSort  {

    private static boolean less(Comparable v, Comparable w) {
        return v.compareTo(w)<0;
    }

    private static void exch(Comparable[] a,int i,int j) {
        Comparable swap=a[i];
        a[i]=a[j];
        a[j]=swap;
    }

    public static void sort(Comparable[] a) {

        int N= a.length;
        for(int i=0;i<N;i++) {
            int min=i;
            for(int j=i+1;j<N;j++) {
                if(less(a[j],a[min]))
                    min=j;
                exch(a,i,min);

            }

        }

    }

}

A: change the algorithm like the following, it works fine
int N= a.length;
for(int i=0;i<N-1;i++) {
     int min=i;

     for(int j=i+1;j<N;j++)
         if(less(a[j],a[min]))
           min=j;

     exch(a,i,min);
}

A: Are you sure that you want the exch to happen inside the j loop?


text:
Q: If K-2SO is alone, then who is "we" here? On planet Eadu, Captain Andor and his team went to search Galen Erso
and leaving K-2SO alone in spoiled Imperial plane:

K-2SO: What are they doing? If Cassian comes back, we're leaving
without them.

If K-2SO is alone, then who is "we" here?

A: He is referring to himself and Cassian as 'we'. The 'them' that he is referring to are Jyn, Baze and Chirrut.
Note that he's explicitly confirmed to be talking to himself in the official novelisation.

The tragedy of K-2SO's existence was this: The skills he most
cherished were skills his rebel masters disdained; and the skills he
considered crude and trivial were skills his masters were helpless to
learn.
Thus, his present circumstances: Instead of traveling to the research
lab to manhandle, capture, restrain, and extract the scientist Galen
Erso—a mission virtually requiring the talents of an Imperial security
droid, and which might (if handled delicately) permit the exercise of
multiple underutilized procedures hardcoded into K-2SO—he was rewiring
a communications array and locating faults in each of eighty-four
connectors by touch.
Such a task required a bare minimum of computational power. K-2SO had
more than enough to spare to listen to the goings-on in the cabin and
observe the landscape from the half-buried cockpit viewport.
He watched Jyn depart with disinterest. The woman had always verged on
disrespectful toward him.
He watched Baze and Chirrut depart with more robust disapproval. He
posited an array of scenarios involving their separation from the
U-wing, few of which ended in their continued well-being.
"What are they doing?" he asked sharply.
K-2SO was not a protocol droid, but he was designed for biological
interaction. He found that verbal discussion, even with himself,
spurred his creativity.
He soon came to a solution he was satisfied with.
"If Cassian comes back," he said, "we're leaving without them."


text:
Q: copy qt scene to clipboard as a PowerPoint object I was wondering if anyone knew the first thing about copying a qt scene to the clipboard and then being able to paste it into word as a grouped object. All I have in my scene are graphics text items, ellipses, and lines. It seems like something that could be made into shapes and lines and text that could be pasted into powerPoint as a group. I don't know where to start! Any ideas? Thanks!

A: I would attack this in two ways:
From the system perspective and from the office sdk perspective.
From the system perspective you are talking about the clipboard, mime types, and exactly what is stored in the clipboard, exactly.
From the office sdk perspective, you are talking about how it stores the pre-rendered elements.
Just from a quick look around, I found this info in the MS Office SDK:
http://msdn.microsoft.com/en-US/library/office/gg278315
http://msdn.microsoft.com/en-US/library/office/cc850847
and this on Clipboard managers:
http://en.wikipedia.org/wiki/Clipboard_manager
and this for the Qt connection to the clipboard:
http://qt-project.org/doc/qt-4.8/qclipboard.html#details
Now... from that start, I wrote this little bit of code:
I added a QPushButton and a QTextEdit to a MainWindow UI Form.  Then I went to the slot of the Push Button and put the following:
void MainWindow::on_pushButton_clicked()
{
    ui->textEdit->clear();
    QClipboard *c = QApplication::clipboard();
    foreach(QString format, c->mimeData()->formats())
    {
        ui->textEdit->append(format);
        ui->textEdit->append(c->mimeData()->data(format));
    }
    ui->textEdit->append("done");
}

I copied an oval and a rectangle from PowerPoint in Office 2010,

and then used the push button in my program.  This is the output it gave me:
application/x-qt-windows-mime;value="Preferred DropEffect"

application/x-qt-windows-mime;value="InShellDragLoop"

application/x-qt-windows-mime;value="PowerPoint 12.0 Internal Shapes"
ÀN
application/x-qt-windows-mime;value="Object Descriptor"
j
application/x-qt-windows-mime;value="Art::GVML ClipFormat"
PK
application/x-qt-windows-mime;value="PNG"
PNG

application/x-qt-image

application/x-qt-windows-mime;value="JFIF"
ÿØÿà
application/x-qt-windows-mime;value="GIF"
GIF89aã
application/x-qt-windows-mime;value="PowerPoint 12.0 Internal Theme"
Hý©
application/x-qt-windows-mime;value="PowerPoint 12.0 Internal Color Scheme"
Pý©
done

So it should be do-able, but you would need to figure out what is some of the stuff they are encoding in between the readable clear text.
Hope that helps.
PS You may have better luck trying to save the Qt elements as an SVG object or some other image on the clipboard.


text:
Q: Django start-up code (like initial caching) conflicts makemigrations. Operational Errors no such columns tables First of all I'm not a fan of "do it the django way" thing. Instead of spending hours to learn the django way I prefer to utilize my basic programming knowledge when I develop an application.
Background :

*

*Application I'm developing is a REST backend that stores localization values like language information.

*I want to take language information that is stored in the database and load it into memory once at startup and then serve that data from memory when a request comes.

*I created my model

    class Text(models.Model):
        language = models.CharField()
        key = models.CharField()
        text = models.CharField()

*

*Then ran python manage.py makemigrations and migrate commands as a regular step

*Then I jumped ahead and implemented my caching code and put it directly under admin.py(it could be urls.py it does not matter, it only needs to be run once)

    cached_languages = models.Text.objects.all()

*

*I go ahead and run my app and it is just working fine.

*Then I wanted to add a field to my Text model like

    class Text(models.Model):
        language = models.CharField()
        key = models.CharField()
        text = models.CharField()
        **dummy = models.CharField()**

*

*Then hit python manage.py makemigrations command and boom at line

cached_languages = models.Text.objects.all()

We get an error saying that
sqlite3.OperationalError: no such column: app_text.dummy
What should I do to fix this?

A: The problem is that django executes every line of code that is written even when you call python manage.py makemigrations. This means before django actually reflects the alterations to database it executes entire project and when it comes to the caching line it tries to get all rows from Text table which does not yet have column dummy but from django perspective (in code) table Text has a column dummy that's why it throws an error.
Solution A workaround is to put a flag in say settings.py
IS_RUNNING = False

and in manage.py add the following
from app import settings
if 'runserver' in sys.argv:
    settings.IS_RUNNING = True

and put your cache code after a flag check
if settings.IS_RUNNING:
     cached_languages = models.Text.objects.all()

then django won't try to get records while making migrations before applying them. The cache algorithm will only execute when you actually call runserver.


text:
Q: Upload image with curl put request from url I was trying to upload image using curl put request, And was able to upload image if the image is stored in local directory. but the problem is that i have to upload image from another image url.
could anyone help me.
    $localfile = "testing.jpg";
// echo filesize($localfile); die;
$url = API_URL . "pages/343/files/=".$localfile."?description=testing";

$fp = fopen ($localfile, "r");
$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_USERPWD, API_USERNAME . ":" . API_PASSWORD);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));

$http_result = curl_exec($ch);
$error = curl_error($ch);
$http_code = curl_getinfo($ch ,CURLINFO_HTTP_CODE);
// $jsonOutput =  json_decode($http_result, true);
curl_close($ch);
fclose($fp);

i have tried to change $localfile to
$localfile = "https://someurl/someimage.png";

but it gave me following error.
Warning: curl_setopt(): cannot represent a stream of type tcp_socket/ssl as a STDIO FILE* in C:\xampp\htdocs\newPutMedia.php on line 29

Warning: filesize(): stat failed for https://help.optimizely.com/hc/en-us/article_attachments/200205465/1._Site-Wide_Addition_gmc_BEFORE.png in C:\xampp\htdocs\newPutMedia.php on line 30

A: Apparently this is a bug in PHP cURL. You can use the bug fix as mentioned here or you can do this :

*

*Copy the file from URL to your local directory :
file_put_contents(__DIR_\_ . "/testing.jpg", file_get_contents($url));

*Use the new file stored in your server for cURL PUT request :
$localfile = __DIR_\_ . "/testing.jpg";

Since the bug does not exist for file reading from your server, the bug won't cause errors and this would perfectly work.


text:
Q: How to finger paint on Surface View In Android? How to perform finger paint operation on surface view in android. I want draw on surface view as well as play video on that surface view is it possible in android please help me thanks.

A: You have a good example in API Demo: FingerPaint
you can find it in the sample of your android sdk:
C:\ANDROID-SDK\samples\android17\ApiDemos\src\com\example\android\apis\graphics


text:
Q: CSS change background color of seperate div when another div is hovered Given a basic menu and div like below..

#link:hover ~ #custom {
    background: #ccc
}

        Link

  Custom Content

I have tried using the general sibling combinator but it isn't working.
Is there a way using CSS that I can get the custom div to also change background color when the nav item is hovered?
Do I need Javascript or can this be achieved more simply?

A: you can change mydiv css with hover mynav
try this css.

A: here is the simple code I hope this will help...

.card {
    width: 150px;
}

.image {
    height: 80px;
  background-color: tomato;
}

.description {
  height: 80px;
  background-color: limegreen;
}

.image:hover ~ .description .link,
.link:hover {
    color: #ff0;
    background-color: white;
    }

img

    some link

Fulfilled direction use continual set.

A: Yes you can do it using j-query.
The below will be the script code:

        Link

  Custom Content

Add this code to your above code and it will work


text:
Q: openpyxl conditional formatting with named style I have a named style, defined with:
style = openpyxl.styles.NamedStyle('style1')

style.fill = openpyxl.styles.PatternFill(patternType='solid', fill_type='solid', fgColor='BB0000')

style.border = openpyxl.styles.Border(left=openpyxl.styles.borders.Side(style='thin'),
                                      right=openpyxl.styles.borders.Side(style='thin'),
                                      bottom=openpyxl.styles.borders.Side(style='thin'),
                                      top=openpyxl.styles.borders.Side(style='thin') )

I want to have a conditional format, based on cell value, that uses this style.
I can do something like:
rule = openpyxl.formatting.rules.CellIsRule(operator='lessThan', formula=['0']', ...)

But this doesn't seem to take a named style. It takes either a differential style, or a fill and a border as separate things...

A: You can't use named styles with conditional formats. There are subtle differences in the way they're applied but they are also implemented and stored differently. Just create a DifferentialStyle in the same way as a named style and set this as the dxf for the rule. You can probably do this very easily:
dxf = DifferentialStyle(**dict(style))


text:
Q: How to override super-class constructor with array parameter in OOP PHP Hello i have a problem in OOP PHP.
I try override constructor from superclass to subclass with array parameter in it.
This is my superclass code :
    <?php
        class Person
        {

            private $firstName;
            private $lastName;
            private $gender;
            private $dob;
            private $address;
            private $country;
            private $phone;
            private $occupation;

            public function __construct($array) {
                foreach($array as $key => $value) {
                    $this->$key = $value;
                }
            }

                public function setFirstName($firstName) {
                    $this->firstName = $firstName;
                }

                public function getFirstName() {
                    return $this->firstName;
                }
            // Another Getter and Setter
            // ...

And this is my subclass code :
<?php

    class Register extends Person
    {

        private $nickName;
        private $email;

        public function __construct($array) {
            parent::__construct($array);
        }

        // Getter and Setter
        // ...

But when i try to access nickName and email, i get an error  like this :
Fatal error: Cannot access private property Register::$email in C:\xampp\htdocs\php\oop\class\person.class.php on line 16

And this is my test code :
<?php
    function __autoload($myClass) {
        require_once 'class/' . $myClass . '.class.php';
    }

    $data = array(
        'firstname'     => $_POST['first_name'],
        'lastname'      => $_POST['last_name'],
        'nickname'      => $_POST['nick_name'],
        'gender'        => $_POST['gender'],
        'dob'           => $_POST['dob'],
        'address'       => $_POST['address'],
        'zipcode'       => $_POST['zipcode'],
        'country'       => $_POST['country'],
        'phone_number'  => $_POST['phone_number'],
        'email'         => $_POST['email'],
        'occupation'    => $_POST['occupation']
    );

    $account = new Register($data);
    echo $account->getFirstName();

    // Proses DB
    // $db->insert($account);

?>

Any Sugesstion?
Thank you.
Answer :
I already find solutions. Key name in array must same with class property.
In array i write firstname and property firstName, the correct way is firstName in both, array and property.

A: One option is to make your private properties protected, so they can be accessed from a parent method.
Another option is to initialize the subclass's properties in the subclass constructor, and remove those entries from the array:
class Register extends Person
{

    private $nickName;
    private $email;

    public function __construct($array) {
        if (isset($array(['nickName'])) {
            $this->nickName = $array['nickName'];
            unset $array(['nickName'];
        }
        if (isset($array(['email'])) {
            $this->email = $array['email'];
            unset $array(['email'];
        }
        parent::__construct($array);
    }

A: That is how visibility works in PHP. If you want to access a property in a sub-class then it has to be either public or protected.
private properties are only visible inside the class that defined it.


text:
Q: Concatenate iterators in Groovy Given three iterators
it1, it2, it3

how can I return one iterator that iterates over it1, then over it2 and last it3?
Lets say
def it1 = [1, 2].iterator()
def it2 = [3, 4].iterator()
def it3 = [5, 6].iterator()

I want to have an iterator that will return
1
2
3
4
5
6

A: There's no such iterator that I know of in Groovy, but you could write your own:
class SequentialIterator<T> implements Iterator<T> {
    List iterators
    int index = 0
    boolean done = false
    T next

    SequentialIterator( Iterator<T> ...iterators ) {
        this.iterators = iterators
        loadNext()
    }

    private void loadNext() {
        while( index < iterators.size() ) {
            if( iterators[ index ].hasNext() ) {
                next = iterators[ index ].next()
                break
            }
            else {
                index++
            }
        }
        if( index >= iterators.size() ) {
            done = true
        }
    }

    void remove() {
        throw UnsupportedOperationException()
    }

    boolean hasNext() {
        !done
    }

    T next() {
        if( done ) {
            throw new NoSuchElementException()
        }
        T ret = next
        loadNext()
        ret
    }
}

def it1 = [1, 2].iterator()
def it2 = [3, 4].iterator()
def it3 = [5, 6].iterator()

assert new SequentialIterator( it1, it2, it3 ).collect() == [ 1, 2, 3, 4, 5, 6 ]

Or, if you're feeling greedy (and will need all the data loaded at the same time) you could just collect the values from the iterators in turn:
[ it1, it2, it3 ].collectMany { it.collect() }

Or as Dave Newton says, you could use Guava:
@Grab( 'com.google.guava:guava:15.0' )
import com.google.common.collect.Iterators

def it1 = [1, 2].iterator()
def it2 = [3, 4].iterator()
def it3 = [5, 6].iterator()

assert Iterators.concat( it1, it2, it3 ).collect() == [ 1, 2, 3, 4, 5, 6 ]

Or commons-collections;
@Grab( 'commons-collections:commons-collections:3.2.1' )
import org.apache.commons.collections.iterators.IteratorChain

def it1 = [1, 2].iterator()
def it2 = [3, 4].iterator()
def it3 = [5, 6].iterator()

assert new IteratorChain( [ it1, it2, it3 ] ).collect() == [ 1, 2, 3, 4, 5, 6 ]


text:
Q: How do I get the current font size of selected text using javascript? I am using contentededitable on a div and want to add an increase font size button for selected text.
Selected text meaning highlighted with the cursor.
In order to run
    document.execCommand('fontsize', false, size);
I need to know the size of the selected text, so I can increase it by 1. How do I get the font size of the currently selected text?
I tried:
    var size = document.getSelection().fontSize.toString();
but that was no bueno. I also tried
    document.execCommand('increaseFontSize', true, 1)
assuming it would increase it by one integer, but nothing happens, not even an error.
I tried this:
var el = document.getSelection();
var size = window.getComputedStyle(el, null).getPropertyValue('font-size');
But I get the error
Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'

A: You can determine the font-size of the parent element like this:
const selection = Window.getSelection();
if (selection) { // make sure it doesn't error if nothing is selected
  const size = window.getComputedStyle(selection.anchorNode.parentElement, null).getPropertyValue('font-size');
}

Window.getSelection() returns a Selection object. On those objects, the property anchorNode contains a reference to the textNode that selection is part of. That, in turn, has the usual parentElement property. From there it's easy.


text:
Q: Docker network macvlan, las subinterfaces no reciben contestación de arp Les cuento mi problema
tengo varios contenedores en docker con ip del estilo 192.168.X.2/24 de forma que cada contenedor esté en una subred distinta. Estas redes están creadas de la siguiente forma
docker network create -d macvlan   --subnet=192.168.4.0/24   --gateway=192.168.4.1   -o parent=eth0.4 test3

Estas maquinas están en un Centos7 en una maquina virtual con virtualbox y adaptador puente y la interfaz de red conectado a un router cisco de forma que ,de momento, todas estas redes tienen sus gateways en el puerto 1 como ips en la vlan1 como secondary
La idea es montar algo similar a esto pero con disntintas ip de vlans
https://docs.docker.com/v17.09/engine/userguide/networking/get-started-macvlan/#macvlan-8021q-trunk-bridge-mode-example-usage
EL problema es que las consultas arp de estas subinterfaces no reciben respuesta
08:00:41.132782 ARP, Request who-has 192.168.2.1 tell 192.168.2.2, length 28
08:00:42.135804 ARP, Request who-has 192.168.2.1 tell 192.168.2.2, length 28
08:00:42.138763 STP 802.1d, Config, Flags [none], bridge-id 8001.1c:17:d3:0d:d4:80.8001, length 43
08:00:43.138921 ARP, Request who-has 192.168.2.1 tell 192.168.2.2, length 28
08:00:44.143655 STP 802.1d, Config, Flags [none], bridge-id 8001.1c:17:d3:0d:d4:80.8001, length 43
08:00:45.134850 ARP, Request who-has 192.168.2.1 tell 192.168.2.2, length 28
08:00:46.136855 ARP, Request who-has 192.168.2.1 tell 192.168.2.2, length 28
08:00:46.151921 STP 802.1d, Config, Flags [none], bridge-id 8001.1c:17:d3:0d:d4:80.8001, length 43
08:00:47.138610 ARP, Request who-has 192.168.2.1 tell 192.168.2.2, length 28
08:00:48.153870 STP 802.1d, Config, Flags [none], bridge-id 8001.1c:17:d3:0d:d4:80.8001, length 43
08:00:48.521751 IP 192.168.50.2.64007 > 192.168.110.102.snmp:  GetRequest(62)  25.3.2.1.5.1 25.3.5.1.1.1 25.3.5.1.2.1
08:00:49.138713 ARP, Request who-has 192.168.2.1 tell 192.168.2.2, length 28

en cambio responde a ping desde la maquina virtual a las interfaces del router por lo que el fallo debe de estar en la dirección de arp.
probé a modificar el proxy_arp en las interfaces con
echo 1 > /proc/sys/net/ipv4/conf/all/proxy_arp
echo 1 > /proc/sys/net/ipv4/conf/all/forwarding
echo 1 > /proc/sys/net/ipv4/conf/all/proxy_arp_pvlan
echo 1 > /proc/sys/net/ipv4/conf/all/arp_filter

alguna ayuda ?


text:
Q: Search Google books api using RTK query in React I am using RTK query with react for searching books using google api. I have one input search field where the user can enter the book name and after clicking on the search button it will fetch data from google api.

For now, I am setting React as the default search keyword but I want that to be blank by default. Below is the component and apiSlice code where the fetching happens.
// Main Component
const BookFinder = () => {
  const [searchTerm, setSearchTerm] = useState('React');

  return (
    <>
      <Container>
        <Row className='mt-5'>

Book Finder

          <SearchBar {...{searchTerm, setSearchTerm}}/>
        </Row>
        <Row xs={2} md={4} className='g-5 mt-3'>
          <BookList {...{searchTerm}} />
        </Row>
      </Container>
    </>
  );
}

I am using react-bootstrap, font-awesome libraries here.
// Search Bar
const SearchBar = ({ searchTerm, setSearchTerm }) => {
  const searchBar = useRef()

  return (
    <>
      <InputGroup className="mb-3 pt-3">
        <Form.Control
          placeholder={searchTerm}
          aria-label="Search"
          aria-describedby="search"
          ref={searchBar}
        />
      <Button variant="outline-primary" id="search" onClick={() => setSearchTerm(searchBar.current.value)}>
        <FontAwesomeIcon icon={faMagnifyingGlass} />
      </Button>
      </InputGroup>
    </>
  );
}

import { useGetBooksQuery } from '../../services/bookSlice';
const BookList = ({ searchTerm }) => {
  const { data: books, isLoading, isSuccess, isError, error } = useGetBooksQuery(searchTerm)

  if(isLoading) {
    return (

        Loading...

    )
  }

  if(isError) {
    return
{error.toString()}

  }

  if(isSuccess) {
    const { items } = books
    // return jsx code using books
  }
}

The above code is using useGetBooksQuery hook to get the data.
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

export const bookSlice = createApi({
  reducerPath: 'bookApi',
  baseQuery: fetchBaseQuery({ baseUrl: 'https://www.googleapis.com/books/v1' }),
  tagTypes: ['Book'],
  endpoints: (builder) => ({
    getBooks: builder.query({
      query: (searchTerm) => `/volumes?q=${searchTerm}`,
      providesTags: ['Book'],
    }),
  }),
})

export const {
  useGetBooksQuery,
} = bookSlice

My problem is if I don't set the default value the api fails and gets an error. Is there any way I can omit the default value? So, the list will be empty the first time or will not call the google api when there is no value in text input. I think of using mutation instead of query but not sure if will it be the right thing to do. So use this platform to get some ideas to handle the above case. Thanks


text:
Q: phpMailer not sending mail, ErrorInfo is empty I'm designing a simple Contact Us form using phpMailer.  The data is passed to the PHP     correctly, but then the email is never sent.  I tried looking at the error info, but it's empty.  Any thoughts?  Thanks in advance!
<?php

    require_once('email/mail/class.phpmailer.php');

    $email_to = 'myEmail';
    $email_subject = 'Contact form';

    $fname = $_POST['firstname'];
    $lname = $_POST['lastname'];
    $email = $_POST['email'];
    $dob = $_POST['dob'];
    $subject = $_POST['subject'];
    $comments = $_POST['comments'];

    $mailer = new PHPMailer(true);
    $mailer->Host = '**********';
    $mailer->Username = '********';
    $mailer->Password = '*********';
    $mailer->SMTPAuth = true;
    $mailer->AddAddress($email_to);
    $mailer->SMTPDebug = false;
    $mailer->IsSMTP();
    $mailer->FromName = 'Contact Page';
    $mailer->From = "**********";
    $mailer->Sender = '**********';
    $mailer->Subject = $email_subject;
    $mailer->Body = "
        Source: Contact Page
        Name: ".$fname. " ".$lname."
        Email: ".$email."
        Date of Birth: ".$dob."
        Subject: ".$subject."
        Comments: ".$comments;

    echo "Data received";

    if(!$mailer->Send()) {
        echo 'Message was not sent.';
        echo 'Mailer error: ' . $mail->ErrorInfo;
    } else {
        echo 'Message has been sent.';
    }

?>

Output is:
Data receivedMessage was not sent.Mailer error:

Output of print_r($mailer):
PHPMailer Object (
    [Priority] => 3
    [CharSet] => iso-8859-1
    [ContentType] => text/plain
    [Encoding] => 8bit
    [ErrorInfo] =>
    [From] => contact@blah.com
    [FromName] => Contact Page
    [Sender] => contact@blah.com
    [Subject] => Contact form
    [Body] =>
        Source: blah
        Name: Derp McDerpson
        Email: derpallday@gmail.com
        Date of Birth: 1/1/2000
        Subject: The things!
        Comments: fix them
    [AltBody] =>
    [WordWrap] => 0
    [Mailer] => smtp
    [Sendmail] => /usr/sbin/sendmail
    [PluginDir] =>
    [Version] => 1.73
    [ConfirmReadingTo] =>
    [Hostname] =>
    [Host] => mail.authsmtp.com
    [Port] => 25
    [Helo] =>
    [SMTPAuth] => 1
    [Username] => blah
    [Password] => blah
    [Timeout] => 10
    [SMTPDebug] =>
    [SMTPKeepAlive] =>
    [smtp] =>
    [to] => Array (
        [0] => Array (
            [0] => blah@blah.com
            [1] => blah
        )
    )
    [cc] => Array ( )
    [bcc] => Array ( )
    [ReplyTo] => Array ( )
    [attachment] => Array ( )
    [CustomHeader] => Array ( )
    [message_type] =>
    [boundary] => Array ( )
    [language] => Array ( )
    [error_count] => 0
    [LE] =>
)

A: I believe that you are missing the actual send piece: $mailer->Send(); try adding that and running it

A: Solved it, I was trying to use the incorrect values for "from" and "sender", my server wasn't set up properly.  Thanks Jim and Patrick for your input.

A: First Name ".$_POST['fname']."company".$_POST['company']."Email".$_POST['email']."Telephone".$_POST['telelphone']."Comments"
.$_POST['comments']."";$headers="MIME-Version":1.0\r\n";$hearder="Content-type:text/html;charest=iso-8859-1\r\n";$headers.=
"FROM:".$_POST['email']."\r\n";mail($to,$subject,$body,$headers);echo'


text:
Q: In Playwright for Python, how do I use a QuerySelector to match partial text inside a tag? I am trying to match a H1 tag on a page that has several h1 tags using partial text.
For this example the text is "Your booking was"
<header data-v-20d51c72="" data-v-3cdc5826="" class="default__title">
   <h1 data-v-20d51c72="" data-v-3cdc5826="" class="default__title">Your booking was unsuccessful.</h1>
</header>

I can locate against the full text like this
 page.querySelector('//h1[normalize-space()="Your booking was unsuccessful."]')

I can also get a list of all h1 tags and then check the innerHTML for all
 [handle for handle in page.querySelectorAll('//h1') if handle.innerHTML().startswith('Your booking was')]

But this way, I can't wait for the handle to appear.
How can I write a selector so that I can match against a partial tag so that I can use page.WaitForSelector() on it?

A: Taking a hint from this SO question a working selector is
handle = page.querySelector('//h1[contains(., "Your booking was")]')

Where
print(handle.innerHTML())

prints 'Your booking was unsuccessful.'


text:
Q: jQuery validation plug-in warning-only custom rule In the jQuery validation plug-in from bassistance, is it possible to define a custom rule which displays an error message but does not block the user from submitting the form?
We have one particular field for which the software should give the user feedback on whether or not the provided value was found in an external system. But we leave it up to the user to decide on the validity of their input. In particular:

*

*$(from).validate().element(field) must return true even if the validator method returns false.

*But the same call must cause a validation message to appear.

*And all other validation rules still must be treated as usual. They block the submission if any value is invalid.


text:
Q: Нужно спарсить сайт на Python https://mediakit.iportal.ru/our-team
Нужно получить Имя, почту город и должность
как это можно сделать
пробовал единственным мне знакомым способом через тэги, совсем не выходит
Подскажите что нибуль

A: Вообще данный сайт является динамическим, т.е. элементы подгружаются при прокрутке. Поэтому вы не можете вытянуть информацию при запросе. Советую изучить библиотеку Selenium для такого вопроса.


text:
Q: Add `git remote add usptream` to repositories but using Ansible I have an Ansible 2.9.27 and I am trying to add upstream remote for git repositories which I previously cloned with Ansible. Let's assume that already cloned repositories are located in /home/user/Documents/github/ directory and I want to add upstream remote for them (git remote add upstream for each repo).
The task looks like this:
- name: Add remote upstream to github projects
  # TODO: how to add remote with git module?
  command: git remote add upstream git@github.com:{{ git_user }}/{{ item }}.git
  changed_when: false
  args:
    chdir: /home/user/Documents/github/{{ item }}
  loop: "{{ github_repos }}"

The issue is that ansible-lint doesn't like using command instead of git module:
WARNING  Listing 1 violation(s) that are fatal
command-instead-of-module: git used in place of git module
tasks/github.yaml:15 Task/Handler: Add remote upstream to github projects

What I need to do to add remote upstream for these repositories with git module?

A: Since what you want to achieve is not (yet...) taken in charge by the git module, this is a very legitimate use of command.
In such cases, it is possible to silence the specific rule in ansible lint for that specific task.
To go a bit further, your changed_when: false clause looks a bit like a quick and dirty fix to silence the no-changed-when rule and can be enhanced in conjunction with a failed_when clause to detect cases where the remote already exists.
Here is how I would write that task to be idempotent, documented and passing all needed lint rules:
- name: Add remote upstream to github projects
  # Git module does not know how to add remotes (yet...)
  # Using command and silencing corresponding ansible-lint rule
  # noqa command-instead-of-module
  command:
    cmd: git remote add upstream git@github.com:{{ git_user }}/{{ item }}.git
    chdir: /home/user/Documents/github/{{ item }}
  register: add_result
  changed_when: add_result.rc == 0
  failed_when:
    - add_result.rc != 0
    - add_result.stderr | default('') is not search("remote .* already exists")
  loop: "{{ github_repos }}"


text:
Q: turning morse into english from a txt file in C, only iterates 1 char in the string before stopping Using the code below it only reads one char and does not convert morse to letter. My idea was to create a string of one morse "letter" and put it in the convert function, however only 1 char is being read since I am only seeing a single 1 printed on the screen after the string itself is printed. The string only consists of '-' , '.' , ' '. I was wondering if anyone knows what the solution might be.
char convertToLetter(M* data, char word[10]) {

int size = 0;
char correct;
while (size < 60)
{
    int compare = strcmp(word, data->morse);
    if (compare == 0) {
        correct = data->letter;
    }
    data++;
    size++;
}
correct = '\0';
return correct;
}

int main(){

//some code here for opening a file.

char curSent[200];
char letter[6] = "";
int i = 0;
char* fullString = (char*)malloc(1000 * sizeof(char));
fullString[0] = '\0';
while (fgets(curSent, 200, inFile) != NULL) {

    if (curSent[0] != '\n') {

        curSent[strlen(curSent) - 1] = '\0';
        strcat_s(fullString,1000, curSent);

    }
    else {
        printf("%s", fullString);
        printf("\n\n");

        int j = 0;
        while (i < strlen(fullString)) {
            if (fullString[i] != ' ') {
                fullString[i] = letter[j];
                i++;
                j++;
                printf("%d \n", 1);

            }else if (fullString[i + 1] == ' ' && fullString[i] == ' ') {

                printf("%d", 2);
                printf(" %c", convertToLetter(dictionary, letter));
                memset(letter, 0, strlen(letter));
                j = 0;
                i = i + 2;

            }else if (fullString[i] == ' ') {
                printf("%d", 3);
                printf("%c", convertToLetter(dictionary, letter));
                memset(letter, 0, strlen(letter));
                j = 0;
                i = i++;
            }

        }

        memset(fullString, 0, strlen(fullString));
        i = 0;

    }

}
//printf("%s", fullString);
getchar();
return 0;

}


text:
Q: FROM keyword not found where expected 00923. 00000 - "FROM keyword not found where expected" select *,
(case when this.testtype in
( select testtype from Offer as o where o.testcenter=t.testcenter)
then 'yes' else 'no' end)
as offered
from Test as t;

A: The AS keyword is not syntactically valid before a table alias. You need to remove it from the outer query and from the sub-query.
You also need the table alias before the columns wildcard * when you are selecting other columns:
select t.*,                                     -- t.* rather than *
       (case
        when this.testtype in (
                select testtype
                from   Offer o                  -- Remove AS
                where o.testcenter=t.testcenter
             )
        then 'yes'
        else 'no'
        end
       ) as offered
from   Test t;                                  -- Remove AS


text:
Q: how to make href links fire C# methods when clicked What I basically want to do is when I click on an href link in html it should fire a C# method attached to that link. What are my options on doing this? the html onclick only looks for javascript functions. also note I am not linking to another page, I just want to use it to add arguments to the URL and then run C# and use those arguments in a method.

A: You would have to create a C# webmethod or WebAPI which you would use ajax to call.  You can not access a C# method directly from html or javascript unless you are using something like a server side control (LinkButton) which you could then add a C# handler for the click of that button.
So client side your 'onClick' would execute a javascript function.  The Javascript function would call the C# webmethod, passing in the parameters, then onSuccess you would have the results and do with them as you please.

A: You can pass your values in hidden field with form ,
<form name="FUN" method="post" action="FUN.aspx" onsubmit='return funCheckProgramName()' >
        <input name="userAction" type="hidden" value="submitName">

    ---------------------------------------------------------------------
function funSearchProgram()
{
    document.FUN.userAction.value="submitName";
}
    -----------------------------

Here you can have a single value which you want to post or you can use javascript to assign value to your hidden field .
=============================================================================
 **string str = Request.Form["userAction"].ToString();**

          =====================================

Now you have your value you can add handler
if (userAction.Trim ().Equals ("submitName"))
        submitNameHandler();

    private void submitNameHandler()
    {
               //Your Code goes here .
            }


text:
Q: Fail to load a dynamically generated bytecodes I have succeeded in dumping dynamically generated bytecodes to a file using ASM, but fail to load it. The error message is:
java.lang.ClassFormatError: JVMCFRE102 field signature invalid; class=TGWD, offset=0
    at java.lang.ClassLoader.defineClass(ClassLoader.java:364)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:284)
    at java.lang.invoke.ByteCodeClassLoader.run(ByteCodeClassLoader.java:20)

The BytecodeClassLoader is a Class I wrote here. The javap -v result is also shown below.
Classfile /C:/temp/TGWD.class
  Last modified Mar 10, 2015; size 750 bytes
  MD5 checksum 462ec39a439ab0d30c676eb92a93fd5a
public class TGWD extends java.lang.invoke.BaseTemplate
  minor version: 0
  major version: 51
  flags: ACC_PUBLIC, ACC_SUPER

Constant pool:
   #1 = Utf8               TGWD
   #2 = Class              #1             //  TGWD
   #3 = Utf8               java/lang/invoke/BaseTemplate
   #4 = Class              #3             //  java/lang/invoke/BaseTemplate
   #5 = Utf8               guard
   #6 = Utf8               Ljava/lang/invoke/MethodHandle;
   #7 = Utf8               trueTarget
   #8 = Utf8               falseTarget
   #9 = Utf8               <init>
  #10 = Utf8               (Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodHandle;)V
  #11 = Utf8               java.lang.invoke.MethodHandle
  #12 = NameAndType        #5:#11         //  guard:java.lang.invoke.MethodHandle
  #13 = Fieldref           #2.#12         //  TGWD.guard:java.lang.invoke.MethodHandle
  #14 = NameAndType        #7:#11         //  trueTarget:java.lang.invoke.MethodHandle
  #15 = Fieldref           #2.#14         //  TGWD.trueTarget:java.lang.invoke.MethodHandle
  #16 = NameAndType        #8:#11         //  falseTarget:java.lang.invoke.MethodHandle
  #17 = Fieldref           #2.#16         //  TGWD.falseTarget:java.lang.invoke.MethodHandle
  #18 = Utf8               eval
  #19 = Utf8               ()V
  #20 = Utf8               Hello
  #21 = Utf8               (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
  #22 = Utf8               java/lang/Throwable
  #23 = Class              #22            //  java/lang/Throwable
  #24 = NameAndType        #5:#6          //  guard:Ljava/lang/invoke/MethodHandle;
  #25 = Fieldref           #2.#24         //  TGWD.guard:Ljava/lang/invoke/MethodHandle;
  #26 = Utf8               java/lang/invoke/MethodHandle
  #27 = Class              #26            //  java/lang/invoke/MethodHandle
  #28 = Utf8               invokeExact
  #29 = Utf8               (Ljava/lang/String;)Z
  #30 = NameAndType        #28:#29        //  invokeExact:(Ljava/lang/String;)Z
  #31 = Methodref          #27.#30        //  java/lang/invoke/MethodHandle.invokeExact:(Ljava/lang/String;)Z
  #32 = NameAndType        #7:#6          //  trueTarget:Ljava/lang/invoke/MethodHandle;
  #33 = Fieldref           #2.#32         //  TGWD.trueTarget:Ljava/lang/invoke/MethodHandle;
  #34 = NameAndType        #28:#21        //  invokeExact:(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
  #35 = Methodref          #27.#34        //  java/lang/invoke/MethodHandle.invokeExact:(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
  #36 = NameAndType        #8:#6          //  falseTarget:Ljava/lang/invoke/MethodHandle;
  #37 = Fieldref           #2.#36         //  TGWD.falseTarget:Ljava/lang/invoke/MethodHandle;
  #38 = Utf8               Code
  #39 = Utf8               StackMapTable
  #40 = Utf8               Exceptions
{
  final java.lang.invoke.MethodHandle guard;
    flags: ACC_FINAL

  final java.lang.invoke.MethodHandle trueTarget;
    flags: ACC_FINAL

  final java.lang.invoke.MethodHandle falseTarget;
    flags: ACC_FINAL

  public TGWD(java.lang.invoke.MethodHandle, java.lang.invoke.MethodHandle, java.lang.invoke.MethodHandle);
    flags: ACC_PUBLIC, ACC_VARARGS

    Code:
      stack=0, locals=4, args_size=4
         0: aload_0
         1: aload_1
         2: bipush        0
         4: aaload
         5: putfield      #13                 // Field guard:java.lang.invoke.MethodHandle
         8: aload_0
         9: aload_1
        10: bipush        1
        12: aaload
        13: putfield      #15                 // Field trueTarget:java.lang.invoke.MethodHandle
        16: aload_0
        17: aload_1
        18: bipush        2
        20: aaload
        21: putfield      #17                 // Field falseTarget:java.lang.invoke.MethodHandle
        24: return

  public void eval();
    flags: ACC_PUBLIC

    Code:
      stack=0, locals=1, args_size=1
         0: return

  public java.lang.String Hello(java.lang.String, java.lang.String) throws java.lang.Throwable;
    flags: ACC_PUBLIC

    Code:
      stack=0, locals=3, args_size=3
         0: aload_0
         1: getfield      #25                 // Field guard:Ljava/lang/invoke/MethodHandle;
         4: aload_1
         5: invokevirtual #31                 // Method java/lang/invoke/MethodHandle.invokeExact:(Ljava/lang/String;)Z
         8: ifeq          21
        11: aload_0
        12: getfield      #33                 // Field trueTarget:Ljava/lang/invoke/MethodHandle;
        15: aload_1
        16: aload_2
        17: invokevirtual #35                 // Method java/lang/invoke/MethodHandle.invokeExact:(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
        20: areturn
        21: aload_0
        22: getfield      #37                 // Field falseTarget:Ljava/lang/invoke/MethodHandle;
        25: aload_1
        26: aload_2
        27: invokevirtual #35                 // Method java/lang/invoke/MethodHandle.invokeExact:(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
        30: areturn
      StackMapTable: number_of_entries = 1
           frame_type = 21 /* same */

    Exceptions:
      throws java.lang.Throwable
}

Can i anyone have an idea where is wrong in the generated bytecodes? Thanks.
I also attached the class file hereClass File..
Below information maybe useful:
1,
According to the stack, i guess the problem is at three field members. I use below code to generate these fields:
FieldVisitor fv;
fv = cw.visitField(ACC_FINAL, 'guard', "Ljava/lang/..", null, null);
fv.visitEnd();

I change ACC_FINAL to the ACC_PRIVATE. The result is the same except none of three field member is shown in javap -v result.
2, The Base class BaseTemplate is an empty abstract class defined as:
public abstract class BaseTemplate { }

==============================
Update:
After changing the putfield instruction in my original code from
mv.visitFieldInsn(PUTFIELD, className, list.get(i).name(), list.get(i).type());
to
mv.visitFieldInsn(PUTFIELD, className, list.get(i).name(),Utils.getFieldDesc(list.get(i).type()));, the class loading succeeds now. The reason is that wronlg field signature set(as in @Holger answers).

A: You generated your constructor using "java.lang.invoke.MethodHandle" as the field signature rather than the correct "Ljava/lang/invoke/MethodHandle;". This can be seen in the javap output by the lines:
     5: putfield      #13             // Field guard:java.lang.invoke.MethodHandle
…
    13: putfield      #15             // Field trueTarget:java.lang.invoke.MethodHandle
…
    21: putfield      #17             // Field falseTarget:java.lang.invoke.MethodHandle

whereas the Hello method correctly uses:
     1: getfield      #25             // Field guard:Ljava/lang/invoke/MethodHandle;
…
    12: getfield      #33             // Field trueTarget:Ljava/lang/invoke/MethodHandle;
…
    22: getfield      #37             // Field falseTarget:Ljava/lang/invoke/MethodHandle;

This also explains the rather big constant pool. Item #11 contains the wrong java.lang.invoke.MethodHandle signature which is then used by the followup items #12 - #17 which are used by the constructor. These are distinct from the items #25, #33, and #37 used in the Hello method. In a correctly generated class, these instructions share the same items in the constant pool (which all refer indirectly to the correct signature Ljava/lang/invoke/MethodHandle; which is stored in item #6 in this class file.


text:
Q: Python, Deep learning, gradient descent method example I am studying gradient descent method with Deep learning from scratch. In the book example, there are some code that is hard to understand. this is the code.
def gradient_descent(f, init_x, lr = 0.01, step_num = 100):
    x = init_x
    x_hist = []
    for i in range(step_num):
        x_hist.append(x) # plot with x_hist
        grad = numerical_gradient(f, x)
        x -= lr * grad
    return x, x_hist

def function_2(x):
    return x[0]**2 + x[1]**2

init_x = np.array([-3.0, 4.0])
x, x_hist = gradient_descent(function_2, init_x, lr = 0.1, step_num = 100)

I'm try to plot x_hist to see the decrease of 'x'. But when I print x_hist, it comes like this.
x_hist
[array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10])]

I can fix this problem if i change x_hist.append(x) to x_hist.append(x.copy()).
Unfortunately, I don't know why this is different. Can anyone tell me the different between those?(Sorry for the English)

A: Your list x_hist contains a reference to x, not the value. So correcting it by x_hist.append(x.copy()) is a good way.


text:
Q: What property does gnome use to group application windows? I want to run two instances of a terminal emulator (urxvt) and have them appear as separate applications. I have two .desktop files and thus two entries in the launcher but when I launch the second one it gets grouped with the first.
I've tried changing the Name, GenericName, StartupWMClass, copying the executable, and passing the -name option to urxvt. None of those works.
I am not asking about switching between the instances with Alt-Tab.


text:
Q: How to display the article content in a popup onclick button I work on a wordpress project  I want to display my articles otherwise I make a list that contains the titles of the existing articles with a button " display more detail" in fact when the user clicks on this button it was necessary that a pop up is displayed with the content of the whole article and not bring him to another page which contains the details of the article.
URL:\wcontent\themes\bizspeak\mdf_templates\any\my_cars_3\index.php
Problem if I click on button: "more details" always the popup only displays the contents of first article
the is my code

    <?php
       while ($mdf_loop->have_posts()) : $mdf_loop->the_post();
        ?>

            <?php
            if (has_post_thumbnail($post->ID))
            {
                echo 'ID) . '" title="' .
    esc_attr($post->post_title) . '">';
                echo 'ID, '500x300') . '" alt=""
      />';
                echo '';
            }
            ?>

<?php the_title() ?>

                    <?php echo do_shortcode('[inpost_fancy thumb_width="50"
  thumb_height="50" post_id="' . $post->ID . '" thumb_margin_left="5"
  thumb_margin_bottom="5" thumb_border_radius="200" thumb_shadow="0 1px 4px
  rgba(0, 0, 0, 0.2)" id="" random="0" group="0" border=""
  show_in_popup="0" album_cover="" album_cover_width="200"
  album_cover_height="200" popup_width="800" popup_max_height="600"
  popup_title="Gallery" type="fancy" sc_id="sc1413390928195"]') ?>

                <?php echo do_shortcode('[mdf_post_features_panel]'); ?>

   Plus de détails

      <button type="button" class="close" data-dismiss="modal">×
    </button>

      <?php the_title() ?>

       <?php the_content(); ?>

     <?php echo do_shortcode('[contact-form-7 id="1461" title="pop"]'); ?>

      <button type="button" class="btn btn-default" data-
     dismiss="modal">Close</button>

       <?php endwhile; // end of the loop.     ?>

there an image for more explanation

A: Several "modal windows" (divs) with same IDs
Try change:
<a class="btn button btn-default " target="_blank"  id="btnPlusDetails" data-toggle="modal" data-target="#myModal_<?php echo $post->ID; ?>">Plus de détails

And:
<div class="modal fade" id="myModal_<?php echo $post->ID; ?>" role="dialog">


text:
Q: How to use Q.all() with complex array of promises? Consider I have an array of objects and promises, something like:
[{
    a: 1
}, {
    a: 4
}, {
    a: 4
}, {
    promiseSend: [Function],
    valueOf: [Function]
}, {
    promiseSend: [Function],
    valueOf: [Function]
}]

Now when call I Q.all(arr) and return the object value in then(), nothing's happen and still my array contains promise objects. Is there any way to work with the Q.all() and such a complex arrays?

A: That's how Q is supposed to work.
To get all the values, not the promises, you may use .spread():
Q.all([a, b]).spread(function (a, b) {
    return a + b;
});

Each argument of the spread() callback will be the result of each promise, in its order.
If you think you'll have lots of promises in such array, loop thru the argument provided in then() and replace the promises with its value:
Q.all(promises).then(function(result) {
    for (var i = 0, len = result.length; i < len; i++) {
        if (Q.isPromise(result[i])) {
            result[i] = result[i].valueOf();
        }
    }

    // Next step!
});


text:
Q: ng-repeat: How to detect when a value in a column *changes* (aka column break) Given a list of items displayed with ng-repeat I want to display extra stuff whenever a value in a column changes, eg:
var myApp = angular.module('myApp', []);

function MyCtrl($scope) {

    $scope.cards = [
        {suit: 'Hearts',   value: 7},
        {suit: 'Clubs',    value: 7},
        {suit: 'Spades',   value: 7},
        {suit: 'Diamonds', value: 7},
        {suit: 'Hearts',   value: 8},
        {suit: 'Clubs',    value: 8},
        {suit: 'Spades',   value: 8},
        {suit: 'Diamonds', value: 8},
        {suit: 'Hearts',   value: 9},
        {suit: 'Clubs',    value: 9},
        {suit: 'Spades',   value: 9},
        {suit: 'Diamonds', value: 9} ];

    $scope.myValueFunction = function(card) {
        return [card.suit, card.value];
    };
}

I need the following result:
The Clubs
7
8
9
The Diamonds
7
8
9
The Hearts
7
8
9
The Spades
7
8
9

I would prefer to have a HTML something like that:

The {{card.suit}}

{{card.value}}

Of course, the real problem contains many columns (not just two), several break columns (eg: break-on-column="col1,col2,col3"), the break columns are not fixed (ie. the are chosen by the user at runtime).

A: I would preprocess the array the way that it displays the data the what you need. I don't think that the ng-repeat directive is capable of such things.
Another idea could be to write a custom function for displaying information like so:
HTML

        <data-displaying></data-displaying>

Directive
.directive('dataDisplaying', function() {
    return {
        templateUrl: 'partials/dataTemplate.html',
        link: function(scope, element, attrs) {
            // Data transformation goes in here
        }
    }
})

Then you can process the data within the directive and only output a suit (or anything else) when the setting is right. E.g. store the suit temporary and just output it when the suit differs.

A: I would use ng-hide like this
function MyCtrl($scope) {

  //...

  $scope.breakProperties = [ 'suit' ];

  $scope.breakOn = function(property, index, cards, breakProperties) {
    var previousIndex = index - 1;
    var propertyPresent = false;
    if (previousIndex >= 0) {
      var card = cards[index];
      var previousCard = cards[previousIndex];
      for ( var i = 0; i < breakProperties.length; i += 1) {
        if (breakProperties[i] === property) {
          propertyPresent = true;
        }
      }
      //if the property is not on the list always show regardless of value
      if (!propertyPresent) {
        return false;
      }

      //if the property is different
      if (previousCard[property] !== card[property]) {
        return false;
      }
    }
    //if it's the first always show
    else {
      return false;
    }
    return true;
  };
}

The template

  <button ng-click="breakProperties = [ 'suit' ]">Break on suit</button>
  <button ng-click="breakProperties = [ 'points' ]">Break on points</button>
  <button ng-click="breakProperties = [ 'suit', 'points' ]">Break on
    suit and points</button>

{{breakProperties}}

Suit
      {{card.suit}}

Value {{card.value}}

Points
      {{card.points}}


text:
Q: R: backwards principal component calculation I would like to perform a backwards principal component calculation in R, meaning: obtaining the original matrix by the PCA object itself.
This is an example case:
# Load an expression matrix
load(url("http://www.giorgilab.org/allexp_rsn.rda"))
# Calculate PCA
pca <- prcomp(t(allexp_rsn))

In order to obtain the original matrix, one should multiply the rotations by the PCA themselves, as such:
test<-pca$rotation%*%pca$x

However, as you may check, the calculated "test" matrix is completely different from the original "allexp_rsn" matrix. What am I doing wrong? Is the function prcomp adding something else to the svs procedure?
Thanks :-)

A: Using USArrests:
pca <- prcomp(t(USArrests))
out <- t(pca$x%*%t(pca$rotation))
out <- sweep(out, 1, pca$center, '+')
apply(USArrests - out, 2, sum)
   Murder       Assault      UrbanPop          Rape
1.070921e-12 -2.778222e-12  3.801404e-13  1.428191e-12

A: Remember that a prerequisite to perform PC analysis is to scale and center the data. I believe that prcomp procedure does that, so pca$x returns scaled original data (with mean 0 and std. equal to 1).

A: Here is a solution using the eigen function, applied to a B/W image matrix to illustrate the point. The function uses increasing numbers of PCs, but you can use all of them, or only some of them
library(gplots)
library(png)
# Download an image:
download.file("http://www.giorgilab.org/pictures/monalisa.tar.gz",destfile="monalisa.tar.gz",cacheOK = FALSE)
untar("monalisa.tar.gz")
# Read image:
img <- readPNG("monalisa.png")
# Dimension
d<-1
# Rotate it:
rotate <- function(x) t(apply(x, 2, rev))
centermat<-rotate(img[,,d])
# Plot it
image(centermat,col=gray(c(0:100)/100))
# Increasing PCA
png("increasingPCA.png",width=2000,height=2000,pointsize=20)
par(mfrow=c(5,5),mar=c(0,0,0,0))
for(end in (1:25)*12){
    for(d in 1){
        centermat<-rotate(img[,,d])
        eig <- eigen(cov(centermat))
        n <- 1:end
        eigmat<-t(eig$vectors[,n] %*% (t(eig$vectors[,n]) %*% t(centermat)))
        image(eigmat,col=gray(c(0:100)/100))
    }
}
dev.off()


text:
Q: RuntimeError:doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS I'm getting this error while i am using my own AUTHENTICATION_BACKENDS
Model class tainfo.apps.users.models.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

my own backend:
    from django.contrib.auth.backends import ModelBackend
    import re
    from tainfo.apps.users.models import User

    def get_user_by_account(account):
        try:
            if re.match(r'1[3-9]\d{9}',account):
                user = User.objects.get(mobile=account)
            else:
                user = User.objects.get(username=account)
            return user
        except User.DoesNotExist:
            return None

    class UsernameMobileAuthBackend(ModelBackend):
        def authenticate(self,request,username=None,password=None,**kwargs):
            user = get_user_by_account(username)
            if user and user.check_password(password) and user.is_active:
                return user

I put this in my devsettings.py:
AUTHENTICATION_BACKENDS = ['users.utils.UsernameMobileAuthBackend',]

if i delete this from settings,then this error will gone,but i that case i won't be able to use my own auth backends.
any idea what i have done wrong?
thanks
updates:
my user model
from django.contrib.auth.models import AbstractUser
from django.db import models

# Create your models here.

class User(AbstractUser):
    mobile = models.CharField(max_length=11, unique=True, verbose_name='mobile',blank=True)
    email_active = models.BooleanField(default=False, verbose_name='emailisactive')

    class Meta:
        db_table = 'tb_users'
        verbose_name = 'user'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username

devsettings:
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'users.apps.UsersConfig',
    'contents.apps.ContentsConfig',
    'verifications.apps.VerificationsConfig',
]
AUTH_USER_MODEL = 'users.User'
AUTHENTICATION_BACKENDS = ['users.utils.UsernameMobileAuthBackend',]

dirs.png
resolved:
from django.contrib.auth.backends import ModelBackend
import re

from tainfo.apps.users.models import User

turns out it was the path that i used in utils..
apps's path is in my sys.path ,and i should use 'from users.models import User',like this :
from django.contrib.auth.backends import ModelBackend
import re

from users.models import User

Thanks everyone


text:
Q: Android status bar show in Unty I'm triyng to show the status bar in an Android phone using Unity. I have try this code:
  void Start()   {

     this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

     }

But an error appear;
Assets/Scenes/Control/control.cs(15,34): error CS0103: The name 'WindowManager' does not exist in the current context

Does I need to call or import another package? Some could help me with this detail. Thanks in advance.

A: You cannot use Android Java functions directly in Unity. You can only use whats available in Unity C Sharp. Unity doesn't understand the method. Suggested workaround, use a 'Slider' UI element and manipulate it in a custom c sharp script. Complicated workaround create a custom Unity Plugin which calls the native Android method (possible but complex).