text:
Q: FactoryGirl creating multiple records I'm trying to get in the habit of writing specs, however, this is becoming increasingly frustrating.
Assume I have two simple models: User and Story. Each model uses a belongs_to relation. Each model uses a validates :foo_id, presence: true as well.
However, FactoryGirl is creating multiple records.
FactoryGirl.define do
  factory :user do
    email "foo@bar.com"
    password "foobarfoobar"
  end # this creates user_id: 1

  factory :story do
    title "this is the title"
    body "this is the body"
    user # this creates user_id: 2
  end
end

This simple test fails:
require 'rails_helper'

describe Story do

  let(:user) { FactoryGirl.create(:user) }
  let(:story) { FactoryGirl.create(:story) }

  it 'should belong to User' do
    story.user = user
    expect(story.user).to eq(user)
  end
end

What am I missing here? I cannot build a Story factory without a User, yet I need it to be just one User record.

A: The values you define for each attribute in a factory are only used if you don't specify a value in your create or build call.
user = FactoryGirl.create(:user)
story = FactoryGirl.create(:story, user: user)

A: Yes, it is a feature of factory girl to create the associated user when you create the story.
You can avoid it like this:
require 'rails_helper'

describe Story do
  let(:story) { FactoryGirl.create(:story) }
  let(:user) { story.user }

  it 'should belong to User' do
    story.user.should eq user
  end
end

This example is setup to be trivially true, but you get the point.

A: When doing something like this you can do:
let(:story) { FactoryGirl.create(:story, user: user) }

Or maybe you can only let the story variable and do:
let(:story) { FactoryGirl.create(:story, user: user) }
let(:user)  { User.last}


text:
Q: InvalidOperationException When Appending Text To RichTextBox Im trying to append text to richtextbox when there is a progress changed in BackgroundWorker thread.
DoWork event
while (true)
{
    try
    {
        byte[] buff = new byte[1000];
        client.Client.Receive(buff);
        string s = Encoding.ASCII.GetString(buff);
        background.ReportProgress(0, s);
    }
    catch { }
}

ProgressChanged Event
try
{
    richTextBox1.AppendText(e.UserState as string);
}
catch { }

i dont understand what is the problem... it worked fine and suddenly its not.

redpajama_set_name: RedPajamaStackExchange


text:
Q: cant generate random number in omnetpp I have define host traffic send interval in this way in my NED file and I expect to receive different number in every execution:
    volatile double sendInterval @unit("s") = default(exponential(1s));

but it gives me same result in every execution, where is the problem?

A: There isn't any problem here. This is a feature. Any random number in OMNeT++ is actually a pseudo-random number.
And they really need to be deterministic, so every experiment can be exactly reproduced.
See the manual section: https://omnetpp.org/doc/omnetpp/manual/#sec:sim-lib:random-number-generators
Where it says:

Starting from the same seed, RNGs always produce the same sequence of random numbers. This is a useful property and of great importance, because it makes simulation runs repeatable.

To get different values, try setting a different seed-set for your configuration in the .ini file, or running multiple repetitions by adjusting the repeat option - each repetition automatically sets a different seed for the PRNGs.
Also see: https://omnetpp.org/doc/omnetpp/manual/#sec:config-sim:repeating-runs-with-different-seeds


text:
Q: Using glob on logstash server machine? We have a separate server for logstash and logs are on a remote machine.
We ship these same logs from a remote machine to logstash server using lumberjack's plugin for logstash.
I tried this:
Client config (where logs are present):
input {
        file{
                path => "/home/Desktop/Logstash-Input/**/*_log"
        }
}

output {

        lumberjack {
                hosts => ["xx.xx.xx.xx"]
                port => 4545
                ssl_certificate => "./logstash.pub"
    }

I want to extract fields from my file input's path variable, so that accordingly for different fields values different parsing patterns can be applied.
Eg: Something like this
grok {
    match => ["path", "/home/Desktop/Logstash-Input/(?<server>[^/]+)/(?<logtype>[^/]+)/(?<logdate>[\d]+.[\d]+.[\d]+)/(?<logfilename>.*)_log"]
}

Here server, logtype are directories names which i want in my fields to apply different parsing patterns like:
filter{

   if [server] == "Server2" and [logtype] == "CronLog" {
               grok........
}

if [server] == "Server3" and [logtype] == "CronLog" {
               grok............
}
}

How shall I be able apply the above on my logstash-server config, as file input is on the client machine from which I want to extract fields from path ???
Lumberjack succesfully ships logs to server.
I tried applying the grok on client:
grok {
    match => ["path", "/home/Desktop/Logstash-Input/(?<server>[^/]+)/(?<logtype>[^/]+)/(?<logdate>[\d]+.[\d]+.[\d]+)/(?<logfilename>.*)_log"]
}

I checked on client console it adds fields like server, logtype to the logs but on logstsh-server console the fields are not added.
How should I be able to achieve the above????

A: Two options:

*

*Set the fields when they are originally shipped.  The full logstash and logstash-forwarder (aka lumberjack) allow you to do this.

*grok the information from the file path, which my documents have in a field called "file".  Check your documents to find the actual field name.


text:
Q: How to handle 2d collisions in a script that isn't attached to Game Object Generally, from what I've learnt, collisions are handled in the script that is attached to a Game Object. In my game, I have 6 game objects that collide with each other making the former idea difficult to implement. I want to make all the game objects prefabs and instantiate them in another script attached to an empty game object. How can I handle collisions between all these 6 game objects in the new script?

A: I'm wondering the same thing as Joe Blow, but still if what you want to try to do is handle collisions manually (which by the way will make Physics harder since you would have to calculate bounciness, gravity, etc... manually) then you can try this:
public class OtherScript : MonoBehavior
{
    public GameObject[] objects; //Your 6 GameObject

    void Update()
    {
        for (int i=0; i<objects.Length; i++)
        {
            for (int j=0; j<objects.Length; i++)
            {
                if (objects[i].GetComponent<Renderer>().bounds.Intersects(
                           objects[j].GetComponent<Renderer>().bounds))
                {
                    //Handle collision
                    break;
                }
            }
        }
    }
}

If this doesn't work then you should also try with GetComponent<MeshFilter>().mesh.bounds. Note that if your game is 2D you should use GetComponent<SpriteRenderer>().mesh.bounds instead.


text:
Q: add last function using deque with data classes Hi I'm trying to solve this code but not really making any headway. I'm supposed to fix a code by adding code to the class, but I haven't worked with deque before and can't really grasp how to do it.
the main.py looks like this
import Deque as deq

empty = deq.Deque()
deque = deq.Deque()

for i in range(1, 11):
    deque.add_last(i)
print(deque.to_string())
print("Size:", deque.size)

and this is the class
@dataclass
class Node:
value: int = None
nxt: Any = None

  @dataclass
  class Deque:
  head: Node = None      # First node in queue
  tail: Node = None      # Last node in queue
  size: int = 0

  # Add element n as last entry in deque
  def add_last(self, n):

and the output is supposed to look like this
{ 1 2 3 4 5 6 7 8 9 10 }
Size: 10

but the thing is that I don't really know how to use deque, so I would really appreciate the help with helping me solve the add_last function.

A: # Add element n as last entry in deque
def add_last(self, n):
    # Case where the deque is empty.
    if self.head == None and self.tail == None:
        self.head = Node(n, None)
        self.tail = self.head
    else:
        # Case where the deque is not empty.
        self.tail.nxt = Node(n, None)
        self.tail = self.tail.nxt

    self.size += 1

For more info I would research linked lists and also refer to the python dataclass documentation https://docs.python.org/3/library/dataclasses.html


text:
Q: how to pass php array data from one page to another i am getting json data and i convert into php array and echo inside the table now i want to pass the selected row data to another page when i select the row it is not taking that value itis taking the last row data how can i solve it .
thanks in advance.

  <?php
 require 'gettoken1.php';
session_start();
?>

<?php

if (isset($_POST['submit']))
 {

            {
$baseurl = 'http://host/api/v1/doctorAvailability';
$rawPOSTdata = array
                (
                    "type" => "private",
                    "hosID" => $_POST['hosMaptxt'],
                    "specID" => $_POST['specialityMaptxt'],
                     "date" => $_POST['date'],
                    "name" => '%'.$_POST['docname'].'%'
                );

$curl = curl_init($baseurl);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json',"Authorization: Bearer $atoken"));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($rawPOSTdata));
$response = curl_exec($curl);
curl_close($curl);

 if( $response )
     {
        if ( isset($result->error) )die( $result->error_message );

        $arr=json_decode( $response, true );

    ?>

        <form method ="post" action="sessiondetails.php" >

 Avilable Doctors

             Doctor
            Specialition
             Hospital
             Town
             Date
             Day
             Booking

<?php
foreach($arr['data']['resultMap'] as $key )

 {

        $_SESSION ['HosCode']=$key['HosCode'] ;
        $_SESSION ['SpecializationId']=$key['SpecializationId'] ;
        $_SESSION ['DoctorNo']=$key['DoctorNo'] ;
        $_SESSION ['AppDay']=$key['AppDay'] ;
        $_SESSION ['AppDate']=$key['AppDate'] ;
        $_SESSION ['DocName']=$key['DocName'] ;
        $_SESSION ['SpecName']=$key['SpecName'] ;
        $_SESSION ['HosName']=$key['HosName'] ;

?>

        <input type="text" readonly="" name ="DoctorNo[]" value="<?php echo $key['DocName']?>"  />
        <input type="text" readonly="" name ="SpecializationId[]"  value="<?php echo $key['SpecName']?> "/>
        <input type="text" readonly="" name ="HosCode[]" value="<?php echo $key['HosName']?>" />
        <input type="text" readonly="" name ="HosTown[]"  style="width:110px "value="<?php echo $key['HosTown']?>"/>
        <input type="text"  readonly="" name ="AppDate[]"  style="width:80px "  value="<?php echo $key['AppDate']?>" />
        <input type="text"  readonly="" name ="AppDay[]"  style="width:80px " value="<?php echo $key['AppDay']?>" />
         <input type="submit" value="click" name="submit">

 <?php

 }

 }

 }}
?>

    </form>

here is the codding

    <link href='style1.css' rel='stylesheet' type='text/css'>
<?php

 session_start();
        $A=$SpecializationId=$_SESSION ['SpecializationId'] ;
        $b=$DoctorNo=   $_SESSION ['DoctorNo'] ;
        $c= $_SESSION ['AppDay'];
        $d= $_SESSION ['AppDate'] ;
        $e=$_SESSION ['HosCode'];
        //$hospital=$_SESSION ['HosName'];
        //$specialization=$_SESSION ['SpecName'];
        //$doctor=$_SESSION ['DocName'];
    $baseurl = 'http://host/api/v1/doctorSessions';
    $rawPOSTdata = array
                (

                    "hosID" =>$e,
                    "specID" => $A,
                    "docNo" =>$b,
                    "day" => $c,
                    "date" =>  $d,
                );

$curl = curl_init($baseurl);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json',"Authorization: Bearer $atoken"));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($rawPOSTdata));
$response = curl_exec($curl);
curl_close($curl);

 if( $response )
     {
        if ( isset($result->error) )die( $result->error_message );

        $arr=json_decode( $response,true);
        ?>

    <form method ="post" action =" patientdetails.php">

 Doctor Details

             Doctor
            	  <?php echo  $_SESSION ['DocName']?>

            Specialition
             <?php echo $_SESSION ['SpecName'];?>

            Hospital
              <?php echo    $_SESSION ['HosName'];?>

             Day
             Date
            Status
             Time
             Amount
             Click

            <?php
foreach($arr['data']['result'] as $key )

    {

        $_SESSION ['Hosid']=$key['Hosid'] ;
        $_SESSION ['Remark']=$key['Remark'] ;
        $_SESSION ['Docno']=$key['Docno'] ;
        $_SESSION ['Sday']=$key['Sday'] ;
        $_SESSION ['ShowDate']=$key['ShowDate'] ;
        $_SESSION ['Ttime']=$key['Ttime'] ;
        $_SESSION ['amount']=$key['amount'] ;

?>

    <input type="text" readonly="" name ="DoctorNo"value="<?php echo $key['Sday'] ?>" />
    <input type="text" readonly="" name ="HosCode" value="<?php echo $key['ShowDate']?>" />
    <input type="text" readonly="" name ="HosCode" value="<?php echo $key['Remark']?>" />
    <input type="text" readonly="" name ="HosTown"  style="width:110px "value="<?php echo $key['Ttime'] ;?>"/>
    <input type="text" readonly="" name ="HosTown"  style="width:110px "value="<?php echo" RS.". $key['amount'];?>"/>
      <input type="submit" value="Confirm" name ="confirm">

 <?php

 }

    }

?>

</form>

A:
The Usage of session_start(); in both Scripts seem a little out of Place. REASON: When you want to use Sessions in your Code, you have to make sure that no White-Space or any other Characters are OUTPUT before starting the SESSION. In other words, Starting the Session should be the 1st Line of Code in your Script. Here's how:

YOUR 1ST SCRIPT COULD HAVE STARTED OUT BETTER LIKE SO:
<?php    // NOTICE THAT THERE IS NO SPACE OR CHARACTER BEFORE <?php
         // NOTICE ALSO THAT STARTING THE SESSION IS THE FIRST LINE AFTER <?php
    session_start();              // <= STEP 1: START SESSION
    require 'gettoken1.php';      // <= STEP 2: IMPORT DEPENDENCIES
?>

YOUR 2ND SCRIPT COULD HAVE BEEN BETTER LIKE SO:
<?php   // NOTICE THAT THERE IS NO SPACE OR CHARACTER BEFORE <?php
        // NOTICE ALSO THAT STARTING THE SESSION IS THE FIRST LINE AFTER <?php
        session_start();    // <= STEP 1: START SESSION
                            // <= STEP 2: CONTINUE WITH THE REST OF THE CODE
        $A       =  $SpecializationId   =   $_SESSION ['SpecializationId'] ;
        $b       =  $DoctorNo           =   $_SESSION ['DoctorNo'] ;
        $c       =  $_SESSION ['AppDay'];
        $d       =  $_SESSION ['AppDate'] ;
        $e       =  $_SESSION ['HosCode'];
        $baseurl = 'http://host/api/v1/doctorSessions';

        //$hospital=$_SESSION ['HosName'];
        //$specialization=$_SESSION ['SpecName'];
        //$doctor=$_SESSION ['DocName'];

        $rawPOSTdata = array(
            "hosID"    => $e,
            "specID"   => $A,
            "docNo"    => $b,
            "day"      => $c,
            "date"     => $d,
        );

        $curl       = curl_init($baseurl);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json',"Authorization: Bearer $atoken"));
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($rawPOSTdata));
        $response = curl_exec($curl);
        curl_close($curl);

        if($response){
            if ( isset($result->error) ){die($result->error_message);}
            $arr  =  json_decode( $response,true);

    ?>

    <link href='style1.css' rel='stylesheet' type='text/css'>

    <form method ="post" action =" patientdetails.php">

 Doctor Details

                 Doctor
                	  <?php echo  $_SESSION ['DocName']?>

                Specialition
                 <?php echo $_SESSION ['SpecName'];?>

                Hospital
                  <?php echo    $_SESSION ['HosName'];?>

                 Day
                 Date
                Status
                 Time
                 Amount
                 Click

            <?php
                foreach($arr['data']['result'] as $key){
                    $_SESSION ['Hosid']    = $key['Hosid'] ;
                    $_SESSION ['Remark']   = $key['Remark'] ;
                    $_SESSION ['Docno']    = $key['Docno'] ;
                    $_SESSION ['Sday']     = $key['Sday'] ;
                    $_SESSION ['ShowDate'] = $key['ShowDate'] ;
                    $_SESSION ['Ttime']    = $key['Ttime'] ;
                    $_SESSION ['amount']   = $key['amount'] ;

            ?>

                <input type="text" readonly="" name ="DoctorNo"value="<?php echo $key['Sday'] ?>" />
                <input type="text" readonly="" name ="HosCode" value="<?php echo $key['ShowDate']?>" />
                <input type="text" readonly="" name ="HosCode" value="<?php echo $key['Remark']?>" />
                <input type="text" readonly="" name ="HosTown"  style="width:110px "value="<?php echo $key['Ttime'] ;?>"/>
                <input type="text" readonly="" name ="HosTown"  style="width:110px "value="<?php echo" RS.". $key['amount'];?>"/>
                  <input type="submit" value="Confirm" name ="confirm">

               <?php
            }
        }

            ?>

    </form>


text:
Q: Perl regex that matches the first substring specified I need to extract data from an HTML document and compose an XML document with only interesting information. The way I'm doing this is by transforming the HTML doc into an XML doc, step by step. I have the 5 outermost XML tags in one line each, now I'm trying to structure what's inside of those.
I have a line that's structured this way :
   <myTag>
      blablabla  title I want  some other stuff  text I don't want  blablabla
   </myTag>

What I want is :
    <myTag>
    <link>link/I/want</link>
    <title> title I want </title>
    </myTag>

The regex I have is :
    /a href="(.*)"(.*)>(.*)<\/a>/

hoping to get  #$1 = url , $2 = whatever , $3 = title.
This isn't working because it's taking this instead:
    <myTag>
    <link>link/I/want *some css* > title I want  some other stuff <a href="link that/I/don't/want" *some css*</link>
    <titl>text I don't want</title>
    </myTag>

How do I extract the content of the FIRST anchor tag of the line ?
Thanks !

A: Just use non-greedy expressions:
/a href="(.*?)"(.*?)>(.*?)<\/a>/

Note ? after each *.


text:
Q: How Can I Sort A 'Version Number' Column Generically Using a SQL Server Query I wonder if the SQL geniuses amongst us could lend me a helping hand.
I have a column VersionNo in a table Versions that contains 'version number' values like
VersionNo
---------
1.2.3.1
1.10.3.1
1.4.7.2

etc.
I am looking to sort this, but unfortunately, when I do a standard order by, it is treated as a string, so the order comes out as
VersionNo
---------
1.10.3.1
1.2.3.1
1.4.7.2

Intead of the following, which is what I am after:
VersionNo
---------
1.2.3.1
1.4.7.2
1.10.3.1

So, what I need to do is to sort by the numbers in reverse order (e.g. in a.b.c.d, I need to sort by d,c,b,a to get the correct sort ourder).
But I am stuck as to how to achieve this in a GENERIC way. Sure, I can split the string up using the various sql functions (e.g. left, right, substring, len, charindex), but I can't guarantee that there will always be 4 parts to the version number. I may have a list like this:
VersionNo
---------
1.2.3.1
1.3
1.4.7.2
1.7.1
1.10.3.1
1.16.8.0.1

Can, does anyone have any suggestions? Your help would be much appreciated.

A: Depending on SQL engine for MySQL would be sth like this:
SELECT versionNo FROM Versions
ORDER BY
SUBSTRING_INDEX(versionNo, '.', 1) + 0,
SUBSTRING_INDEX(SUBSTRING_INDEX(versionNo, '.', -3), '.', 1) + 0,
SUBSTRING_INDEX(SUBSTRING_INDEX(versionNo, '.', -2), '.', 1) + 0,
SUBSTRING_INDEX(versionNo, '.', -1) + 0;
For MySQL version 3.23.15 an above

SELECT versionNo FROM Versions ORDER BY INET_ATON(ip);

A: If You are using SQL Server 2008
select VersionNo from Versions order by cast('/' + replace(VersionNo , '.', '/') + '/' as hierarchyid);

What is hierarchyid
Edit:
Solutions for 2000, 2005, 2008: Solutions to T-SQL Sorting Challenge here.
The challenge

A: Another way to do it:
Assuming you only have a,b,c,d only you may as well separate the data out to columns and do an order by a,b,c,d(all desc) and get the top 1 row
If you need to scale to more than d to say e,f,g... just change 1,2,3,4, to 1,2,3,4,5,6,7 and so on in the query
Query :
see demo
create table t (versionnumber varchar(255))
insert into t values
('1.0.0.505')
,('1.0.0.506')
,('1.0.0.507')
,('1.0.0.508')
,('1.0.0.509')
,('1.0.1.2')

; with cte as
(
    select
    column1=row_number() over (order by (select NULL)) ,
    column2=versionnumber
    from t
    )

select top 1
    CONCAT([1],'.',[2],'.',[3],'.',[4])
from
(
    select
        t.column1,
        split_values=SUBSTRING( t.column2, t1.N, ISNULL(NULLIF(CHARINDEX('.',t.column2,t1.N),0)-t1.N,8000)),
        r= row_number() over( partition by column1 order by t1.N)
    from cte t
        join
        (
            select
                t.column2,
                1 as N
            from cte t
                UNION ALL
            select
                t.column2,
                t1.N + 1 as N
            from cte t
                join
                (
                 select
                    top 8000
                        row_number() over(order by (select NULL)) as N
                 from
                    sys.objects s1
                        cross join
                   sys.objects s2
                ) t1
            on SUBSTRING(t.column2,t1.N,1) = '.'
         ) t1
          on t1.column2=t.column2
)a
pivot
(
    max(split_values) for r in ([1],[2],[3],[4])
   )p
  order by [1] desc,[2] desc,[3] desc,[4] desc

A: If you can, alter the schema so that the version has 4 columns instead of one. Then sorting is easy.


text:
Q: Prove that matrix A so that $a_{ij}$ = (m+1)*(i+j) mod n is a symmetric Latin Square with different elements on its diagonal (m is a freely chosen Z) It's obvious that it's symmetric because $a_{\left(i+1\right)j}=\left(m+1\right)\left(i+1+j\right) = a_{i\left(j+1\right)}=\left(m+1\right)\left(i+j+1\right)$, but how can I prove that it's a Latin square and that it's diagonal consists of different elements?
I thought about showing that the sum of the elements in any row/column is equal to 0+1+...+n-1, but it's not working out
$\left(m+1\right)\left[\left(i+j\right)+\left(i+j+1\right)+...+\left(i+j+n-1\right)\right] mod(n)$
$\left(m+1\right)\left[n\left(i+j\right)+\left(1\right)+...+\left(n-1\right)\right] mod(n)$
$\left(m+1\right)\left[n\left(i+j\right)+\frac{n\left(n-1\right)}{2}\right] mod(n)$
$\left(m+1\right) \left[0\right]mod(n)$
Which will get me 0 or k*n where k is an integer, so we only know that if summing up any row/column (I get the same for other rows also)

A: It's true if and only if $m+1$ and $n$ are coprime.  In particular, the cells $(i,j)$ and $(i,j+n/\gcd(m+1,n))$ are in the same row and contain the same symbol.  However, they are the same cell if and only if $m+1$ and $n$ are coprime, i.e., provided $\gcd(m+1,n)=1$).
As you say, it's obvious that it's symmetric, since $a_{ij} = a_{ji}$ by commutativity of + (i.e., we know $i+j = j+i$).  However, checking $a_{(i+1)j} = a_{i(j+1)}$ does not show it's symmetric (it shows some other property, not symmetry).  We need only show the rows are Latin, i.e., there are no repeated symbols in any row (the columns are the same but transposed, so we don't need to re-check them).  I don't think summing the rows is going to lead to a proof: it won't show there are no duplicate symbols in each row.
To prove the rows are Latin, suppose $a_{ij} = a_{ij'}$ for columns $j$ and $j'$.  Then we deduce from the definition of $a_{ij}$ and $a_{ij'}$ that $$j(m+1) \equiv j'(m+1) \pmod n.$$
If $m+1$ and $n$ are coprime, then we can "cancel out" the $m+1$ (or more formally, multiply by the multiplicative inverse of $m+1$ on both sides) to obtain
$j \equiv j' \pmod n$ which implies $a_{ij}$ and $a_{ij'}$ refer to the same cell, and thus there are no duplicate symbols in the arbitrary row $i$.

A: $(m+1)$ is any number $\in$ Z. I think , there is relation between $m$ and $n$ to get the require . Also, you mean the operation * is usual multiplication.


text:
Q: How to Create PostgreSQL Leading Zero Sequence (zerofill) How can I create a leading zero sequence in PostgreSQL?
For MySQL I know it is BIGINT(10) UNSIGNED ZEROFILL AUTO_INCREMENT but in PostgreSQL I can't find an equivalent (only bigserial).
Moreover how can I limit the number of zeroes as BIGINT(10) means 10 symbols, does the type bigserial have such a limit?

A: Create a regular sequence, then use to_char() to pad it with leading zeroes. Your data type will be char(), though, Postgres does not support zerofill for integral types.

A: A good alternative to to_char() in a "fill leading zeros" task is lpad():
create table TableName(columnName serial primary key);

select lpad(columnName::text, 3, '0'), * from TableName;

Caution: lpad() does not generate an error on overflow, see for example:
select lpad(4444::text, 3, '0'), to_char(4444, '000')


text:
Q: ReSharper not running NUnit tests correctly I'm having some issues with ReSharper and NUnit test running. I have some tests that, for debug purposes, I have changed to only contain Assert.True(true);. There are multiple Test Fixtures on the class with different parameter values. When I try and run the tests, however, only a few of them run. If I name them all something simple like "A", "B", "C", etc, they all run. I have compiled an album of screenshots on Imgur to document the issue: http://imgur.com/a/3BnpB
As you can see on the Warnings page in the last screenshot, it doesn't even pull the full name of the test correctly. They get chopped off at various lengths. I can't  find anything about that error message ("was left pending after its completion") on Google either.
What's going on?


text:
Q: JSON Parsing Sub Items VB.net using Newtonsoft I've been fighting with this all weekend.  I'm trying to parse/deserialize my JSON using the Newtonsoft tools.
I am able to get to the top level data (EventID and EventName) with no troubles.
I've been scouring the examples and other posts for help getting to the ROOMS array on info.  The rooms and sessions will have 0-many items in the json set.

MY JSON:
{
    "EventID": 123,
    "EventName": "Training Camp",
    "Rooms": [
        {
            "RoomID": 12,
            "RoomName": "Main Ballroom"
        },
        {
            "RoomID": 256,
            "RoomName": "East Hall"
        }
    ],
    "Sessions": [
        {
            "SessName": "Session One",
            "ScheduleID": 1682,
        },
        {
            "SessName": "Session Two",
            "ScheduleID": 1683,
        }
    ]
}

My code:
Public Class JSONEvent
    Public EventID As Integer
        Public EventName As String
        Public RoomsArray As List(Of JSONRooms)
End Class

Public Class JSONRooms
    Public Property RoomName As String
    Public Property RoomID As String
End Class

in Form1:
Dim obj = JsonConvert.DeserializeObject(Of JSONEvent)(JsonData)
messagebox.show(obj.eventid)
messagebox.show(obj.eventname)

Dim TheEvent As JSONEvent = JsonConvert.DeserializeObject(Of JSONEvent)(JsonData)
TheEvent.RoomsArray = JsonConvert.DeserializeObject(Of List(Of JSONRooms))(TheEvent.roomname) 'this I can't get right

Can someone please help me to access these data elements?
Any help is greatly appreciated.
Thank you in advance.
Jeff

A:     <Serializable> _
    Public Class Room
        Public Property RoomID() As Integer
            Get
                Return m_RoomID
            End Get
            Set
                m_RoomID = Value
            End Set
        End Property
        Private m_RoomID As Integer
        Public Property RoomName() As String
            Get
                Return m_RoomName
            End Get
            Set
                m_RoomName = Value
            End Set
        End Property
        Private m_RoomName As String
    End Class
    <Serializable> _
    Public Class Session
        Public Property SessName() As String
            Get
                Return m_SessName
            End Get
            Set
                m_SessName = Value
            End Set
        End Property
        Private m_SessName As String
        Public Property ScheduleID() As Integer
            Get
                Return m_ScheduleID
            End Get
            Set
                m_ScheduleID = Value
            End Set
        End Property
        Private m_ScheduleID As Integer
    End Class
    <Serializable> _
    Public Class JSONEvent
        Public Property EventID() As String
            Get
                Return m_EventID
            End Get
            Set
                m_EventID = Value
            End Set
        End Property
        Private m_EventID As String
        Public Property EventName() As String
            Get
                Return m_EventName
            End Get
            Set
                m_EventName = Value
            End Set
        End Property
        Private m_EventName As String
        Public Property Rooms() As List(Of Room)
            Get
                Return m_Rooms
            End Get
            Set
                m_Rooms = Value
            End Set
        End Property
        Private m_Rooms As List(Of Room)
        Public Property Sessions() As List(Of Session)
            Get
                Return m_Sessions
            End Get
            Set
                m_Sessions = Value
            End Set
        End Property
        Private m_Sessions As List(Of Session)

    End Class

and in c#
[Serializable]
public class Room
{
    public int RoomID { get; set; }
    public string RoomName { get; set; }
}
[Serializable]
public class Session
{
    public string SessName { get; set; }
    public int ScheduleID { get; set; }
}
[Serializable]
public class JSONEvent
{
    public string EventID { get; set; }
    public string EventName { get; set; }
    public List<Room> Rooms { get; set; }
    public List<Session> Sessions { get; set; }

}

    // your code should work except the whole object should be deserialized at once.

        JSONEvent obj = JsonConvert.DeserializeObject<JSONEvent>(JsonData);
        messagebox.show(obj.EventID);
        messagebox.show(obj.EventName);
        // check the array
        if(obj.Rooms != null && obj.Rooms.Count > 0)
        {
            messagebox.show(obj.Rooms[0].RoomID.ToString());
            messagebox.show(obj.Rooms[0].RoomName):
        }


text:
Q: html select option SELECTED I have in my php
$sel = "
    <option> one </option>
    <option> two </option>
    <option> thre </option>
    <option> four </option>
";

let say I have an inline URL = site.php?sel=one
if I didn't saved those options in a variable, I can do it this way to make one of the option be SELECTED where value is equal to $_GET[sel]
<option <?php if($_GET[sel] == 'one') echo"selected"; ?> > one </option>
<option <?php if($_GET[sel] == 'two') echo"selected"; ?> > two </option>
<option <?php if($_GET[sel] == 'three') echo"selected"; ?> > three </option>
<option <?php if($_GET[sel] == 'four') echo"selected"; ?> > four </option>

but the problem is, I need to save those options in a variable because I have a lot of options and I need to call that variable many times.
Is there a way to make that option be selected where value = $_GET[sel] ?

A: This is simple example by using ternary operator to set selected=selected
<?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
<select class="form-control" title="Choose Plan">
<?php foreach ($plan as $key => $value) { ?>
  <option value="<?php echo $key;?>" <?php echo ($key ==  '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
<?php } ?>
</select>

A: foreach($array as $value=>$name)
{
    if($value == $_GET['sel'])
    {
         echo "<option selected='selected' value='".$value."'>".$name."</option>";
    }
    else
    {
         echo "<option value='".$value."'>".$name."</option>";
    }
}

A: Just use the array of options, to see, which option is currently selected.
$options = array( 'one', 'two', 'three' );

$output = '';
for( $i=0; $i<count($options); $i++ ) {
  $output .= '<option '
             . ( $_GET['sel'] == $options[$i] ? 'selected="selected"' : '' ) . '>'
             . $options[$i]
             . '</option>';
}

Sidenote: I would define a value to be some kind of id for each element, else you may run into problems, when two options have the same string representation.

A: You could create a function and then add it to each option field to print the selected="selected".
Example
<option value="PHP" ' . tsw_selected('PHP', $row['anchor']) . '>PHP/PDO/SQL[+]</option>
<option value="HTML" ' . tsw_selected('HTML', $row['anchor']) . '>HTML/CSS</option>

Then your fun:
function tsw_selected( $opt, $val )
{
$sel = '';
$opt = ('' != $opt ) ? $opt : 'OTHER';
if( $opt == $val ) $sel = true;
if ( $sel ) {
    return 'selected="selected"'; } else { return ''; }
}

This will echo the select="selected" per true and echo '' (nothing) for false.
You could set $sel = false, but it does not matter. Booloean checks on empty as false.

A: You're missing quotes for $_GET['sel'] - fixing this might help solving your issue sooner :)

A: foreach ($array as $value => $name) {
     echo '<option value="' . htmlentities($value) . '"' . (($_GET['sel'] === $value) ? ' selected="selected"') . '>' . htmlentities($name) . '</option>';
}

This is fairly neat, and, I think, self-explanatory.


text:
Q: Recursive vs non-recursive sorting algorithms Can someone explain in English how non-recursive and recursive implementations of sorting algorithms differs from each other?

A: How they differ, in what sense? Bear in mind: any recursive algorithm can be implemented as an iterative algorithm, and vice versa (take a look at this post). Iteration or recursion - it's just an implementation detail; although it can have a major impact in performance depending on the choice, the algorithm will be the same nevertheless.

A: Recursive sorting algorithms work by splitting the input into two or more smaller inputs and then sorting those, then combining the results. Merge sort and quick sort are examples of recursive sorting algorithms.
A non-recursive technique is anything that doesn't use recursion. Insertion sort is a simple example of a non-recursive sorting algorithm.

A: A recursive sorting algorithm calls on itself to sort a smaller part of the array, then combining the partially sorted results. Quick-sort is an example.
A non-recursive algorithm does the sorting all at once, without calling itself. Bubble-sort is an example of a non-recursive algorithm.


text:
Q: Table-like list of symbols in Lyx How do I create a list of symbols like this in Lyx? I have tried the usual Nomenclature with entries, but it's way less "tidy". Any suggestions?
The image is taken from this thesis.


text:
Q: java mvc authorization without spring security My task is to use a send request and then to get some XML.
example:
request: /api/ext/data.xml
response: some XML
The application uses Spring MVC, so I just wrote controller method, and everything works OK, but I also need to implement authorization. This app does not use Spring security.
What should I do? Should I use session to save User authorization data?

A: You should still look at Apache Shiro and/or Spring Security. However Spring Security (and container security for that matter) are not so friendly for REST API security. For Spring you will need to implement a custom AuthenticationEntryPoint to avoid the redirect on 403. Shiro might be a little easier for REST API.
If you want to do it yourself w/o dependencies or complexities you should look into writing a Servlet Filter and/or leverage container security. A compromise might be this SecurityFilter project. However if you need Roles, ACLs etc... you should seriously reconsider Shiro or Spring Security.

A: And what about implementing your own HmacSha1 model (signed requests) as Amazon Web Services do?
Basics: Client signs the request with a Secret access key (SAK) and expire data, obtaining an hmac code.
Then client sends via POST the request plus some headers like hmac code and expire data and whatever you need. The server then gets your request in the controller (or interceptor), signs it with your SAK and expire time, and compares obtaining hmacs to validate user.


text:
Q: Max Count from Framed SQL Query I have the query below that is selected data in a 'framed' manner. There is a lot of data and I only want to get one 'page' at a time.
SELECT
    entryDateTime,
    value
FROM
(
    SELECT
        ROW_NUMBER() OVER(ORDER BY entryDateTime DESC) AS rowNum,
        entryDateTime,
        value
    FROM
        table
    WHERE
        entryDateTime BETWEEN @start AND @end
) AS TempTbl
WHERE
    rowNum BETWEEN @startRow AND @endRow;

I want to know if it's possible to get the maximum rowNum value from this. Basically, I am looking to get a count of all possible rows so I know how many pages of data exist for the given time span (I expect the maximum rowNum to be bigger than @endRow). Does anyone know how to do this?

A: Typically you would execute 2 separate queries, one that just does a COUNT(*), and then a separate one that gets the current page of data.


text:
Q: How do I view the execution time of my program? I want to find just how long my program takes to run from start to finish in order to compare it with a past version.
How would I go about finding the time it takes for both of these versions? I'm running ubuntu 12.04LTS

A: Use the time command:
time yourprogram

By default it will output something similar to this:
real    0m0.020s
user    0m0.004s
sys     0m0.000s

real means the total time your program runs. user means the time your program spent in user land code and sys is the time your program spent in kernel calls.

A: Run time myprogram
The time command will display all the details you need to know.
Example:
rh63-build(greg)~>time ls >/dev/null

real    0m0.003s
user    0m0.001s
sys     0m0.002s

Here is more about the time command: http://linux.die.net/man/1/time

A: Linux comes with the 'time' program.
$time ./myapp

real 0m0.002s
user 0m0.000s
sys 0m0.000s


text:
Q: How can create loop for below function Here webdriver should click on each element, but the action is same, can you anyone help me
I am new to JavaScript
public void clickOnAllFiters(){
        driver.findElement(By.cssSelector("div.scroll-item.all")).click();
        driver.findElement(By.cssSelector("div.scroll-item.news")).click();
        driver.findElement(By.cssSelector("div.scroll-item.results")).click();
        driver.findElement(By.cssSelector("div.scroll-item.schedules")).click();
        driver.findElement(By.cssSelector("div.scroll-item.images")).click();
        driver.findElement(By.cssSelector("div.scroll-item.video")).click();
        driver.findElement(By.cssSelector("div.scroll-item.comment")).click();
        driver.findElement(By.cssSelector("div.scroll-item.activity")).click();
    }

A: clickOnAllFilters("div.scroll-item.activity", "div.scroll-item.activity"); // You can add more, or simply send an array of strings.

public void clickOnAllFilters(String... filters)
{
    for(String filter : filters)
    {
        driver.findElement(By.cssSelector(filter)).click();
    }
}

A: Put the strings into an array and loop through the array.
String[] strings = new String[] {"div.scroll-item.all", ...};
for (String string : strings) {
  driver.findElement(By.cssSelector(string)).click();
}


text:
Q: Heroku Error Deleting a Post in Production: Rails I am trying to delete a post in my app. It's working fine in localhost but when i pushed to heroku it's not working. I get an error saying "Something went wrong , Please check the logs". Here is my code:
posts_controller.rb
class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user! , except: [:index,:show,:search]
  before_filter :check_user, only: [:edit,:update,:destroy]

  # GET /posts
  # GET /posts.json

  def search
    if params[:search].present?
    @posts = Post.search(params[:search])
    else
    @posts = Post.all
    end
  end

  def index
    if params[:tag]
      @posts = Post.tagged_with(params[:tag])
    else
      @posts = Post.all
    end
  end

  # GET /posts/1
  # GET /posts/1.json
  def show
    @reviews = Review.where(post_id: @post.id)

  end

  # GET /posts/new
  def new
    @post = Post.new
  end

  # GET /posts/1/edit
  def edit
    @post = Post.find(params[:id])
  end

  # POST /posts
  # POST /posts.json
  def create
    @post = Post.new(post_params)
    @post.user_id = current_user.id

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render :show, status: :created, location: @post }
      else
        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /posts/1
  # PATCH/PUT /posts/1.json
  def update
    respond_to do |format|
      if @post.update(post_params)
        format.html { redirect_to root_url, notice: 'Post was successfully updated.' }
        format.json { render :show, status: :ok, location: @post }
      else
        format.html { render :edit }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /posts/1
  # DELETE /posts/1.json
  def destroy
    @post.destroy
    respond_to do |format|
      format.html { redirect_to root_path, notice: 'Post was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_post
      @post = Post.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def post_params
      params.require(:post).permit(:title, :description,:image,:all_tags)
    end

    def check_user
      if  current_user.id != @post.user_id
      redirect_to root_path , alert: "Sorry this Post belongs to someone else"
    end
    end

end

The Logs

view/posts/index.html.erb

Posts

    <% @posts.each do |post| %>

<%=link_to post.title , post%>

        <%=raw tag_links(post.all_tags)%>
          <%= link_to 'Edit', edit_post_path(post) %>
          <%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %>

    <%end%>

models/post.rb
  class Post < ActiveRecord::Base
  searchkick
  has_many :reviews , dependent: :destroy
  has_many :taggings, dependent: :destroy
  has_many :tags, through: :taggings
  #Paperclip Installation
  has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
  validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]

  def all_tags=(names)
  self.tags = names.split(",").map do |name|
      Tag.where(name: name.strip).first_or_create!
  end
end

def all_tags
  self.tags.map(&:name).join(", ")
end

def self.tagged_with(name)
  Tag.find_by_name!(name).posts
end

end

Schema
ActiveRecord::Schema.define(version: 20151026124712) do

      create_table "posts", force: :cascade do |t|
        t.string   "title"
        t.text     "description"
        t.datetime "created_at",         null: false
        t.datetime "updated_at",         null: false
        t.integer  "user_id"
        t.string   "tags"
        t.string   "image_file_name"
        t.string   "image_content_type"
        t.integer  "image_file_size"
        t.datetime "image_updated_at"
      end

      create_table "reviews", force: :cascade do |t|
        t.text     "comment"
        t.datetime "created_at", null: false
        t.datetime "updated_at", null: false
        t.integer  "user_id"
        t.integer  "post_id"
      end

      create_table "taggings", force: :cascade do |t|
        t.integer  "post_id"
        t.integer  "tag_id"
        t.datetime "created_at", null: false
        t.datetime "updated_at", null: false
      end

      add_index "taggings", ["post_id"], name: "index_taggings_on_post_id"
      add_index "taggings", ["tag_id"], name: "index_taggings_on_tag_id"

      create_table "tags", force: :cascade do |t|
        t.string   "name"
        t.datetime "created_at", null: false
        t.datetime "updated_at", null: false
      end

      create_table "users", force: :cascade do |t|
        t.string   "email",                  default: "", null: false
        t.string   "encrypted_password",     default: "", null: false
        t.string   "reset_password_token"
        t.datetime "reset_password_sent_at"
        t.datetime "remember_created_at"
        t.integer  "sign_in_count",          default: 0,  null: false
        t.datetime "current_sign_in_at"
        t.datetime "last_sign_in_at"
        t.string   "current_sign_in_ip"
        t.string   "last_sign_in_ip"
        t.datetime "created_at"
        t.datetime "updated_at"
        t.string   "name"
      end

      add_index "users", ["email"], name: "index_users_on_email", unique: true
      add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

      create_table "votes", force: :cascade do |t|
        t.integer  "votable_id"
        t.string   "votable_type"
        t.integer  "voter_id"
        t.string   "voter_type"
        t.boolean  "vote_flag"
        t.string   "vote_scope"
        t.integer  "vote_weight"
        t.datetime "created_at"
        t.datetime "updated_at"
      end

      add_index "votes", ["votable_id", "votable_type", "vote_scope"], name: "index_votes_on_votable_id_and_votable_type_and_vote_scope"
      add_index "votes", ["voter_id", "voter_type", "vote_scope"], name: "index_votes_on_voter_id_and_voter_type_and_vote_scope"

    end

A: As the error log says, there are foreign keys related to posts in taggings table, so it does not allow you to delete posts.
I guess a post has many taggings, and a tagging belongs to a tag? In this case, you need to delete all taggings belong to the post you want to delete. The easiest way is adding dependent: :destroy to your post model like
# models/post.rb
has_many :taggings, dependent: :destroy

A: You have some records in Taggings table which referenced to Post record.
So you have several options -

*

*has_many :taggings, dependent: :destroy
Or you can change yours migration:

*

*add_foreign_key :taggins, :posts, on_delete: :cascade (you can add this in database migration)

Described here


text:
Q: simplereenroll for EST client using libCurl I'm trying to develop an EST client program in C using libcurl, to perform simpleenroll and simplereenroll. As of now, I was able to retrieve the certificate using ./well-known/est/simpleenroll., but I'm have a problem performing ./well-known/est/simplereenroll
url = self.url_prefix + '/simplereenroll'
        auth = (self.username, self.password)
        headers = {'Content-Type': 'application/pkcs10'}
        content = est.request.post(url, csr, auth=auth, headers=headers,
            verify=self.implicit_trust_anchor_cert_path,
            cert=cert)
        pem = self.pkcs7_to_pem(content)

I was referring this python code where I could see the certificate being passed for simplereenroll operation. I don't know how to implement the same using libcurl.
Below mentioned is the portion of libcurl code which I'm using to perform the simpleenroll.
/*SIMPLEENROLL
 *
 */

if (res = curl_easy_setopt(curl,CURLOPT_URL,"https://localhost:4443/.well-known/est/simpleenroll")!=CURLE_OK)
    {
        fprintf(stderr,"curl_easy_setopt() failed: %s\n",curl_easy_strerror(res));
        return 1;
    }
    struct curl_slist* slist = NULL;
    slist = curl_slist_append(slist, "Content-Type: application/pkcs10");
    curl_easy_setopt(curl,CURLOPT_USERPWD,"estuser:estpwd")
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, CSR);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, CSR_LEN);
    if((res = curl_easy_perform(curl))!=CURLE_OK)
    {
        fprintf(stderr,"curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
        return 1;
    }

The above code will return a client certificate from server. Now I need to perform simplereenroll where I need to provide this certificate.

A: curl_easy_setopt(curl, CURLOPT_SSLKEY, client_key);
curl_easy_setopt(curl, CURLOPT_SSLCERT, client_cert);
curl_easy_setopt(curl, CURLOPT_CERTINFO, 1L);


text:
Q: How to get pixel color at location from UIimage scaled within a UIimageView I'm currently using this technique to get the color of a pixel in a UIimage. (on Ios)
- (UIColor*) getPixelColorAtLocation:(CGPoint)point {
UIColor* color = nil;
CGImageRef inImage = self.image.CGImage;
// Create off screen bitmap context to draw the image into. Format ARGB is 4 bytes for each pixel: Alpa, Red, Green, Blue
CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage];
if (cgctx == NULL) { return nil; /* error */ }

size_t w = CGImageGetWidth(inImage);
size_t h = CGImageGetHeight(inImage);
CGRect rect = {{0,0},{w,h}};

// Draw the image to the bitmap context. Once we draw, the memory
// allocated for the context for rendering will then contain the
// raw image data in the specified color space.
CGContextDrawImage(cgctx, rect, inImage);

// Now we can get a pointer to the image data associated with the bitmap
// context.
unsigned char* data = CGBitmapContextGetData (cgctx);
if (data != NULL) {
    //offset locates the pixel in the data from x,y.
    //4 for 4 bytes of data per pixel, w is width of one row of data.
    int offset = 4*((w*round(point.y))+round(point.x));
    int alpha =  data[offset];
    int red = data[offset+1];
    int green = data[offset+2];
    int blue = data[offset+3];
    NSLog(@"offset: %i colors: RGB A %i %i %i  %i",offset,red,green,blue,alpha);
    color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:(blue/255.0f) alpha:(alpha/255.0f)];
}

// When finished, release the context
CGContextRelease(cgctx);
// Free image data memory for the context
if (data) { free(data); }
return color;

}
As illustrated here;
http://www.markj.net/iphone-uiimage-pixel-color/
it works quite well, but when working with images larger than the UIImageView it fails. I tried adding an image and changing the scaling mode to fit the view. How would I modify the code to so that it would still be able to sample the pixel color with a scaled image.

A: try this for swift3
func getPixelColor(image: UIImage, x: Int, y: Int, width: CGFloat) -> UIColor
{

    let pixelData = CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage))
    let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)

    let pixelInfo: Int = ((Int(width) * y) + x) * 4

    let r = CGFloat(data[pixelInfo]) / CGFloat(255.0)
    let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
    let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
    let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)

    return UIColor(red: r, green: g, blue: b, alpha: a)
}

A: Here's a pointer:
0x3A28213A //sorry, I couldn't resist the joke

For real now: after going through the comments on the page at markj.net, a certain James has suggested to make the following changes:
size_t w = CGImageGetWidth(inImage); //Written by Mark
size_t h = CGImageGetHeight(inImage); //Written by Mark
float xscale = w / self.frame.size.width;
float yscale = h / self.frame.size.height;
point.x = point.x * xscale;
point.y = point.y * yscale;

(thanks to http://www.markj.net/iphone-uiimage-pixel-color/comment-page-1/#comment-2159)
This didn't actually work for me... Not that I did much testing, and I'm not the world's greatest programmer (yet)...
My solution was to scale the UIImageView in such a way that each pixel of the image in it was the same size as a standard CGPoint on the screen, then I took my color like normal (using getPixelColorAtLocation:(CGPoint)point) , then I scaled the image back to the size I wanted.
Hope this helps!

A: Use the UIImageView Layer:
- (UIColor*) getPixelColorAtLocation:(CGPoint)point {
    UIColor* color = nil;

    UIGraphicsBeginImageContext(self.frame.size);
    CGContextRef cgctx = UIGraphicsGetCurrentContext();
    if (cgctx == NULL) { return nil; /* error */ }

    [self.layer renderInContext:cgctx];

    unsigned char* data = CGBitmapContextGetData (cgctx);
    /*
    ...
    */
    UIGraphicsEndImageContext();
    return color;
}


text:
Q: argsparse groups mutually exclusive I wonder if it is possible to create mutually exclusive groups, not only arguments.
The code below works fine with groups.
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("p1")

group_infra_role = parser.add_argument_group("Group1")
group_infra_role.add_argument("--p2")
group_infra_role.add_argument("--p3")

group_custom_role = parser.add_argument_group("Group2")
group_custom_role.add_argument("--p4")
group_custom_role.add_argument("--p5")
args = parser.parse_args()
print(args)

It generated the output as below:
$ ./demo-argsparser.py -h
usage: demo-argsparser.py [-h] [--p2 P2] [--p3 P3] [--p4 P4] [--p5 P5] p1

positional arguments:
  p1

optional arguments:
  -h, --help  show this help message and exit

Group1:
  --p2 P2
  --p3 P3

Group2:
  --p4 P4
  --p5 P5

I would like to configure it in a way that if any argument from Group1 is supplied it will be mutually exclusive from Group2, and vice-versa.
Like the code below:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("p1")

group_exclusive = parser.add_mutually_exclusive_group()

group_infra_role = group_exclusive.add_argument_group("Group1")
group_infra_role.add_argument("--p2")
group_infra_role.add_argument("--p3")

group_custom_role = group_exclusive.add_argument_group("Group2")
group_custom_role.add_argument("--p4")
group_custom_role.add_argument("--p5")
args = parser.parse_args()
print(args)

But it fail:
$ ./demo-argsparser.py -h
Traceback (most recent call last):
  File "./demo-argsparser.py", line 17, in <module>
    args = parser.parse_args()
  File "/usr/lib/python3.7/argparse.py", line 1764, in parse_args
    args, argv = self.parse_known_args(args, namespace)
  File "/usr/lib/python3.7/argparse.py", line 1796, in parse_known_args
    namespace, args = self._parse_known_args(args, namespace)
  File "/usr/lib/python3.7/argparse.py", line 2002, in _parse_known_args
    start_index = consume_optional(start_index)
  File "/usr/lib/python3.7/argparse.py", line 1942, in consume_optional
    take_action(action, args, option_string)
  File "/usr/lib/python3.7/argparse.py", line 1870, in take_action
    action(self, namespace, argument_values, option_string)
  File "/usr/lib/python3.7/argparse.py", line 1052, in __call__
    parser.print_help()
  File "/usr/lib/python3.7/argparse.py", line 2489, in print_help
    self._print_message(self.format_help(), file)
  File "/usr/lib/python3.7/argparse.py", line 2473, in format_help
    return formatter.format_help()
  File "/usr/lib/python3.7/argparse.py", line 293, in format_help
    help = self._root_section.format_help()
  File "/usr/lib/python3.7/argparse.py", line 224, in format_help
    item_help = join([func(*args) for func, args in self.items])
  File "/usr/lib/python3.7/argparse.py", line 224, in <listcomp>
    item_help = join([func(*args) for func, args in self.items])
  File "/usr/lib/python3.7/argparse.py", line 331, in _format_usage
    action_usage = format(optionals + positionals, groups)
  File "/usr/lib/python3.7/argparse.py", line 406, in _format_actions_usage
    start = actions.index(group._group_actions[0])
IndexError: list index out of range


text:
Q: Is it possible to run Steam games using optirun? I am using Bumblebee on OpenSuse 13.1 on my Intel HD4600 / Nvidia GTX 860M combo.
Steam games seems to lag a bit, when using primusrun. (vblank_mode=0 primusrun)
Testing both primusrun and optirun with glxspheres, indicates that optirun is the better option on my system. But my Steam games does not start with the optirun command.
vblank_mode=0 primusrun glxspheres
209.926051 frames/sec - 234.277473 Mpixels/sec

vblank_mode=0 optirun glxspheres
250.734727 frames/sec - 279.819955 Mpixels/sec

Any help would be appreciated.

A: In theory, primusrun is preferred over optirun for performance and stability, as recommended by the bumblebee devs. I'm unsure why you get the results you did. I know in some cases, frames are capped, but that doesn't seem to be the case for you. (In my case I get 150 fps for optirun glxspheres64 and 60 fps for primusrun glxspheres64, which I believe is due to the cap.)
In any case, I use different options for different Steam games. Mostly, performance is similar with different commands, but the main difference to me is stability. This includes stability with and without the Steam overlay enabled. The following are different settings that I've used for different games, which you can test. I generally try this first:
primusrun %command%

However, I've found this is not always optimal. Sometimes optirun is more stable.
optirun %command%

In some cases, neither of those work (e.g. in Team Fortress 2) so I use:
LD_PRELOAD="libpthread.so.0 libGL.so.1" __GL_THREADED_OPTIMIZATIONS=1 optirun %command%


text:
Q: Converting an array to output as a CSV file I would like a downloadable CSV file from the table of data that is produced in my PHP Script. When I run the script, I get prompted for a download however when I open it, it appears to have just dumped all of the code (including tags etc) into a CSV file. All I need is the results contained in the table. Ive been tearing my hair out over this one! Any ideas? Heres the PHP part of my script:
<?php
session_start();
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='. 'file.csv');
header('Pragma: no-cache');
header("Expires: 0");

$serverName = "localhost\SQLEXPRESS";
$connectionInfo = array( "Database"=>"AuServer", "ReturnDatesAsStrings"=>"true");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

$sql = "select top 100 AuEvent.time_stamp, AusDatabase.Title, AuEvent.user_name, AuEvent.rec_id,                                        LogEventDescription.description
        FROM AuEvent
        INNER JOIN LogEventDescription
        ON AuEvent.event_id=LogEventDescription.event_id
        INNER JOIN AusDatabase
        ON AuEvent.db_id=AusDatabase.ID
        WHERE LogEventDescription.lcid='1033'
        ORDER BY time_stamp DESC";

    $stmt = sqlsrv_query( $conn, $sql );
    if( $stmt === false) {
        die( print_r( sqlsrv_errors(), true) );
}

//sort results into an array for the table
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ){
    echo "

        ". $row['time_stamp'] . "
        ". $row['Title'] . "
        ". $row['user_name'] . "
        ". $row['description'] . "
        ". $row['rec_id'] . "

";

$fp = fopen('file.csv', 'w');

foreach ($row as $fields) {
fputcsv($fp, $row);
}

}
?>

A: If you want to create downloadable file then stop echoing table data
<?php

session_start();
$serverName = "localhost\SQLEXPRESS";
$connectionInfo = array("Database" => "AuServer", "ReturnDatesAsStrings" => "true");
$conn = sqlsrv_connect($serverName, $connectionInfo);

$sql = "select top 100 AuEvent.time_stamp, AusDatabase.Title, AuEvent.user_name, AuEvent.rec_id,                                        LogEventDescription.description
        FROM AuEvent
        INNER JOIN LogEventDescription
        ON AuEvent.event_id=LogEventDescription.event_id
        INNER JOIN AusDatabase
        ON AuEvent.db_id=AusDatabase.ID
        WHERE LogEventDescription.lcid='1033'
        ORDER BY time_stamp DESC";

$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
    die(print_r(sqlsrv_errors(), true));
}

$fp = fopen('file.csv', 'w');
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
    foreach ($row as $fields) {
        fputcsv($fp, $row);
    }
}

$path = path/to/file;
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: '.filesize($file));
readfile($file);

?>

and if you want both print and downloading file then
<?php

session_start();
$serverName = "localhost\SQLEXPRESS";
$connectionInfo = array("Database" => "AuServer", "ReturnDatesAsStrings" => "true");
$conn = sqlsrv_connect($serverName, $connectionInfo);

$sql = "select top 100 AuEvent.time_stamp, AusDatabase.Title, AuEvent.user_name, AuEvent.rec_id,                                        LogEventDescription.description
        FROM AuEvent
        INNER JOIN LogEventDescription
        ON AuEvent.event_id=LogEventDescription.event_id
        INNER JOIN AusDatabase
        ON AuEvent.db_id=AusDatabase.ID
        WHERE LogEventDescription.lcid='1033'
        ORDER BY time_stamp DESC";

$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
    die(print_r(sqlsrv_errors(), true));
}

$fp = fopen('file.csv', 'w');
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
    foreach ($row as $fields) {
        fputcsv($fp, $row);
    }
}

$path = path/to/file;
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: '.filesize($file));
readfile($file);

ob_end_clean();
ob_start();

while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
    echo "echo all data here, tr and td etc";
}
ob_flush();
?>


text:
Q: StringLengthAttribute I am using Asp.Net MVC 2, and trying to iterate through the metadata to add input controls to grid columns. Most attributes like DisplayAttribute, StringLength attribute, etc are not populated by the default modelmetadata provider.
1- I think these attributes are going to be supported in MVC3, right?
2- Is there a custom provider that I can use till MVC3 is out, I remember seeing a custom metadata provider (thought it was in MVCContrib) but could not find it there, anyone knows where to find the metadataprovider supporting this attributes?

A: I wrote a provider to handle more attributes than the standard provider does. Here's the idea:
/// <summary>
/// Adds support for data annotation attributes omitted from DataAnnotationsModelMetadataProvider
/// </summary>
public class ExtendedDataAnnotationsModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
    {
        var result = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

        DisplayAttribute da = attributes.OfType<DisplayAttribute>().FirstOrDefault();
        if (da != null)
        {
            var autoGenerate = da.GetAutoGenerateFilter();
            if (autoGenerate.HasValue)
            {
                result.AdditionalValues[AdditionalValuesKeys.AutoGenerateFilter] = autoGenerate.Value;
            }
            var groupName = da.GroupName;
            if (!string.IsNullOrEmpty(groupName))
            {
                result.AdditionalValues[AdditionalValuesKeys.GroupName] = groupName;
            }
            if (!string.IsNullOrEmpty(da.Prompt))
            {
                result.Watermark = da.Prompt;
            }
        }

        DisplayColumnAttribute dc = attributes.OfType<DisplayColumnAttribute>().FirstOrDefault();
        if (dc != null)
        {
            var sc = dc.SortColumn;
            if (!string.IsNullOrEmpty(sc))
            {
                result.AdditionalValues[AdditionalValuesKeys.SortColumnName] = sc;
                if (dc.SortDescending)
                {
                    result.AdditionalValues[AdditionalValuesKeys.SortDescending] = true;
                }
            }
        }

        StringLengthAttribute sla = attributes.OfType<StringLengthAttribute>().FirstOrDefault();
        if (sla != null)
        {
            result.AdditionalValues[AdditionalValuesKeys.MaximumStringLength] = sla.MaximumLength;
        }

        return result;
    }
}

Naturally, the default templates with MVC don't actually do anything with that info. You have to customize them yourself.


text:
Q: Decoding StdClass in Python I am using Python to query a WordPress.org API using urllib. WordPress.org, in turn, decides to respond with an encoded PHP StdClass object. It would be great if I were using PHP, but I must use Python. Any idea how to take this and turn it into a dictionary (without the s:10:"slijekgdds" prefixes)?
apiUrl = "http://api.wordpress.org/themes/info/1.0/"
body = urllib.urlencode({
    'action': "query_themes",
    'request': {
        "browse": "featured",
        'fields': {
            'download_link': True,
            'preview_url': False,
            'screenshot_url': False,
            'description': False,
            'sections': False,
            'screenshots': False,
            'downloaded': False,
            'screenshot_count': False
        }
    }
}, True)

request = urllib.urlopen(apiUrl, body)
response = request.read(200)

This is returning (truncated):
O:8:"stdClass":2:{
    s:4:"info";
    a:3:{
        s:4:"page";
        i:1;
        s:5:"pages";
        i:41;
        s:7:"results";
        i:610;
    }
    s:6:"themes";
    a:15{
        i:0;
        O:8:"stdClass":10:{
            #BLAH BLAH
        }
    }
}

A: Based on this, which you'll have to install with pip or somesuch, I'm guessing this is what you want:
from phpserialize import loads, phpobject

python_object = loads(php_serialized_string, object_hook=phpobject)


text:
Q: How to search and delete files who contain specific string in name How can I delete every file on the system which have something in the name?

A: Please be careful
This following command with the parameter -delete deletes all the files with something in the name in the specified directory and in all subdirectories.

Open a terminal and go to the right folder:
cd <your_search_starts_here>

test with
find . -type f -name "*something*"

and delete with
find . -type f -name "*something*" -delete

Or a shorter version:
find <your_search_starts_here> -type f -name "*something*" -delete

For your home folder:

*

*!!! first run a test
find ~ -type f -name "*something*"

and than
find ~ -type f -name "*something*" -delete

For the whole filesystem

*

*!!! first run a test !!!
sudo find / -type f -name "*something*"

and test again and than delete with
sudo find / -type f -name "*something*" -delete

Or only in the specified directory:
find <your_search_starts_here> -maxdepth 1 -type f -name "*something*" -delete

And because you have used the tag locate:
The results of a search with locate are based on a database. This may be outdated. Start an update with sudo updatedb. find performs a true search. However, it also takes longer.


text:
Q: Showing another posts on Archive custom post type page I am facing very strange problem. Speaker is a custom post type and taxonomy. Target is showing all speakers which taxonomy is speaker as well.
When I am loading /speakers page, it is showing general blog posts. Also template is not same as archive-speaker.php. I have created another custom post type for testing which is working well. Only issue with speaker custom post type. It was working on another nginx server. After cloning the site to new nginx server, I see this problem.
My all configurations and testing:
register_post_type('speaker', array(
    'labels' => array(
        'name' => __('People', 'dxef'),
        'singular_name' => __('People', 'dxef'),
        'add_new' => __('Add New', 'dxef'),
        'add_new_item' => __('Add New Person', 'dxef'),
        'edit_item' => __('Edit Person', 'dxef'),
        'new_item' => __('New Person', 'dxef'),
        'all_items' => __('All People', 'dxef'),
        'view_item' => __('View Person', 'dxef'),
        'search_items' => __('Search People', 'dxef'),
        'not_found' => __('No People found', 'dxef'),
        'not_found_in_trash' => __('No People found in trash', 'dxef'),
        'menu_name' => __('People', 'dxef')
    ),
    'public' => true,
    'publicly_queryable' => true,
    'show_ui' => true,
    'show_in_menu' => true,
    'query_var' => true,
    'rewrite' => array(
        'slug' => 'speakers',
        'with_front' => false
    ),
    'capability_type' => 'post',
    'has_archive' => true,
    'hierarchical' => true,
    'menu_position' => 5,
    'supports' => array(
        'title',
        'editor',
        'thumbnail'
    )
));

Loading taxonomy related customs_posts
add_action( 'pre_get_posts', 'speaker_archive' );

function speaker_archive( $query ) {

    if( $query->is_main_query() && !is_admin() && is_post_type_archive( 'speaker' ) ) {

        $query->set( 'posts_per_page', '30' );

        $taxquery = array(
            array (
                'taxonomy' => 'roles',
                'field' => 'slug',
                'terms' => 'speaker',
                'operator' => 'IN'
            )
        );

        $query->set( 'tax_query', $taxquery );

    }

}

Above code is not being called any more. is_post_type_archive( 'speaker' ) returns false on /speakers page. I have flushed rewrite rule by saving permalinks. But it does not solve my issue.
I am assuming before calling custom post type, general blog post is being called. But not sure how to detect why such happen and what is the actual solution.


text:
Q: Making requests through tor, requests.exceptions.ConnectionError Errno 61: Connection Refused I'm trying to make a simple request to a whatsmyip site while connected to tor but no matter what I try I continue to get this error:
requests.exceptions.ConnectionError: SOCKSHTTPSConnectionPool(host='httpbin.org', port=443): Max retries exceeded with url: /get (Caused by NewConnectionError('<urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x1018a7438>: Failed to establish a new connection: [Errno 61] Connection refused'))

I've looked at a lot of posts on here with similar issues but I can't seem to find a fix that works.
This is the current code but I've tried multiple ways and its the same error every time:
import requests

def main():
    proxies = {
            'http': 'socks5h://127.0.0.1:9050',
            'https': 'socks5h://127.0.0.1:9050'
    }
    r = requests.get('https://httpbin.org/get', proxies=proxies)
    print(r.text)

if __name__ == '__main__':
    main()

A: Well the error says Max retries exceeded with url:, so possibly could be too many requests has been made from the tor exit nodes ip. Attempt to do it with a new Tor identity and see if that works.
If you wanted to you could catch the exception and put it in a loop to attempt every number of seconds, but this may lead to that ip address being refused by the server for longer.


text:
Q: Indy upload Memorystream to FTP I generate a JPEG at runtime, from a Screenshot, and want to upload it to a FTP server. But when I have it is uploaded it is no longer a valid jpeg.
In this example I just load a bitmap from the HD:
First some code:
procedure TForm13.Button1Click(Sender: TObject);
var
  InBitmap: TBitmap;
  JpegImage: TJpegImage;
  MemoryStream: TMemoryStream;
  IdFTP: TIdFTP;
begin
  InBitmap := TBitmap.Create;
  MemoryStream := TMemoryStream.Create;
  JpegImage := TJpegImage.Create;
  IdFTP := TIdFTP.Create(self);

  try
    InBitmap.LoadFromFile('C:\aa\test.bmp');

    JpegImage.Assign(InBitmap);
    JpegImage.CompressionQuality := 65;
    JpegImage.SaveToStream(MemoryStream);

    with IdFTP do
      try
        Host := <HOST>;
        Username := <USER>;
        Password := <PASS>;
        Port := 21;
        Passive := True;
        Connect;
        MemoryStream.Position := 0;
        Put(MemoryStream, 'test.jpg');
      finally
        Disconnect;
      end;
  finally
    IdFTP.Free;
    JpegImage.Free;
    InBitmap.Free;
    MemoryStream.Free;
  end;
end;

I have tried to save the JPEG to file before uploading it, and it is a valid JPG
I have tried to save the MemortStream to a file before uploading it, and it is a valid JPG
But when it is uploaded to the FTP server it is just a blank JPG file, still "valid" though.
It is not my FTP server, but one owned by those who host my domain. Here is a link to the just uploaded jpg: http://fluffykids.dk/test.jpg and here is the jpeg I saved to disc : http://fluffykids.dk/aa.jpg.
Question: Why am I loosing the "content" of my JPEG after uploading it?

A: You have to set the TIdFTP.TransferType to ftBinary. Default is ftASCII and that makes the difference.
with IdFTP do
  try
    Host := <HOST>;
    Username := <USER>;
    Password := <PASS>;
    Port := 21;
    Passive := True;

    TransferType := ftBinary;

    Connect;
    MemoryStream.Position := 0;
    Put(MemoryStream, 'test.jpg');
  finally
    Disconnect;
  end;


text:
Q: Extracting day with lubridate I have a date column, but it's written all the way around, Ex: "31-12-2019"
When I try to extract the day using the day() function from lubridate : day("31-12-2019") it returns "19" instead of "31"
PS : I've already tried to change to column type using as.Date, but it reorders my data and I don't want that

A: We need to first convert to Date class and then apply the day
library(lubridate)
day(as.Date("31-12-2019", "%d-%m-%Y"))
#[1] 31

Or with dmy
day(dmy("31-12-2019"))


text:
Q: Folder writing permission If I'm not wrong, to create or delete a file from a directory, you either need write permissions on that folder or write permission on that file (in case you're modifying it).
So, in a folder with 711 permissions and a php script (in that folder) with 755 permissions, and the following code:
$fileName = "createdFile.txt";
$fileHandle = fopen($fileName, 'w') or die("can't open file");
fclose($fileHandle);

Should this create a new file or throw an error? I have tried this on the public_html folder of a webserver and it does work, which surprises me because of what I have mentioned.
Moreover, I'm kind of confused about permissions for "everyone" in the case of the webserver. If you have 777 permissions on a folder, but no php script that could actually write or move files to that folder, is there any risk at all? Or would it have to be ftp access or some php script?
Sorry for the confusing question. I'll try to clarify if I can.

A: 755 is read and execute not write
You would need write permissions 766 or 777
OK, a little more help. It's a safe bet that the user account that the php script is running under owns the folder and since the first digit is a '7' the 'owner' has read write and execute permissions.

A: It's hard to give a much better answer because of the limited info about the created file you're able to supply but I'm presuming that the server is running as the same user that you upload files as. This is the only explanation that I have about it being able to create a file in a directory that has 755 permissions.
I'd have a chat with your hosting provider or check their documentation to verify in case there's some kind of misconfiguration on their part.


text:
Q: Problem with calling SESSION in another php tag So I'm trying to call the SESSION from one < ?php ?> (had to add the space cause it didn't want to show it) tag, in another < ?php ?> tag and I've no idea why it's not working at all. What I'm trying to do is to show the "editPassword" of an added advertisement in an alert modal window. But the problem is, that I'm getting an error, like the SESSION doesn't exist. The echo underneath the $post was only done to try if it works correctly in this php tag. It does.

  $postData = [
      'title' => $_POST['title'],
      'content' => $_POST['content'],
      'imageName' => $_FILES['imageUpload']['name'],
      'imageTmpName' => $_FILES['imageUpload']['tmp_name'],
      'imageSize' => $_FILES['imageUpload']['size'],
      'brand'   => $_POST["brand"],
      'model'   => $_POST["model"],
      'type'   => $_POST["type"],
      'fueltype'  => $_POST["fueltype"],
      'price'  => $_POST["price"],
      'editPassword' => $_SESSION['editPassword'] = substr(md5(rand()), 0, 5)
  ];
   $post->addPost($connection, $postData);
   echo $_SESSION['editPassword'];
}?>

And I'm calling the SESSION again in the html with a simple:

<?php  echo $_SESSION['editPassword']?>

When I try to run it, it shows this error, like the SESSION doesn't exist.
ERROR SHOWN
And when I fill the form the second time without reloading the page, it runs fine, BUT it shows the editPassword for the previous advert, not the current one.
editPassword of previous advert
What am I doing wrong?
Edit: I've added the session_start(); at the beginning of the php, now there's another problem which I've specified in the comments.

A: If for some reason $_SESSION['editPassword'] doesn't have a default value, that might trigger an undefined index until this runs, which i suppose doesn't run until a form is submitted.
So what you could do is
if (isset($_SESSION['editPassword'])){
echo $_SESSION['editPassword'];
}

You might also what to put a condition over when the form is submitted, something like
if (isset($_POST['submit])){
echo $_SESSION['editPassword'];
}

or read on $_REQUEST


text:
Q: How do I run ng e2e against a remote server? I want to run the the angular cli's ng e2e tests against a web application that is being served by someone else (other than angular cli).  How do I specify the host and port of the application?

A: Found it.  It's specified in the protractor.conf.js file at the root of the angular project:
  baseUrl: 'http://localhost:8080/',

A: You can specify in your config, and then override on the cli...
protractor conf.js --baseUrl https://adomain.com


text:
Q: Identifying hex value of keystrokes I need some guidance on how to write a Perl, VBScript or JavaScript code to display the hex value of a key stroke. I need this mainly for multimedia keys in keyboard like mute, volume up, volume down, etc.

A: Luckily somebody already wrote it: See
http://www.javascriptkit.com/javatutors/javascriptkey2.shtml


text:
Q: What is the best way to manage access to web controller in java? I have some question. What is the best way to manage access to web controller in java?
For example I have users and projects.
Each user can have several projects, but I don't want, that anyone has access to my project. How I can manage it? By writing some code in every controller, to check the permissions? Or are there some framework for it? Thanks for your answers.

A: Spring Security can help you with that.


text:
Q: Reflection and typeChecking for optionals Playing with reflections in swift 2.0 i'm trying to type check a child value.
The problem: each element of the children array in the Mirror of Any item is not optional, but his type can be optional... What happens is that of course i have the child value even if the value is nil
Maybe it is not clear so i put here some code to explain better.
For convenience i defined a subscript in a Mirror extension that fetches the child object with a given label
extension Mirror {
    public subscript(key: String)->Child?{
        var child = children.filter {
            var valid = false
            if let label = $0.label {
                valid = label == key
            }
            return valid
            }.last
        if child == nil,
            let superMirror = superclassMirror() {
                child = superMirror[key]
        }
        return child
    }
}

perfect, now let's say i have this class
class Rule: NSObject, AProtocol {
    var hello: String?
    var subRule: Rule?
}

Ok, now the problem
let aRule = Rule()
let mirroredRule = Mirror(reflecting:aRule)
if let child = mirroredRule["subRule"] {
     //child.value always exists
     //i can't do child.value is AProtocol? because child.value is not optional
     //child.value is AProtocol of course returns false
     //child.dynamicType is Optional(Rule)
     if let unwrapped = unwrap(child.value) where unwrapped is AProtocol {
         //This of course works only if child.value is not nil
         //so the unwrap function returns an unwrapped value
         //this is not a definitive solution
     }
}

child.value has not been initialized so it is nil, and i can't check his type using the unwrap function. I'm writing a deserializer so i need to check the var also if it is nil because in the dictionary that will be used for the deserialization it could be defined.
private func unwrap(subject: Any) -> Any? {
    var value: Any?
    let mirrored = Mirror(reflecting:subject)
    if mirrored.displayStyle != .Optional {
        value = subject
    } else if let firstChild = mirrored.children.first {
        value = firstChild.value
    }
    return value
}

I hope the problem is clear. Any suggestions?

A: Based on this answer, I recommend using if case Optional<Any>.some(_).
I did something recently to make sure I have at least one optional set on my struct. You can paste into playgrounds:
struct ErrorResponse: Codable {
    let message: String?
    let authorizationException: [String: String]?
    let validationException: String?
    let generalException: String?

    var isValid: Bool {
        var hasAtLeastOneNonNilErrorValue = false
        Mirror(reflecting: self).children.forEach {
            if case Optional<Any>.some(_) = $0.value {
                hasAtLeastOneNonNilErrorValue = true
            }
        }
        return hasAtLeastOneNonNilErrorValue
    }
}

let errorTest = ErrorResponse(message: "some message", authorizationException: nil, validationException: nil, generalException: nil)
let errorTest2 = ErrorResponse(message: nil, authorizationException: nil, validationException: nil, generalException: nil)

print("is valid: \(errorTest.isValid)")  //is valid: true
print("is valid: \(errorTest2.isValid)") //is valid: false


text:
Q: Reading a list of xml nodes causes segmentation fault I try to develop a package system for a game server engine i use, so, upon start i read a XML file and add the nodes to a list so i can use later. I can read the list after i created it, in same method. But when i try to read it from another file, it will give me segmentation fault. Lets see some code.
First, I have added a packages.cpp and packages.h. They look like:
packages.cpp
#include "otpch.h"
#include "packages.h"
#include "pugicast.h"
#include "tools.h"
#include "events.h"

std::list<pugi::xml_node> packages;

Packages::Packages()
{
    //
}

bool Packages::loadFromXml()
{
    std::string packagesPath = "data/packages";
    pugi::xml_document packagesDoc;
    pugi::xml_parse_result packagesResult = packagesDoc.load_file((packagesPath + std::string("/packages.xml")).c_str());
    if (!packagesResult) {
        printXMLError("Error - BaseEvents::loadFromXml", "data/packages/packages.xml", packagesResult);
        return false;
    }

    for (auto packageNode : packagesDoc.child("packages").children()) {
        packages.push_back(packageNode);
    }

    // I can read the list here without any problem.

    return true;
}

packages.h:
extern std::list<pugi::xml_node> packages;

class Packages
{
    public:
        Packages();
        bool loadFromXml();
};

Then I add this code to the startup file
Packages g_packages;

void mainLoader()
{
    std::cout << ">> Loading packages" << std::endl;
    if (!g_packages.loadFromXml()) {
        startupErrorMessage("Unable to load packages!");
        return;
    }
}

And finally, I try to iterate this list like this in another file:
#include "packages.h"

bool Events::loadFromPackages()
{
    for (auto& package : packages) {
        std::cout << package.name() << std::endl; // segmentation fault
    }
}

Thankful for any help.

A: Moving pugi::xml_document packagesDoc; to global scope will probably solve this issue.
When pugi::xml_document goes out of scope and is destroyed, all xml_node objects associated with nodes from that document become invalid. This is similar to iterators in STL containers - you can get iterators to std::list elements, but destroying the list object means that you can't access them.
It is likely that a better solution is to use something other than globals here - for example, maybe putting both xml_document and std::list<xml_node> inside the Packages class is a better option, but this somewhat depends on the structure you want your code to have.


text:
Q: unable to get value from asp.net dropdownlist on page submit i am developing a website using asp.net 3.5.i have created a cascading dropdownlist for country,state,and city.I am filling the state and city using jquery and web service.
But on page submit i am not able to get the selected value of state and city.it is returning blank.
on page load i am using this.
ListItem stateitem = new ListItem();
stateitem.Text = "Select";
stateitem.Value = "0";
dd_State.Items.Insert(0,stateitem);

I am using jquery and webservice to bind the state and city based on state.
on save button event i am getting the value as.
obj.StateId = Convert.ToInt32(dd_State.SelectedItem.Value);

onj.CityId = Convert.ToInt32(dd_City.SelectedItem.Value);

thanks in advance.

A: Since you are adding the values client-side, the page won't know about those values because they were not generated from code-behind. This means that on each postback the dropdown will be restored from viewstate as empty so it has no item to mark as selected.
You have at least two options:

*

*Lookup the selected value in the Form variables (the selected value is however sent to the server as a common POST behaviour)

*Use a hidden field in which you store the selected value via script in the onchange event of the dropdown


text:
Q: Capture image & Video without using uiimagepicker controller I need to capture Image & Video without opening imagepickerController.

A: You can Capture video and photo using AVCaptureSession
refer to iPhone SDK 4 AVFoundation - How to use captureStillImageAsynchronouslyFromConnection correctly?
-(void) viewDidAppear:(BOOL)animated
{
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    session.sessionPreset = AVCaptureSessionPresetMedium;

    CALayer *viewLayer = self.vImagePreview.layer;
    NSLog(@"viewLayer = %@", viewLayer);

    AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];

    captureVideoPreviewLayer.frame = self.vImagePreview.bounds;
    [self.vImagePreview.layer addSublayer:captureVideoPreviewLayer];

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    NSError *error = nil;
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    if (!input) {
        // Handle the error appropriately.
        NSLog(@"ERROR: trying to open camera: %@", error);
    }
    [session addInput:input];

stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil];
[stillImageOutput setOutputSettings:outputSettings];

[session addOutput:stillImageOutput];

    [session startRunning];
}

-(IBAction) captureNow
{
    AVCaptureConnection *videoConnection = nil;
    for (AVCaptureConnection *connection in stillImageOutput.connections)
    {
        for (AVCaptureInputPort *port in [connection inputPorts])
        {
            if ([[port mediaType] isEqual:AVMediaTypeVideo] )
            {
                videoConnection = connection;
                break;
            }
        }
        if (videoConnection) { break; }
    }

    NSLog(@"about to request a capture from: %@", stillImageOutput);
    [stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
    {
         CFDictionaryRef exifAttachments = CMGetAttachment( imageSampleBuffer, kCGImagePropertyExifDictionary, NULL);
         if (exifAttachments)
         {
            // Do something with the attachments.
            NSLog(@"attachements: %@", exifAttachments);
         }
        else
            NSLog(@"no attachments");

        NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
        UIImage *image = [[UIImage alloc] initWithData:imageData];

        self.vImage.image = image;
     }];
}


text:
Q: Adjuntar al proceso en Visual Studio Code Alguien sabe como adjuntar Visual Studio Code a otro proceso?
Necesito hacer debug de un addin de excel pero no encuentro la manera de hacerlo.
En Visual Studio si puede hacerse pero el IntelliSense funciona peor cuando se trata de trabajar con un conjunto de ficheros python que no están dentro de ningún proyecto.
Un saludo


text:
Q: What is the HEAD in git? There seems to be a difference between the last commit, the HEAD and the state of the file I can see in my directory.
What is HEAD, what can I do with it and what mistake should I avoid?

A: HEAD is a ref (reference) to the currently checked out commit.
In normal states, it's actually a symbolic ref to the branch you have checked out - if you look at the contents of .git/HEAD you'll see something like "ref: refs/heads/master". The branch itself is a reference to the commit at the tip of the branch. Therefore, in the normal state, HEAD effectively refers to the commit at the tip of the current branch.
It's also possible to have a "detached HEAD". This happens when you check out something besides a (local) branch, like a remote branch, a specific commit, or a tag. The most common place to see this is during an interactive rebase, when you choose to edit a commit. In detached HEAD state, your HEAD is a direct reference to a commit - the contents of .git/HEAD will be a SHA1 hash.
Generally speaking, HEAD is just a convenient name to mean "what you have checked out" and you don't really have to worry much about it. Just be aware of what you have checked out, and remember that you probably don't want to commit if you're not on a branch (detached HEAD state) unless you know what you're doing (e.g. are in an interactive rebase).

A: From docs; The role of HEAD is:

Tree
Role

Header
Last commit snapshot, next [future] parent

Index
Proposed next commit snapshot

Working Directory
Sandbox

HEAD is the pointer to the current branch reference, which is in turn a pointer to the last commit made on that branch.
That means HEAD will be the parent of the next commit that is created. It's generally simplest to think of HEAD as the snapshot of your last commit on that branch.

I always thought HEAD~5 means go to 5 commits before. But it doesn't carry the GO part of the command. It only carries the reference part of the command.
What you can do with that reference varies by the command you select
In layman terms it's used to answer the question of: WHERE should I go? To which commit?

*

*HEAD means (the reference to the) current commit

*HEAD~1 means (the reference to) 1 commit before

*HEAD~ ALSO means (the reference to) 1 commit before

*HEAD~87 means (the reference to) 87 commits before

*HEAD~3..HEAD means from 3 commits to current commit (in total 3 commits)

Usage:

*

*git checkout HEAD~1 will actually GO/checkout to 1 commit/reference before

*git reset HEAD~3 will uncommit your last 3 commits — without removing the changes, ie you can see all the changes made in the last 3 commits together, remove anything you don't like or add onto it and then commit them all again.

*git reset --hard HEAD~3 will uncommit your last commit and remove their changes. It will completely remove those changes. For more see here.

*git diff HEAD~3 to look into the changes of the last 3 commits

*git diff someFile HEAD~3 to look into the last 3 changes of a specific file

*git revert --no-commit HEAD~3..HEAD. Reverts 3 commits, without automatically commiting i.e. you have to do git commit -m yourself. For more see here

*git rev-parse HEAD~2 outputs the SHA of two commit before.

*See all changes between a pull request and main. It's a multi-step process.

git fetch origin/feature22
git checkout feature22
git merge-base feature22 main # will return the SHA of their 050dc022f3a65bdc78d97e2b1ac9b595a924c3f2
git reset 050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

You could just do git reset main, but that only works if your colleague who created the pull request has the latest changes with main. If they're working on a big feature (and haven't merged with main for a couple days) and you just want to see what additions they have after their last pull from main, then you have to follow the steps above.

Also make sure you see this answer for What is a detached HEAD.
It has some good info on cat .git/HEAD

Out of scope, but super interesting:
Other than HEAD, there are other kinds of heads. See git revisions:
ORIG_HEAD

ORIG_HEAD is created by commands that move your HEAD in a drastic way, to record the position of the HEAD before their operation, so that you can easily change the tip of the branch back to the state before you ran them

To undo a git merge
git reset --hard ORIG_HEAD

MERGE_HEAD
I got this error message after I tried to merge again before concluding an existing merge

fatal: You have not concluded your merge (MERGE_HEAD exists).
Please, commit your changes before you merge.

To fix this, I had to conclude my merge. Then do another merge.
FETCH_HEAD

records the branch which you fetched from a remote repository with your last git fetch invocation

CHERRY_PICK_HEAD

records the commit which you are cherry-picking when you run git cherry-pick.

For more on that see this other answer and docs

A: HEAD is a reference to the last commit in the currently checked-out branch.

There is a small exception to this, which is the detached HEAD. A detached HEAD is the situation you end up in whenever you check out a commit (or tag) instead of a branch. In this case, you have to imagine this as a temporary branch without a name; so instead of having a named branch reference, we only have HEAD. It will still allow you to make commits (which will update HEAD), so the above short definition is still true if you think of a detached HEAD as a temporary branch without a name.

A: HEAD pointer in Git
Git maintains a reference variable called HEAD. And we call this variable a pointer, because its purpose is to reference, or point to, a specific commit in the repository. As we make new commits the pointer is going to change or move to point to a new commit. HEAD always points to the tip of the current branch in our repository. Now, this has to do with our repository, not our staging index, or our working directory.
Another way to think of it is the last state of our repository or what was last checked out, and because it's where the repository left off or the last state, you can also say that the HEAD points to the parent of the next commit or it's where commit writing is going to take place.
I think a good metaphor to think about this is the playback and record head on a cassette tape recorder. As we start recording audio, the tape moves past the head, and it records onto it. when we press Stop the place where that record head is stopped is the place it'll start recording again when we press Record a second time.Now we can move around, we can move the head to different places, but wherever the head is positioned when we hit Record again that's where it's going to start recording.
The HEAD pointer in Git is very similar, it points at the place where we're going to start recording next. It's the place where we left off in our repository for the things that we've committed.

A: In simple terms, HEAD is a reference to the last commit in the currently check-out branch.
Think of the HEAD as the "current branch". When you switch branches with git checkout, the HEAD revision changes to point to the tip of the new branch.
You can see what HEAD points to by doing:
cat .git/HEAD

It is possible for HEAD to refer to a specific revision that is not associated with a branch name. This situation is called a detached HEAD.

A: Basically HEAD is a pointer/reference which points to the last commit in the current branch.
You can use these two commands to verify this.
$ git log -1

commit 9883e13257f2e7555eb6e3b14b2c814978c75692 (HEAD -> MyLocalBranch)
Author: vikram <vikramguptavit@gmail.com>
Date:   Sun Oct 11 23:32:45 2020 -0400
this is my last commit message

Now use below command to see where HEAD is pointing:
$ git rev-parse HEAD
9883e13257f2e7555eb6e3b14b2c814978c75692

As you can see that these two commit hashes are the same. So HEAD always points to the latest/last commit in the current branch.