text:
Q: Ruby programming exercise to determine whether a string is a palindrome I'm doing a programming exercise in Ruby to determine whether a string is a palindrome. Here is what I came up with:
# Write a method that takes a string and returns true if it is a
# palindrome. A palindrome is a string that is the same whether written
# backward or forward. Assume that there are no spaces; only lowercase
# letters will be given.
#
# Difficulty: easy.

def palindrome?(string)
    iterations=string.length/2
    is_palindrome=true
    i=0
    while i<iterations
        if string[i] != string[string.length-i-1]
            puts("string is not a palindrome")
            is_palindrome=false
        end
        i+=1
    end
    return is_palindrome
end

# These are tests to check that your code is working. After writing
# your solution, they should all print true.

puts("\nTests for #palindrome?")
puts("===============================================")
    puts('palindrome?("abc") == false: ' + (palindrome?('abc') == false).to_s)
    puts('palindrome?("abcba") == true: ' + (palindrome?('abcba') == true).to_s)
    puts('palindrome?("z") == true: ' + (palindrome?('z') == true).to_s)
puts("===============================================")

This returns the following:
Tests for #palindrome?
===============================================
string is not a palindrome
palindrome?("abc") == false: true
palindrome?("abcba") == true: true
palindrome?("z") == true: true
===============================================

The first output should be "false", and I can't figure out why it is not returning that. It does print "string is not a palindrome", so I would expect it to also set the "is_palindrome" variable to "false" and return that.

A: As far as your solution is concerned, I think you are mistaken your code works as expected. Of course false == false is true, so palindrome?("abc') == false is true.
Although not directly related to your solution but how about using inbuilt reverse functionality of ruby
def palindrome?(string):
    string == string.reverse
end

A: Disclaimer: This answer doesn't answer your question, the other answer was faster.
If you want to test your code you should also use also unit tests.
An example:
# Write a method that takes a string and returns true if it is a
# palindrome. A palindrome is a string that is the same whether written
# backward or forward. Assume that there are no spaces; only lowercase
# letters will be given.
#
# Difficulty: easy.

def palindrome?(string)
    iterations=string.length/2
    is_palindrome=true
    i=0
    while i<iterations
        if string[i] != string[string.length-i-1]
            #~ puts("string is not a palindrome")
            is_palindrome=false
        end
        i+=1
    end
    return is_palindrome
end

# These are tests to check that your code is working. After writing
# your solution, they should all print true.
require 'minitest/autorun'
class FirstLetterTest < Minitest::Test
  def test_abc
    refute(palindrome?('abc'), "'abc' is detected as a palindrome, but it isn't")
  end
  def test_abcba
    assert(palindrome?('abcba'), "'abcba' is not detected as a palindrome")
  end
  def test_z
    assert(palindrome?('z'), "'z' is detected as a palindrome, but it isn't")
  end
end

I removed your puts("string is not a palindrome") - it confuse the output.


text:
Q: MS Access SQL Insert Into table where records do not exist I am building an Access database for my work and I am a bit stuck with how to execute an INSERT INTO SQL query. I have a table (tblTempData) which has data imported from Excel. 2 of the columns contain the names of wards and consultants respectively. I have converted these to their correct WardID and ConsultantID by comparing their names to the stored names in my tblWard and tblConsultant tables.
At my work, a ward can have many consultants and a consultant can work on many wards so I have made a bridge table called tblWardConsultant which has a primary key and the FKs of WardID and ConsultantID. I now need to compare the records in tblTempData to tblWardConsultant and add any ward/consultant combinations that do not currently exist to tblWardConsultant.
E.g.
 tblWard:  WardID: 1, WardName: Ward X
           WardID: 2, WardName: Ward Y

 tblConsultant: ConsultantID: 1, ConsultantName: Person A
                ConsultantID: 2, ConsultantName: Person B

As person A can work on ward X and Y and person B works on ward X, they are in the following bridge table:
 tblWardConsultant: WardConsultantID: 1, WardID: 1, ConsultantID: 1
                    WardConsultantID: 2, WardID: 2, ConsultantID: 1
                    WardConsultantID: 3, WardID: 1, ConsultantID: 2

If in my tblTempData, I find that person B also works on ward Y, I need to add the WardID and ConsultantID into tblWardConsultant as a new record as:
 tblWardConsultant: WardConsultantID: 4, WardID: 2, ConsultantID: 2

So the question is how to do this! I have tried to just make the select part of the query using the code below but this returns all ward/consultant combos regardless of whether they are in the tblWardConsultant table or not. Changing it to WHERE EXISTS returns no results:
SELECT tblTempData.WardID, tblTempData.ConsultantID
FROM tblTempData
WHERE NOT EXISTS (
SELECT tblWardConsultant.WardID, tblWardConsultant.ConsultantID
FROM tblWardConsultant)
AND tblTempData.WardID IS NOT NULL
AND tblTempData.ConsultantID IS NOT NULL;

A: You need a correlated subquery, such as:
SELECT DISTINCT td.WardID, td.ConsultantID
FROM tblTempData as td
WHERE NOT EXISTS (SELECT twc.WardID, twc.ConsultantID
                  FROM tblWardConsultant as twc
                  WHERE twc.WardId = td.WardId AND twc.ConsultantId = tw.ConsultantId
                 ) AND
      td.WardID IS NOT NULL AND
      td.ConsultantID IS NOT NULL;

A: As an alternative, consider using the LEFT JOIN...IS NULL query (avoids subquery and might be better in readability if not performance):
SELECT tblWardConsultant.WardID, tblWardConsultant.ConsultantID
FROM tblWardConsultant
LEFT JOIN tblTempData
       ON tblWardConsultant.WardID = tblTempData.WardID
      AND tblWardConsultant.ConsultantID = tblTempData.ConsultantID
WHERE tblWardConsultant.WardID IS NULL
AND tblWardConsultant.ConsultantID IS NULL;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java Serial Reader I found this example using RXTX library. It works fine but I'm trying to understand how it works. Here is the code chunk.
public static class SerialReader implements Runnable
        {
            InputStream in;
            Robot robot;
            int x;
            int y;
            public SerialReader ( InputStream in , Robot robot)
            {
                this.in = in;
                this.robot = robot;
            }

            public void run ()
            {
                byte[] buffer = new byte[1024];
                int len = -1;
                try
                {
                    while ( ( len = this.in.read(buffer)) > -1 )
                    {

                        System.out.print(new String(buffer,0,len));

                    }
                }
                catch ( IOException e )
                {
                    e.printStackTrace();
                }
            }
        }

What I'm trying to understand is the while loop. It looks like it loads the buffer from input stream but since RS-232 send one byte at a time, im confused. What I'm trying to achive is to get the integer representation of the result that is printed out.

A: What is confusing about it? Even though data is sent one byte at a time, a sequence of bytes can be accumulated in the buffer so you read the whole sequence at once. The value len is how many bytes in sequence have been received. The way you are dealing with the received data though can be changed to reflect your expectations. Try for example replacing this
System.out.print(new String(buffer,0,len));

with this:
StringBuffer sb = new StringBuffer();
for (int i = 0; i < len; i++) {
    sb.append(String.valueOf(buffer[i]));
}
System.out.print(sb.toString());


text:
Q: What's this about kinetic energy increasing with the fifth power of length? I don't quite understand this quote from Stephen J. Gould's Ever since Darwin, where he talks about the compensating physical characteristics of organisms for their size.

Other essential features of organisms change even more rapidly
  with increasing size than the ratio of surface to volume. Kinetic
  energy, in some situations, increases as length raised to the fifth
  power. If a child half your height falls down, its head will hit
  with not half, but only 1/32 the energy of yours in a similar fall. In return,
  we are protected from the physical force of its tantrums, for
  the child can strike with, not half, but only 1/32 of the energy
  we can muster.

Mass increases with the third power of length, and even if we allow for a shorter fall (even though that is not clear from the wording) for the child (who is half as tall), I can only come up with the fourth power.

A: Model the child as a rod  of mass $m$ and length $l$ standing on the ground vertically, with center of mass at height $l/2$, with feet glued to the ground but the rest of the body able to rotate.
When upright, the potential energy is $mgl/2$. When lying on the ground, the potential is 0. So when falling, the child hits the ground with energy $mgl/2$. Equating this with $\frac{1}{2}I\omega^2$, with $I=\frac{m l^2}{3}$ (the moment of inertia of a rigid rod rotating about its end) one gets
$$\omega=\sqrt{\frac{3g}{l}}.$$
The head hits the ground with velocity $l\omega$. Letting the mass of the head be $m_h$, the kinetic energy of the head hitting the ground is
$$T=\frac{1}{2}m_h(l\omega)^2=\frac{3}{2} g l m_h.$$
Since $l\rightarrow \lambda l$ and $m_h\rightarrow\lambda^3m_h$ under a scale transformation $\lambda$, we have
$$T\rightarrow\lambda^4T.$$
So unless I'm overlooking something, I can't quite see where Gould's extra factor of $\lambda$ comes from. Assuming this is right and Gould is mistaken, I suspect he got the $\lambda^5$ figure by looking at $E=\frac{1}{2}I\omega^2$ and noting that $I\rightarrow\lambda^5I$, but forgot to look in detail as to how $\omega$ transforms.
NOTE: If it makes it easier to swallow, this analysis can also be carried out by assuming the child is a cylinder of radius $R$, length $L$ and constant density $\rho$ which is free to rotate about its base. The inertia tensor is
$$\mathbf{I}=\left(
\begin{array}{ccc}
 \frac{1}{12} L \pi  R^2 \left(4 L^2+3 R^2\right) \rho  & 0 & 0 \\
 0 & \frac{1}{12} L \pi  R^2 \left(4 L^2+3 R^2\right) \rho  & 0 \\
 0 & 0 & \frac{1}{2} L \pi  R^4 \rho  \\
\end{array}
\right)$$
and repeating the previous analysis using $I=\mathbf{I}_{xx}$ and $m=\pi  L \rho  R^2$ gives a head energy which scales as
$$T=m_h(L\omega)^2=\frac{6 g L^3 m_h}{4 L^2+3 R^2}\rightarrow\lambda^4T$$
under scale transformation.

A: It appears that the statement is half-right....
As answered by @DumpsterDoofus, the factor for a scaled object falling a scaled height, is the fourth power.
However, if we scale an object that is traveling at a velocity of  $x \frac{\text{body-lengths}}{\text{second}}$, then a fifth power for the kinetic energy is correct. The size and thus mass in the kinetic energy equation scales as the cube, and the velocity term in the kinetic energy scales as the square.
The difference in the two scenarios comes from correctly not scaling the distance factor in the value of $g$.


text:
Q: With Ruby gem aasm, is it possible to define the not(!) operator on guard functions that return a boolean result? class Ticket
  include AASM

  state :new
  state :open
  state :closed

  event :open do
    transitions :from => :new,:to => :closed, :guard => :cancelled?
    transitions :from => :new,:to => :open, :guard => !:cancelled?
  end
  def cancelled?
    true
  end
  def not_cancelled?
    true
  end
end

##Would I need the below?
transitions :from => :new,:to => :open, :guard => :not_cancelled?

In an effort to lessen the amount of code I have to write, is it possible to have something like !:cancelled in a guard function?  Or do I have to write a separate not_cancelled? function (as I suspect is the case).
I'm using Ruby 2.1 with gem 'aasm', '~> 3.1.1'

A: First, !:cancelled? expression evaluates to false always, so aasm doesn't even call cancelled? method in that case. To reduce the amount of code you can have it like the following
transitions :from => :new, :to => :closed, :guard => :cancelled?
transitions :from => :new, :to => :open, :guard => Proc.new { |ticket| !ticket.cancelled? }


text:
Q: Remove duplicates from a 2D array in perl I have a 2D array in perl whose data is coming as rows in html format from a DB like the data shown below:

Rafa	Nadal	Data1
,

Goran	Ivan	Data2
,

Leander	Paes	Data2
,

Leander	Paes	Data2

i want to remove the duplicate rows from the array.
"
Leander	Paes	Data2
" should be removed in above case.
I tried the below piece of code, but it's not working out.
sub unique {
     my %seen;
     grep ! $seen{ join $;, @$_ }++, @_
}

A: First: you really should try not to use outdated Perl syntax and side effects.
Second: the answer depends on the data structure you generate from the input. Here are two example implementations:
#!/usr/bin/perl
use strict;
use warnings;

# 2D Array: list of array references
my @data = (
    ['Rafa', 'Nadal', 'Data1'],
    ['Goran', 'Ivan', 'Data2'],
    ['Leander', 'Paes', 'Data2'],
    ['Leander', 'Paes', 'Data2'],
);
my %seen;

foreach my $unique (
    grep {
        not $seen{
            join('', @{ $_ })
        }++
    } @data
) {
    print join(',', @{ $unique }), "\n";
}
print "\n";

# List of "objects", keys are table column names
@data = (
    { first => 'Rafa',    last => 'Nadal', data => 'Data1' },
    { first => 'Goran',   last => 'Ivan',  data => 'Data2' },
    { first => 'Leander', last => 'Paes',  data => 'Data2' },
    { first => 'Leander', last => 'Paes',  data => 'Data2' },
);
%seen = ();

my @key_order = qw(first last data);

foreach my $unique (
    grep {
        not $seen{
            join('', @{ $_ }{ @key_order } )
        }++
    } @data
) {
    print join(',', @{ $unique }{ @key_order }), "\n";
}

Output:

$ perl dummy.pl
Rafa,Nadal,Data1
Goran,Ivan,Data2
Leander,Paes,Data2

Rafa,Nadal,Data1
Goran,Ivan,Data2
Leander,Paes,Data2

A: The shown sub is good for the job, with an array which for elements has array references. That is indeed a basic way to organize 2D data, where your rows are arrayrefs.
There are modules that can be leveraged for this, but this good old method works fine as well
use warnings;
use strict;
use Data::Dump qw(dd);

sub uniq_arys {
    my %seen;
    grep { not $seen{join $;, @$_}++ } @_;
}

my @data = (
    [ qw(one two three) ],
    [ qw(ten eleven twelve) ],
    [ qw(10 11 12) ],
    [ qw(ten eleven twelve) ],
);

my @data_uniq = uniq_arys(@data);

dd \@data_uniq;

Prints as expected (last row is gone), using Data::Dump to show data.
The sub works by joining each array into a string, and those are then checked for duplicates using a hash. The $; is a subscript separator, and an empty string '' is just fine instead.
This approach creates a lot of ancillary data -- in principle doubles the data -- and if performance becomes a problem it may be better to simply compare element-wise (at the cost of complexity). This can be an issue only with rather large data sets.

A module example: use uniq_by from List::UtilsBy
use List::UtilsBy qw(uniq_by);

my @no_dupes = uniq_by { join '', @$_ } @data;

This does, more or less, the same as the sub above.


text:
Q: One solution to check every form if empty I wonder if there is a smart solution to check every form - independent which form it is - if it is empty or not.
Like some solution I can declare in top of my class file and it will grab all the text input filed.
What I wan't to accomplish is to not be needed to create a input check if it is empty or not in every function dependent on a input text field. Just one clean solution fitting for all input text fields.
Hope you grab my idea.

A: Try:
if (array_reduce($_POST, function($res, $x) { return $res + strlen($x); }, 0) === 0)
  echo 'Form empty';

Edit:
An even simpler solution is
if (count(array_filter($_POST)) === 0)
  echo 'Form empty';

A: I see no point in such an idea.
Beside of such a general checking you will have to check the fields individually.
So, you will check required fields anyway and there is no point in running additional loop.


text:
Q: Iterate over object properties of an anonymous type list I am using EPPlus to create an "Export to Excel" helper. This will basically take an anonymous list and use that list to populate the spreadsheet.
I want to be able to iterate over the list object's properties and determine which is a datetime and format that column appropriately. The code I have below works, however is there a more succinct way to write this - specifically where I'm not depending on pulling an object from the list and operating on that object (i.e. I'm getting the property types from the list itself)?
    private static string[] columnIndex = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z".Split(',');
    private static ExcelWorksheet CreateAndFormatWorksheet<T>(OfficeOpenXml.ExcelPackage pck, List<T> dataSet)
    {
        ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Monet_Export_" + DateTime.Now.ToString());
        ws.Cells["A1"].LoadFromCollection(dataSet, true);

        if (dataSet.Count > 0)
        {
            // Pull first list item to determine so we have something to iterate over below
            dynamic first = dataSet[0];

            // List count == upper row count for the spreadsheet
            string rowCount = dataSet.Count.ToString();

            int i = 0;
            foreach (PropertyInfo info in first.GetType().GetProperties())
            {
                if (info.PropertyType == typeof(DateTime))
                {
                    string column = columnIndex[i];
                    string indexer = column + "2:" + column + rowCount;
                    ws.Cells[indexer].Style.Numberformat.Format = "mm/dd/yyyy";
                }
                else if (info.PropertyType == typeof (int))
                {
                    string column = columnIndex[i];
                    string indexer = column + "2:" + column + rowCount;
                    ws.Cells[indexer].Style.Numberformat.Format = "@";
                }

                i++;
            }
        }

        return ws;
    }

A: You can get the properties of the type T with typeof(T).GetProperties(). This works with anonymous types as well.
Then you don't need to pull out the first item to inspect its properties, and you don't have to check for dataSet.Count > 0 (if you want to allow an empty spreadsheet).


text:
Q: TouchBar keeps freezing The TouchBar in my new MacBookPro 2017 keeps freezing every time I use it to adjust the brightness of the screen. In order to circumvent this, I need to use the "Force Quit" command,  but is becoming really annoying.
Has this happened to anyone before? How should I fix the problem?

A: This is a known issue. The touch bar is quite finicky. Try these scripts in the terminal:
Kill touch bar - pkill "Touch Bar agent"
Refresh control strip - killall ControlStrip
Additionally, if the scripts didn't solve your issue and you are still under the 90 days of free Apple Care, I'd recommend taking it in. There are a number of things that could be wrong with it and it's really hard to diagnose + solve without a physical examination from an expert.


text:
Q: AddOrder issue on WHMCS Local API I'm adding a new order using WHMCS local API. Everything works fine except custom fields.
$command = 'AddOrder';
$postData = array(
    'clientid' => $client_id,
    'pid' => array($product_id),
    'billingcycle' => array('monthly'),
    'customfields' => array(base64_encode(serialize(array(1 => $site_id)))),
    'paymentmethod' => 'stripe',
);
return localAPI($command, $postData);

My custom field ID is 53 but I set the key to 1 because of tutorials. Also I tried 53 as key array(base64_encode(serialize(array(53 => $site_id)))) but nothing changed.
Do you have any suggestion?

A: Try this:
 $command = 'AddOrder';
 $postData = array(
'clientid' => $client_id,
'pid' => array($product_id),
'billingcycle' => array('monthly'),
'customfields[0]' => array(base64_encode(serialize(array(1 =>     $site_id)))),//changes here
'paymentmethod' => 'stripe',
);
return localAPI($command, $postData);ode here


text:
Q: I would like to use the IranNastaliq font with xelatex I would like to use the IranNastaliq font with xelatex, the document below throws an error when I try to compile it.
\documentclass{article}
\usepackage{xepersian}
\defpersianfont\Nastaliq{IranNastaliq}
\makeatletter
\newenvironment{Nastaliq}{\N@stliq}{}
\makeatother
\begin{document}
\begin{Nastaliq}

این طرح‌نما می‌آزماید نگاره و اندازه و شکل را

\end{Nastaliq}
\end{document}

Error
! Package fontspec Error: The font "IranNastaliq" cannot be found.

For immediate help type H <return>.
 ...

l.6

?

Package fontspec Warning: Font "IranNastaliq" does not contain requested
(fontspec)                Script "Persian".

Package fontspec Info: Could not resolve font "IranNastaliq/BI" (it probably
(fontspec)             doesn't exist).

Package fontspec Info: Could not resolve font "IranNastaliq/B" (it probably
(fontspec)             doesn't exist).

Package fontspec Info: Could not resolve font "IranNastaliq/I" (it probably
(fontspec)             doesn't exist).

! Package fontspec Error: The font "IranNastaliq" cannot be found.

A: You don't need to define an environment.
Use the code below:
\documentclass{article}
\usepackage{xepersian}
\settextfont{Yas}
\defpersianfont\nas[Scale=4]{IranNastaliq}
\begin{document}
\begin{nas}
این طرح‌نما می‌آزماید نگاره و اندازه و شکل را
\end{nas}
\end{document}

Output:

Of course, you must first make sure your font is installed.
If you are a Windows 10 user, right-click on the font and select
Install for all users. If you install it only for your own user account, Windows will put a copy in a hidden directory that XeTeX does not search (and you will need to remove it in the Fonts control panel if you ever want to install it for all users).
On Mac, you would want to install it to the System Font Book.  On Linux, there are several places to put it, including /usr/local/share/fonts/ to install it for everyone, and ~/.fonts/ to install it just for yourself.
If you only want to use the font for TeX, and not have it available in your other apps, you can instead put it in a subdirectory of your local TeX tree.  Which directory that is will vary, but you can normally find it with
kpsewhich --var-value=TEXMFLOCAL

On the Windows version of TeX Live, for example, this will typically be C:\texlive\texmf-local\.  On MikTeX, you might need to create a local TeX tree in the MikTeX console.  The conventional place to put the file would be under C:\texlive\texmf-local\fonts\opentype\IranNastaliq\, where you probably need to create the sub=folders yourself, but that's just to make it easier for you to find and delete them later.  Dropping the files anywhere in the tree is all the same to XeTeX.
If you're on a shared computer and don't have permission to change the TeX installation, you can use the TEXMFHOME directory instead of TEXMFLOCAL.  The command to find that is
kpsewhich --var-value=TEXMFHOME

If you only need the font for one project, or if you want to make sure you archive one particular version of the font with your project, you can save a copy in your project directory, and XeTeX should find it.
Wherever you put the font, you then might want to update the TeX font caches.  (This step is optional.)  To do so, run as an administrator either a powershell or a command prompt (hit Win-X on Windows) and run fc-cache.exe -f -s -v.  If you also use LuaLaTeX, you might additionally want to run luaotflaod-tool -f -u -p -v.
Good luck!


text:
Q: Unable to authenticate proxy when starting SQL snapshot agent I have a Windows Server 2008 R2 install running SQL Server 2008 R2 with all the latest updates etc applied,
I have restored a database from an old image (SQL 2005) and am trying to get web-sync working with merge subscriptions.
However when I attempt to start the SQL Snapshot Agent on the distribution I have defined I get this error:
Unable to start execution of step 2 (reason: Error authenticating proxy SERVER-NAME\Administrator, system error: Logon failure: unknown user name or bad password.).  The step failed.
I am starting the agent as the computer admin and am not using a proxy server.
Any ideas on why this might show up?
See below:

The params used by the SQL Snapshot agent are:

-Publication

-Publisher

-Distributor

-PublisherDB

-ReplicationType

If you are using SQL Server Authentication (I am), you must also specify the following arguments:

-DistributorLogin

-DistributorPassword

-DistributorSecurityMode = 0

-PublisherLogin

-PublisherPassword

-PublisherSecurityMode = 0


text:
Q: how to show titles(Type) in table view using JSON Data in iOS Swift? how to show titles(Type) in table view  using JSON Data in iOS Swift using the following format
[
    {
        "Id": 11000,
        "Type": "Title1"
    },
    {
        "Id": 11001,
        "Type": "Title2"
    },
    {
        "Id": 11002,
        "Type": "Title3"
    },
    {
        "Id": 11003,
        "Type": "Title4"
    }
]

A: You can use the following function to read titles in an array and use it as data source for tableView.
private func readJson( data : Data) -> [String] {
    var titlesArray = [String]()
    do {
        let json = try JSONSerialization.jsonObject(with: data, options: [])
        if let jsonDict = json as? [[String: Any]] {
            for anObject in jsonDict {
                if let title = anObject["Type"] as? String {
                    titlesArray.append(title)
                }
            }
        } else {
            print("JSON is invalid")
        }

    } catch {
        print(error.localizedDescription)
    }
    return titlesArray
}

I would suggest to use SwiftyJson for json parsing. Instead of doing it manually. You can read about Swifty Json.


text:
Q: synonyms in elasticsearch not matching a phrase with plurals Seeing a strange behaviour with synonyms on Elasticsearch:
Let's say my synonyms file has the following:
orange => apples & oranges

When I search for orange:
POST my_index/_search
{
  "suggest" : {
    "name_suggest" : {
      "text" : "orange",
      "completion" : {
        "field" : "name_suggest",
        "size" : 7,
        "fuzzy" :{}
      }
    }
  }
}

it does not match a doc with the name "apples & oranges"
However, if I search for "apples &"
POST new_sector_index,org_index/_search
{
  "suggest" : {
    "name_suggest" : {
      "text" : "apples &",
      "completion" : {
        "field" : "name_suggest",
        "size" : 7,
        "fuzzy" :{}
      }
    }
  }
}

it does match the doc with the name 'apples & oranges'
I cannot understand why 'orange' does not match even when I have defined the synonym in the file. I know the synonyms are indexed correctly since the other synonyms in the same file are working.
Also, wanted to mention that I am using a synonym_analyzer with lowercase, stop and kstem filters and whitespace tokenizer. I could imagine apples & oranges being stemmed to 'apple', '&' , 'orange' and hence not matching  but in that case just the phrase 'apples &' shouldn't match either?

A: The usage of ampersand (&) was causing the strange behaviour.
If I just do the following in the synonyms file,
orange => apples

it returns the intended document with the name 'apples & oranges' correctly
Not sure why apples & oranges in the synonyms does not work though. I tried removing stop and kstem filters but the behaviour remains the same


text:
Q: GWT RequestFactory not firing properly after using edit() I have a problem using "fire()" with a GWT RequestFactory after I've used it to unfreeze and edit a proxy.
If I have two request factory objects and their associated contexts like this:
private SyntheticRequest req1 = requestFactory.someRequest();
private Request<xProxy> sendRequest1 = req1.something();

private SyntheticRequest req2 = requestFactory.someRequest();
private Request<xProxy> sendRequest2 = req2.something();

using "fire()" on the first request works fine:
sendRequest1.fire(new Receiver<xProxy>() {
    @Override
    public void onSuccess(xProxy response) {
        ...
        if (somethingIsTrue){
               xProxy x = req2.edit(response);  //<-- **I think this causes a problem later, although the proxy "x" works as expected here.**
               x.setSomething("something");
               update();
         }
});

that part runs ok because I get to the "onSuccess".  But when this one runs "update()", which looks like this:
private void update(){
  sendRequest2.fire(new Receiver<xProxy>(){
       ...onFailure...
       ...onSuccess...
  });
}

sendRequest2 always fails, with the error

Server Error Index:0 Size:0

and I put a breakpoint in the code for the "something()" service and it never even gets to that code! There must be something about the "req2.edit()" that hurts req2 and sendRequest2, but what?
Thanks.

A: what is 'b'? the line  xProxy x = req2.edit(b);  is the first time it's mentioned? is it supposed to be  xProxy x = req2.edit(response);
Anyway.. that is not the problem..
'Server Error' indicates that RequestFactory caught an exception during the processing of a request, server-side. Something (but maybe not something()) is throwing an IndexOutOfBounds exception.
If you have a look at RequestFactoryServlet.java (which you can replace with your own very easily btw) you can see it setting up a try catch block that catches all exceptions when processing a request. It passes them to 'DefaultExceptionHandler' which wraps them in a ServerFailure, and that gets returned to you GWT code as an onFailure() call.
An easy way to find where the exception is being thrown is set a breakpoint on IndexOutOfBoundsException, making sure to catch 'caught' exceptions as well as uncaught.


text:
Q: AS3 Project - How do I import TLF? Using Flash develop I need to create a TLFTextField in an AIR AS3 project, but where do I find the swc to import?
I have imported textLayout.swc from the the flex sdk, but I get the error:
Error: Type was not found or was not a compile-time constant: TLFTextField.

A: TLFTextField is bundled in tlfruntime.swc. As far as I know, that's only bundled with Flash, not the Flex SDK.

A: This looks like the source code:
http://opensource.adobe.com/svn/opensource/flex/sdk/sandbox/viatropos/trunk/frameworks/projects/spark/src/mx/core/TLFTextField.as


text:
Q: Selenium controlled browser not working properly? I am trying to automate a website, and there is a dynamic drop-down which pops up based on the text entered. This drop-down works fine on any normal browser.
But when I execute the selenium test, the drop-down never shows up.  I even stopped the execution of the test but did not close the browser that opened by selenium. I refreshed the website, tried to manually entered the text, and still the dropdown was not showing up.


text:
Q: regex to match the argument of specific functions how to write a regular expression to match the below string :
name(abc1) or number(param9) or listget(12jtxgh)
I want to match the string enclosed in brackets only if it is prepended by name or number or listget.
I tried to this :
r'((.*?))'
and if my expression looks like below :
(name(foo) & number(bar)) - listget(baz)
then it starts matching (name(foo) also. I want my regex to extract only foo, bar and baz from the above expression as it is appended by name, number, listget.
I have to write regex in this form only #r'regex'

A: In regex brackets are special symbols used for grouping. To match them you have to use an escape character \ like this \(.
For NOT matching a symbol ex. brackets:
[^)]

should be used. Where you don't need the escape character.
For finding an alternative you should use the pipe character | surrounded by brackets. Example:
 (mary|john)

For NOT catching a group in a result match inside the the brackets you should start with ?:

A: The following regular expression should do the trick:
(?:listget|name|number)\(([^)]+)\)

You can try a working demo by visiting this link. As others pointed out, parenthesis must be escaped in order to match their literal, otherwise they are being used by the regex for different purposes (like capturing groups).


text:
Q: PHP display weird characters for utf8 characters I received the content from my database using:
$strip_title = html_entity_decode(strip_tags($title),ENT_QUOTES,'UTF-8');

it's displayed correctly with this string after echo:
[MV HD] Nợ Ai Đó Cả Thế Giới – Phạm Quỳnh Anh

but when I display above string as an array of characters using str_split function:
$result = str_split($title);
echo "
";
print_r($result);
echo "
";

then the result look something like this:
Array
(
    [0] => [
    [1] => M
    [2] => V
    [3] =>
    [4] => H
    [5] => D
    [6] => ]
    [7] =>
    [8] => N
    [9] => �
    [10] => �
    [11] => �
......................

What am I doing wrong here? How to correct this problem?
You can take a look at this sandbox demo

A: // this function is get from http://php.net/manual/en/function.str-split.php
function str_split_unicode($str, $l = 0) {
    if ($l > 0) {
        $ret = array();
        $len = mb_strlen($str, "UTF-8");
        for ($i = 0; $i < $len; $i += $l) {
            $ret[] = mb_substr($str, $i, $l, "UTF-8");
        }
        return $ret;
    }
    return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}

$title = "[MV HD] Nợ Ai Đó Cả Thế Giới - Phạm Quỳnh Anh";
$result = str_split_unicode($title);
echo "
";
print_r($result);
echo "
";

Sandbox Demo.


text:
Q: Save data as Arrays in Mysql I am trying to make a Quiz Game. I am having the table Questions  in MySQL
Columns -> id,
           Question
           Option_A
           Option_B
           Option_C
           Option_D
           Answer

Here I am having a definite number of options. But I want to have dynamically many options for each Question.
Can I save the options as an array in MySQL, if we can please help me out with this problem

A: There is no Concept of Array In MySQL. Create a Table QuestionOptions which has foreign key FK_Qusetion Refrenced By  Question_ID in Question Table.Then you Can Add Many Questions Against A Single Question Thanks


text:
Q: Very Slow Sharepoint (Authentication Problem? - Getting 401 errors on images and styles) I'm currently using Team Foundation Server and WSS 3.0 as the Team Portal. After the installation and configuring, I noticed the application was very slow sometimes, taking minutes to load a page. Then I googled it and found n solutions, none solved my problem.
Using Firebug I noticed I was getting a lot of 401 errors, mostly in _layouts and _themes folders.
Error image: http://i.stack.imgur.com/SmurI.jpg
Authentication method is NTLM
Any clue on what's happening? The page loads, it just takes forever before showing up.
EDIT: Here's fiddler statistics:
Request Count:  161
Bytes Sent:     144.851 (headers:133249; body:11602)
Bytes Received: 400.222 (headers:69769; body:330453)
ACTUAL PERFORMANCE
Requests started at:    09:47:55.449
Responses completed at: 09:50:03.311
Aggregate Session time: 00:03:11.542
Sequence (clock) time:  00:02:07.8627850
TCP/IP Connect time:    239ms
RESPONSE CODES
HTTP/401:   84
HTTP/200:   74
HTTP/302:   2
HTTP/404:   1
RESPONSE BYTES (by Content-Type)
application/x-javascript:   218.048
               ~headers~:   69.769
               text/html:   37.837
               image/gif:   31.467
                text/css:   27.506
               image/png:   10.133
              image/jpeg:   3.937
         text/javascript:   1.007
                text/xml:   518

A: We have had exactly this problem with a sharepoint site.
The root cause is the way that NTLM works. The NTLM handshake is a 401.2 401.1 followed by a 200. Allways 3 requests for each file.
For each request, the web server will send a request to the AD server. The problem is that by default there is only 2 connections to the AD server. So the request get backed up and retried.
There are two things that you can do:

*

*Make sure that you are caching the gif files (then you will not have to get them all the time)

*Switch to Kerberos

Edit
For setting up Kerberos have a look at this blog post http://blogs.msdn.com/b/martinkearn/archive/2007/04/23/configuring-kerberos-for-sharepoint-2007-part-1-base-configuration-for-sharepoint.aspx

A: Did you look at this common SharePoint performance fix?

A: Can you verify this happens on all clients?  If you access the page from a browser on the server itself, do you still get this result?
If you haven't yet, turn off IPv6 in your network settings.  Also, verify your DNS settings.  Slow AD authentication + RPC Server Unavailable leads me to believe you may have addressing issues.  Does everything seem responsive from a ping?  When you log on to your machine, does it take a long time to log in (another symptom of DNS setting problems)?

A: if you are 401 errors on CSS / js / Images / .axd. with sharepoint /
 NTLM authentification
You must configure the anonymous access on the webapplication and if you have a publishing portal activate the anonymous on :
 - style library
 - sitecollectionimage

A: I came across this problem with css files I downloaded. For some reason, the windows setting "encrypt contents to secure data" was checked for some files. After removing this setting, everything went fine. Be sure to unblock them if necessary.
(just to be sure: I'm talking about (file)->properties->advanced->encrypt data...)


text:
Q: Get the src value from a list of webelements with Selenium Hello trying to adapt a solution from this video
#scroller 100 fois pour reveler le plus d'image ( comment etre sur qu'on est à la fin ?)
n_scrolls = 100
for i in range(1, n_scrolls):
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(5)
    #recupère toutes les balises img puis leurs attribut src (je ne comprend pa bien cette façon d'assigner les elements)
    images = driver.find_elements_by_tag_name('img')
    print(images)
    images = [images.get_attribute('src') for img in images]

But the output is:
[<selenium.webdriver.remote.webelement.WebElement (session="50f35cc8388f3b59df4042bcc09c7079", element="4a4b2838-67d6-4787-a168-9e25e948a21a")>, <selenium.webdriver.remote.webelement.WebElement (session="50f35cc8388f3b59df4042bcc09c7079", element="7e3ae8f5-160a-4da6-b3a7-2be10bad8f3f")>, <selenium.webdriver.remote.webelement.WebElement (session="50f35cc8388f3b59df4042bcc09c7079", element="8c45c421-3f25-4498-85a2-565506835984")>, <selenium.webdriver.remote.webelement.WebElement (session="50f35cc8388f3b59df4042bcc09c7079", element="5ef69be7-13d7-41f1-9ec8-d8ac6e843fdd")>, <selenium.webdriver.remote.webelement.WebElement (session="50f35cc8388f3b59df4042bcc09c7079", element="626ae474-bccc-40c3-ac60-5b5f021b7bf0")>, <selenium.webdriver.remote.webelement.WebElement (session="50f35cc8388f3b59df4042bcc09c7079", element="ea0b589d-8e90-470a-ad59-a661f8d52b31")>

Instead of the img tag element, is it possible to get the src attributes?

A: I can find the mistake you have made.
Instead of this
images = [images.get_attribute('src') for img in images]

It should be
images = [img.get_attribute('src') for img in images]

Since you are iterating the list.
Now print the list you will get all src values.
print(images)

A: As images is the list of the <img> elements, while iterating the WebElements within the for loop you need to extract the src attribute from each individual img and also may like to avoid editing the same list and create a different list altogether. So effectively, your line of code will be:
images = driver.find_elements_by_tag_name('img')
print(images)
image_src_list = [img.get_attribute('src') for img in images]
print(image_src_list)


text:
Q: I'm getting an error "invalid use of incomplete type 'class map' I am making a basic text based RPG sorry if my question is stupid because i'm new to c++. So basically I have a small combat class that I have to link back and forth to from the map class so I had to forward declare my map class and it comes up with the error. BTW sorry there aren't any comments.
Here is the error: invalid use of incomplete type class Map
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class Map;
class Player
{
  public:
    int health;
    int damage;
    int defense;
    int gems=0;
    string race;
    string name;
    string location;
};

class Enemy
{
  public:
    int ehealth;
    int edamage;
    int edefense;
    int echoice;
};

class combat
{
  public:
    Map* mapobj;
    int damagedealt;
    Player playerobj;
    Enemy enemeyobj;
    string cchoice;
    string retry;

    void initial()
    {
        cout <<"A wild orc has appeared\n";
        cout <<"What do you do?\n";
        cout <<"---------------------------\n";
        cout <<"|-------------------------|\n";
        cout <<"|----Attack-----Defend----|\n";
        cout <<"|-------------------------|\n";
        cout <<"---------------------------\n";
        cin >>cchoice;
        this->battle();
    };
    void newturn()
    {
        cout <<"The orc is still alive!";
        cout <<"What do you do?";
        cout <<"\n---------------------------\n";
        cout <<"|-------------------------|\n";
        cout <<"|----Attack-----Defend----|\n";
        cout <<"|-------------------------|\n";
        cout <<"---------------------------\n";
        cin >>cchoice;
        this->battle();
    };
    void battle()
    {
        enemeyobj.echoice = rand() % 2;
        if (enemeyobj.echoice= 1)
        {
            if (cchoice=="Attack")
            {
            playerobj.damage;
            enemeyobj.ehealth=enemeyobj.ehealth-playerobj.damage;
            cout <<"You did "<<playerobj.damage<<" points of damge to the enemey.\n";
            if (enemeyobj.ehealth>0)
            {
                playerobj.health=enemeyobj.edamage-playerobj.health;
                cout <<"The enemyattacked you. You now have "<<playerobj.health<<" health";
                if (playerobj.health>0)
                {
                    this->newturn();
                }
                else if (playerobj.health<=0)
                {
                    cout << playerobj.name << "was killed\n";
                    cout << "Game Over";
                }
            }
            else if (enemeyobj.ehealth<=0)
            {
                 cout <<"You have defeated the orc!";
                 if (playerobj.location=="a")
                 {
                     mapobj->relaypointa();
                 }
            }

            }
            else if (cchoice=="Defend")
            {
                damagedealt=enemeyobj.edamage-playerobj.defense;
                playerobj.health=damagedealt-playerobj.health;
                cout <<"You defend but the enemey was able to deal\n";
                cout <<damagedealt<<" points of damage your health is\n";
                cout <<playerobj.health;
                if (playerobj.health>0)
                {
                    this->newturn();
                }
                else if (playerobj.health<=0)
                {
                    cout <<playerobj.name<<"was killed\n";
                    cout <<"Game Over";
                }
            }
        }
        else if (enemeyobj.echoice=2)
        {
            if (cchoice=="Attack")
            {
                damagedealt=enemeyobj.edefense-playerobj.damage;
                enemeyobj.ehealth=enemeyobj.ehealth-damagedealt;
                cout <<"You did "<<damagedealt<<" points of damage to the enemy";
                if (enemeyobj.ehealth>0)
                {
                    this->newturn();
                }
                else if (enemeyobj.ehealth<=0)
                {
                    cout <<"You have defeated the orc!";
                    mapobj->relaypointa();
                }
            }
            else if (cchoice=="Defend")
            {
                cout <<"Both parties defended";
                this->newturn();
            }
        }
    }
};

class Map
{
    public:
    combat combatobj;
    string mchoice;
    int espawn;
    Player playerobj;
    Enemy enemeyobj;
    void relaypointaespawn()
    {
        playerobj.location=="relaypointa";
        enemeyobj.ehealth = rand() % 50 + 100;
        enemeyobj.edamage = rand() % 50 + 75;
        enemeyobj.edefense = rand() % 50 + 50;
        combatobj.initial();
    }
    void relaypointa()
    {
        cout <<"You have found yourself at the\n";
        cout <<"mouth of a mighty river to the north\n";
        cout <<"What do you want to do?\n";
    }

    void relaypointb()
    {
        playerobj.location=="relaypointb";
        cout << "\n\n%%%%%%%%%%%%%%%%%%%%\n";
        cout << "%                  %\n";
        cout << "%   #Wild North#   %\n";
        cout << "%                  %\n";
        cout << "%%%%%%%%%%%%%%%%%%%%\n\n";
        cout <<"You have entered the wild north this is where your journey starts\n";
        cout <<"What would you like to do\n\n";
        cin >> mchoice;

        if (mchoice=="Travel")
        {
            cout <<"Where would you like to travel?\n";
            cin >>mchoice;
            if (mchoice=="North")
            {

            }
            else if (mchoice=="East")
            {

            }
            else if (mchoice=="South")
            {

            }
            else if (mchoice=="West")
            {
                this->relaypointaespawn();
            }
            else
            {
                cout <<"Invalid command\n\n";
                this->relaypointb();
            }
        }
    }
    void relaypointcespawn()
    {
        playerobj.location=="a";
        enemeyobj.ehealth = rand() % 50 + 100;
        enemeyobj.edamage = rand() % 50 + 75;
        enemeyobj.edefense = rand() % 50 + 50;
        espawn = rand() % 2;
    }
};

A: I am just providing another case where you can get this error message.  The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.
class FooReader {
  public:
     /** Constructor */
     FooReader() : d(new FooReaderPrivate(this)) { }  // will not compile here
     .......
  private:
     FooReaderPrivate* d;
};

====== In a separate file =====
class FooReaderPrivate {
  public:
     FooReaderPrivate(FooReader*) : parent(p) { }
  private:
     FooReader* parent;
};

The above will not pass the compiler and get error: invalid use of incomplete type FooReaderPrivate.  You basically have to put the inline portion into the *.cpp implementation file. This is OK.  What I am trying to say here is that you may have a design issue.  Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design.  I would be wrong, but please comment then I will update my posting.

A: Your first usage of Map is inside a function in the combat class. That happens before Map is defined, hence the error.
A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map is fully declared.
The solution is to follow the C++ pattern of the class declaration in a .h file and the function bodies in a .cpp. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.

A: This is because you need to show the at least decleration of the functions.
For workaround, create interface class with pure virtual methods for map class. Declare the functions that you are using ( as I see only relaypointa) then put this interface class in the beginning of the file and ofcourse do not forget to derive the map from it and use pointer to interface. combat class will see the interface and pure virtual function, so it will be okay.
I see this problem when I want to use single page online compiler
#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;
class MapIf {
    public:
        virtual void relaypointa() = 0;
};
class Player {
    public:
        int health;
    int damage;
    int defense;
    int gems = 0;
    string race;
    string name;
    string location;

};
class Enemy {
    public:

        int ehealth;
    int edamage;
    int edefense;
    int echoice;

};
class combat {
    public:
        MapIf * mapobj;
    int damagedealt;
    Player playerobj;
    Enemy enemeyobj;
    string cchoice;
    string retry;

    void initial() {
        cout << "A wild orc has appeared\n";
        cout << "What do you do?\n";
        cout << "---------------------------\n";
        cout << "|-------------------------|\n";
        cout << "|----Attack-----Defend----|\n";
        cout << "|-------------------------|\n";
        cout << "---------------------------\n";
        cin >> cchoice;
        this -> battle();
    }
    void newturn() {
        cout << "The orc is still alive!";
        cout << "What do you do?";
        cout << "\n---------------------------\n";
        cout << "|-------------------------|\n";
        cout << "|----Attack-----Defend----|\n";
        cout << "|-------------------------|\n";
        cout << "---------------------------\n";
        cin >> cchoice;
        this -> battle();
    };
    void battle() {

        enemeyobj.echoice = rand() % 2;
        if (enemeyobj.echoice = 1) {
            if (cchoice == "Attack") {
                playerobj.damage;
                enemeyobj.ehealth = enemeyobj.ehealth - playerobj.damage;
                cout << "You did " << playerobj.damage << " points of damge to the enemey.\n";
                if (enemeyobj.ehealth > 0) {
                    playerobj.health = enemeyobj.edamage - playerobj.health;
                    cout << "The enemyattacked you. You now have " << playerobj.health << " health";
                    if (playerobj.health > 0) {
                        this -> newturn();
                    } else if (playerobj.health <= 0) {
                        cout << playerobj.name << "was killed\n";
                        cout << "Game Over";

                    }

                } else if (enemeyobj.ehealth <= 0) {
                    cout << "You have defeated the orc!";
                    if (playerobj.location == "a") {
                        mapobj -> relaypointa();
                    }

                }

            } else if (cchoice == "Defend") {
                damagedealt = enemeyobj.edamage - playerobj.defense;
                playerobj.health = damagedealt - playerobj.health;
                cout << "You defend but the enemey was able to deal\n";
                cout << damagedealt << " points of damage your health is\n";
                cout << playerobj.health;
                if (playerobj.health > 0) {
                    this -> newturn();
                } else if (playerobj.health <= 0) {
                    cout << playerobj.name << "was killed\n";
                    cout << "Game Over";
                }
            }
        } else if (enemeyobj.echoice = 2) {
            if (cchoice == "Attack") {
                damagedealt = enemeyobj.edefense - playerobj.damage;
                enemeyobj.ehealth = enemeyobj.ehealth - damagedealt;
                cout << "You did " << damagedealt << " points of damage to the enemey";
                if (enemeyobj.ehealth > 0) {
                    this -> newturn();
                } else if (enemeyobj.ehealth <= 0) {
                    cout << "You have defeated the orc!";
                    mapobj -> relaypointa();
                }
            } else if (cchoice == "Defend") {
                cout << "Both parties defended";
                this -> newturn();
            }
        }
    }
};

class Map: public MapIf {
    public: combat combatobj;
    string mchoice;
    int espawn;
    Player playerobj;
    Enemy enemeyobj;
    void relaypointaespawn() {
        playerobj.location == "relaypointa";
        enemeyobj.ehealth = rand() % 50 + 100;
        enemeyobj.edamage = rand() % 50 + 75;
        enemeyobj.edefense = rand() % 50 + 50;
        combatobj.initial();
    }
    void relaypointa() {
        cout << "You have found yourself at the\n";
        cout << "mouth of a mighty river to the north\n";
        cout << "What do you want to do?\n";

    }

    void relaypointb() {
        playerobj.location == "relaypointb";
        cout << "\n\n%%%%%%%%%%%%%%%%%%%%\n";
        cout << "%                  %\n";
        cout << "%   #Wild North#   %\n";
        cout << "%                  %\n";
        cout << "%%%%%%%%%%%%%%%%%%%%\n\n";
        cout << "You have entered the wild north this is where your journey starts\n";
        cout << "What would you like to do\n\n";
        cin >> mchoice;
        if (mchoice == "Travel") {
            cout << "Where would you like to travel?\n";
            cin >> mchoice;
            if (mchoice == "North") {

            } else if (mchoice == "East") {

            } else if (mchoice == "South") {

            } else if (mchoice == "West") {
                this -> relaypointaespawn();
            } else {
                cout << "Invalid command\n\n";
                this -> relaypointb();
            }
        }

    }
    void relaypointcespawn() {
        playerobj.location == "a";
        enemeyobj.ehealth = rand() % 50 + 100;
        enemeyobj.edamage = rand() % 50 + 75;
        enemeyobj.edefense = rand() % 50 + 50;
        espawn = rand() % 2;
    }
};

int main() {

}


text:
Q: Does nodes of a polygon and cell relationships determine the shape of the polygoon? This is a follow-up concerning this question :
Explaination concerning the polygonal generalized Schoenflies problem
I have trouble understanding the implication of the Shoenflies problem. I am currently working on ways to describe polygonal meshes, and I wanted to prove the floowing (intuitive) proposition : "Node positions and "cell-relationships" fully dertermine a polygonal embedding as long as cells of dimension $p$ have their nodes in an affine hyperspace of dimension $p$".
By "cell-relationship", I mean knwowing the relationship "is in the boundary of ..." acting on cells. The number of cells can be constrained to be finite if needed.
In my previous post, I formulated the questions in thechnical terms that I do not fully understand, and while it received a very good answer very quickly, I am still not sure about what it implies for my proposition.
So my question is the following : for dimensions $<4$, is the inductive proof using the Shoenflies theorem valid ? Can the theorem be saved for dimensions $\ge4$ ?
Thanks in advance,


text:
Q: Show that injective immersion of a compact manifold is an embedding I need to show that injective immersion of a compact manifold is an embedding.
Here is what I think - By definition, an embedding is an immersion which is proper and injective. So consider a map $F : M \rightarrow N$ s.t. $F$ is an injective immersion.  Suppose $M$ is a compact manifold. ($N$ is also a manifold). Now by default I am done with the injective part of the function as I am defining my function to be injective. Hence I am left with the proper part. Then by using the property  of compact manifold which says that any continuous real-valued function is bounded on a compact manifold , I can say that $F$ is a bounded map. But I am unable to show that it is also a closed map.
Am I right in my above reasoning (proof) or is/are there some flaws? If not then can someone please tell me how to show that $F$ is closed?

A: Just to expand on my comment, you'll need to apply the theorem that the continuous image of a compact space is compact.
But, the problem is missing a hypothesis: you'll need to assume that the range is Hausdorff, so that you can apply the theorem that a compact subset of a Hausdorff space is closed.


text:
Q: "Enable SSL Verification" option does not stay checked in Anaconda Navigator I have been fiddling around with conda settings for about 3 days now, as my primary goal is simply to use various python packages in a Jupyter Notebook. Because I was having issues downloading some packages, I had run ssl_verify false in an effort to download the packages.
Having been unsuccessful, I attempted unchecking the "Enable SSL Verification" option in the "Preferences" of Anaconda Navigator. This didn't seem to change anything, except for that now every time I open preferences the box remains unchecked, and when I check the box and hit "apply" my cursor moves to the area directly to the left of the checkbox and there is a weird image that is an orange circle with a "!" and it opens an incomplete text box saying "invalid Anaconda URL." After closing the preferences window and re-opening, I find the "Enable SSL Verification" box still unchecked, and I want to be sure that SSL verification is enabled.
This is clearly a bug with Anaconda Navigator and I'm wondering if anybody else has experienced this, and whether there is a way to confirm SSL Verification stays enabled.


text:
Q: Does the isolation forest care about integer-encoded categorical variables? The isolation forest (initial paper, follow-up paper) as well as the proposed extended isolation forest (paper) seem like very appealing unsupervised anomaly detection techniques. However, the algorithms themselves work solely on continuous numerical data and cannot incorporate categorical (nominal) variables.
Since lot of machine learning models work with distance or density metrics, a simple mapping of nominal categorical variables to unique integers (i.e. 'A'-->0, 'B'-->1, ..., 'XYZAB'-->1022) would be a cardinal mistake as the models will impose a false sense of originality (e.g. implying 23 > 7 where 23 and 7 are simply different unrelated categories).
However, does the isolation forest care about such simple mappings of categorical variables to unique integers? (e.g. using scikit-learn's LabelEncoder class)
Since no computation of density or distance metrics are involved in the calculation of the anomaly score, I believe this is a valid question to discuss. It is not obvious to me why the model should not simply work with such a simple encoding of categorical variables, provided for example when the isolation trees are fully grown.


text:
Q: React-Select upgraded from 1.x to 3.0.4 - Selected value not shown I am a bit new in React and i am trying to upgrading react from old version to 16.9.
Everything works great but the following component that i had to upgrade to version 3.0.4.
The problem is that when i select a value, it's selected but i don't see the selected option on the screen and i see only the default placeholder.
i found few answers that explaining that i have to set the value using the full object and as per my understanding i am doing so.
Can someone help me to find the problem?
// @flow

import React, { Component } from "react";
import ReactSelect from "react-select";
import { isNil } from "lodash";
import type { FormProps } from "redux-form";
import cx from "classnames";
import { getClassName, addModifierTo } from "ui-kit/utils/component";
import { injectIntl, FormattedMessage } from "react-intl";
/* import "react-select/dist/react-select.css"; */
import "./Select.scss";

type Option = {
  label: string,
  value: string
}

type Props = {
  name?: string,
  options?: Array<Option>,
  className?: string
} & FormProps;

type State = {
  selectedOption: Object
}

const getInitOption = (multi, valueType) => (multi && valueType === "Array" ? [] : "");

class Select extends Component<Props, State> {
  constructor(props: Props) {
    super(props);

    this.state = {
      selectedOption: this.getOptionFromPropValue(),
      openUp:         false
    };
  }

  componentDidMount() {
    const { defaultValue, input } = this.props;

    if (input && defaultValue) {
      input.onChange(defaultValue);
    }
  }

  getOptionFromPropValue(props: Props = this.props) {
    const {
      defaultValue,
      input,
      multi,
      valueType = "String",
      value: valueFromProp
    } = props;
    let value = "";

    if (!isNil(defaultValue)) {
      value = defaultValue;
    }
    if (input && !isNil(input.value)) {
      ({ value } = input);
    }
    else if (valueFromProp) {
      value = valueFromProp;
    }

    let options;
    if (multi) {
      if (valueType === "String" || typeof value === "string") {
        value = value.split(",");
      }
      options = value.map(valueItem => ({ value: valueItem }));
    } else {
      options = [{ value }];
    }
    if (props.options) {
      options = options.map((option) => {
        const sameOption = props.options.find(item => item.value === option.value);
        if (sameOption) {
          return sameOption;
        }
        return option.value !== "" ? option : null;
      });
    }
    return multi ? options : options[0];
  }

  initialized: false

  UNSAFE_componentWillReceiveProps(nextProps) {
    const {
      loadedLabel, input, multi, valueType
    } = nextProps;

    if (!this.initialized) {
      this.setState({ selectedOption: this.getOptionFromPropValue(nextProps) });
      this.initialized = true;
    }

    if (this.selectedOption && !this.selectedOption.label && loadedLabel) {
      this.setState(prevState => ({ selectedOption: { ...prevState.selectedOption, label: loadedLabel } }));
    }

    if (input && !input.value) {
      this.setState({ selectedOption: getInitOption(multi, valueType) });
    }
  }

  render() {
    const {
      className,
      name,
      label,
      simple,
      creatable = false,
      asyncLoad = false,
      input,
      hasBorder = true,
      errorOffset = false,
      meta = {},
      onChange: onChangeEvent,
      onChangeReplace,
      initialized,
      defaultValue,
      multi,
      valueType = "String",
      maxHeight,
      ...props
    } = this.props;

    const msg = meta.error || meta.warning;

    let Tag;
    if (asyncLoad) {
      Tag =  creatable ? ReactSelect.AsyncCreatable : ReactSelect.Async;
    } else {
      Tag =  creatable ? ReactSelect.Creatable : ReactSelect;
    }

    const onChange = onChangeReplace || ((selectedOption) => {
      if (!selectedOption) {
        selectedOption = { value: "" };
      }
      let value;
      if (multi && Array.isArray(selectedOption)) {
        value = selectedOption.map(({ value: valueItem }) => valueItem);
        if (valueType === "String") {
          value = value.join(",");
        }
      } else {
        ({ value } = selectedOption);
      }
      if (input) {
        input.onChange(value);
      }
      if (onChangeEvent) onChangeEvent({ target: { name, value } });
      this.setState({ selectedOption });
    });

    // for fix bug with losing value on Blur (https://github.com/erikras/redux-form/issues/1185)
    const onBlur = () => input && this.state.selectedOption && input.onBlur(this.state.selectedOption.value);

    const onOpenHandler = () => {
      if (!isNil(this.elDOM)) {
        let inputEl = this.elDOM.input;
        if (!isNil(inputEl) && !(inputEl instanceof window.Element)) {
          inputEl = inputEl.input;
        }
        if (!isNil(inputEl) && !isNil(this.elDOM.menuContainer)) {
          const rect = inputEl.getBoundingClientRect();
          const menuRect = this.elDOM.menuContainer.getBoundingClientRect();
          const bottomDistance = window.innerHeight - rect.bottom;
          const openUp = bottomDistance < (menuRect.height + 20);
          this.setState({ openUp }, () => {
            if (openUp && rect.top < menuRect.height) {
              window.scrollTo(0, window.scrollY - (menuRect.height - rect.top));
            }
          });
        }
      }
    };

    const ccn = getClassName("Select");
    const modify = addModifierTo(ccn());
    const modifyWrap = addModifierTo(ccn("wrap"));

    console.log(this.state.selectedOption);

    // className "Select" is already present in Tag
    return (

        {label &&
{label}
}
        <Tag
          className={cx(
            simple && modify("simple"),
            !hasBorder && modify("no-border"),
          )}
          style={{ maxHeight }}
          name={name}
          multi={multi}
          {...input}
          clearable={false}
          backspaceRemoves={false}
          autosize={simple || false}
          value={this.state.selectedOption}
          onChange={onChange}
          onBlur={onBlur.bind(this)}
          onOpen={onOpenHandler}
          ref={(el) => { this.elDOM = el; }}
          placeholder=""
          noResultsText={<FormattedMessage id="select.noResultsText" defaultMessage="No results found" />}
          {...props}
        />
        {meta.visited && msg &&
{msg}
}

    );
  }
}

export default injectIntl(Select);

A: I think the react version for React-Select is 16.8.
https://github.com/JedWatson/react-select/issues/3585


text:
Q: Have renamed and modified file in git. How to make two commits, one for renaming and one for the contents? I've searched google and stackoverflow for an answer but not found any. Yes I could read the man pages and figure it out for myself, but I think there should be an easily accessible best-practice answer to this question here.
So, say oldname.py was renamed newname.py and modified, and now I want to first commit the rename operation without committing any of the changed contents, and then commit the changes in a new, separate commit. No changes have been staged.

A: Here is a way to do it :
# choose some way to "stash" your modifications
# either use git stash (you will need to 'git add' the new files, but not 'git commit' them)
# or simply rename them, e.g : mv newname.py newname.py.keep

$ git checkout oldname.py
$ git mv oldname.py newname.py
$ git commit

# get back your "stashed" content
# either 'git stash pop', and solve conflicts
# or rename the files to their target name, e.g : mv newname.py.keep newname.py

$ git add newname.py
$ git commit


text:
Q: How to change select functions in Angular Directive? http://plnkr.co/edit/pJRzKn2v1s865w5WZBkR?p=preview
I have a large select dropdown form which is repeated in 2 places. The only thing that changes is the first select tag, which has a different function.

<select name="name1" ng-change="functionOne('function1')" id="the-id-1">
<select name="name2" ng-change="functionTwo('function2)" id="the-id-2">
  <option value="aaa">aaa</option>
  <option value="bbb">bbb</option>
  <option value="ccc">ccc</option>
</select>

I tried using ng-hide ng-show however there must be a different way to accomplish this.
var app = angular.module('myApp', [])

.directive('termsForm', function() {
    return {
        templateUrl : "termsForm.html",
        restrict    : "E",
        scope       : false,
        controller  : 'TermsFormController'
    }
})

.directive('selectOptions', function() {
    return {
        templateUrl : "form.html",
        restrict    : "E",
        scope       : false
    }
})

.controller('TermsFormController',
['$scope',
function($scope) {
    var vs = $scope;
    vs.hello = "This is the form.";
    vs.showingSimple = true;
    vs.showingAdvanced = false;

    vs.showForm = function(type) {
      if (type === 'simple') {
        vs.showingSimple = true;
        vs.showingAdvanced = false;
      } else if (type === 'advanced') {
        vs.showingSimple = false;
        vs.showingAdvanced = true;
      }
    }

    vs.functionOne = function(msg) {
      alert(msg);
    }

    vs.functionTwo = function(msg) {
      alert(msg);
    }
}]);

termsForm.html

  <button class="btn btn-info" ng-click="showForm('simple')">Simple</button>
  <button class="btn btn-info" ng-click="showForm('advanced')">Advanced</button>

The select:

Simple

  <select-options></select-options>

Advanced

  <select-options></select-options>

A: You already have a directive created for your select, that gets you half way there. Now you just need to pass the function in through whats known as the isolated scope.
.directive('selectOptions', function() {
    return {
        templateUrl : "form.html",
        restrict    : "E",
        scope       : {
          changeFunc: '&'
        }
    }
})

This allows you to pass in the function you want to call on the ng-change event:
<select-options changeFunc="function1"></select-options>
<select-options changeFunc="function2"></select-options>

And then in your form.html you simply put
<select name="name2" ng-change="changeFunc()" id="the-id-2">

This way you are basically passing the funciton in as a parameter. Read this blog for a great guide on isolated scopes.

A: I would just refactor your markup and controller to adapt based on the simple/advanced context.
In your controller, you'd expose a 'generic' on change function for the dropdown, first...
(function () {
    'use strict';

    angular.module('app').controller('someCtrl', [someCtrl]);

    function someCtrl() {
        var vm = this;
        vm.isSimple = true;
        vm.nameChange = function () {
            if(vm.isSimple)
                functionOne('function1');
            else
                functionTwo('function2');
        }

        // Other things go here.
    }
})();

...Then, on your view, your select would change to this*:
<select id="someId" name="someName" ng-change="vm.nameChange()" />

*: Assuming you're using controllerAs syntax, that is.  If you're not, don't prepend the vm. on the select.


text:
Q: Kafka Stream 2.3 DeserializationExceptionHandler Error: Inside Custom DeserializationExceptionHandler in Kafka Stream DSL
1.While accessing Processor context inside custom Deserialization Exception handler. For Some Poison Pills ->Error : java.lang.IllegalStateException: This should not happen as partition() should only be called while a record is processed.
(As if this context object is shared?) AND Sometimes the Header information inside Processor context is from previous messages(Thread leak).
And while restarting the Kafka Stream ,some of these poison pills are consumed again.
Note:My response is always to continue in overriden handle method.
Could anyone explain this unusual behavior?Is it a bug in Kafka 2.3 DSL?
Any Suggestions would be of great help.


text:
Q: Return only capitalised names from a SQL query I have a table storing first names and surnames; some may be stored with capitalisation. Is there a query I could use to return only those rows with capitalisation?
For instance, if I have the following entries:
firstname  | surname
-----------+-----------
Bob        | Jones
john       | bobbins

I'd only expect to be returned the record for "Bob Jones".
I'm sure it's not a difficult thing to do, but I haven't been able to find any examples anywhere.

A: Compare the value with the value where the first character is upper-case:
select *
from the_table
where firstname = initcap(firstname)
  and surname = initcap(surname);

The function initcap() converts the first letter of each word to upper case and the rest to lower case.


text:
Q: Shell written in C has Output Redirection Error: segmentation fault I'm trying to complete my output redirection function for a C shell assignment. However, when entering a command such as: echo hello world > test.txt my shell exits with a segmentation fault that I suspect to be the line: args[i] = strtok(NULL," ") I don't believe I am NULL terminating the argument array correctly.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "execute.h"
#include "parser.h"

#define ReadFd 0
#define WriteFd 1

void outred(char ** args, char * filename, int pos){

   pid_t pid;
  int fd[2];//array of two for each file descriptor

  int buffer_size = BUFFSIZE;
  int status;

  //only want tokens before the ">" metacharacter
  int i;
  for(i = 0; i < pos; i++;){
    args[i] = args[i];
  }
  args[i] = strtok(NULL," ");

pid = fork();

  if(pid == 0){//If in child process execute the cmd to write to the file

 close(fd[ReadFd]);//child recieves fds from parent
 fd[WriteFd] = creat(filename, 0644);//create file

 dup2(fd[WriteFd],fileno(stdout));//duplicate write end to stdout, output to stdout goes to write end instead

 close(fd[WriteFd]);//new execution will write to stdout which is being redirected to fd[WriteFd] so it can be closed

    execvp(args[0],args);//execute cmd on args

  }

  if(pid < 0){
    perror("ERROR: output redirect failed");//no execution
    exit(0);
    }

  if(pid > 0){
    close(fd[WriteFd]);
    wait(&status);

  }
}


text:
Q: jCarousel load content with ajax I made a jCarousel on my home page with all the feature products, but if the feature products are 100 in number the home page will load very slowly so I decided I will load the content with ajax, I'm using ASP.NET MVC 3.0 with razor view engine. This is my actually code:

            @foreach (var item in Model.Products)
            {

                        @Html.Partial("_ProductSmallBox", item)

            }

and using css to show the carousel correctly. I don't know how to make an ajax call to load the content.


text:
Q: What is the quickest and most effective way to edit a "List<>" that has already been filled with data from a "DataGrid.ItemsSource"? I have a DataGrid that is related to the book specifications. Inventory is one of these specifications. To avoid user error, I automatically calculate the Inventory of that book based on its ISBN and save these changes in the Access database after removing each row.
The value of the IsReadOnly property of the Inventory column in the DataGrid is set to True.
So, if I'm not mistaken, after deleting each row, we have two choices: reload the database data in the BookDataGrid.ItemsSource or change the changes made, which are saved in a List<>, and then transfer them into the BookDataGrid.ItemsSource.
The following codes are related to removing the row from BookDataGrid and then saving it to the database:
    OleDbConnection OleDbConnect = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + System.Windows.Forms.Application.StartupPath + @"\Database.accdb");
    DataView BookDataView = new DataView();
    public MainWindow()
    {
        InitializeComponent();
        BookDataView = BookDataGrid.ItemsSource as DataView;
    }
    private void DataGridDeleteMenu_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        List<object> Rows = new List<object>();
        for (int i = 0; i < BookDataGrid.Items.Count; i++)
        {
            Rows.Add(BookDataGrid.Items[i]);
        }
        uint[] BookCodeSelectedItems = new uint[BookDataGrid.SelectedItems.Count];
        string[] ISBN_Value = new string[BookDataGrid.SelectedItems.Count];
        int j = 0;
        foreach (DataRowView DRV in BookDataGrid.SelectedItems)
        {
            BookCodeSelectedItems[j] = uint.Parse(BookDataView.Table.Rows[BookDataView.Table.Rows.IndexOf(DRV.Row)][3].ToString());
            ISBN_Value[j] = BookDataView.Table.Rows[BookDataView.Table.Rows.IndexOf(DRV.Row)][14].ToString();
            j++;
        }
        for (int i = 0; i < BookDataGrid.SelectedItems.Count; i++)
        {
            Rows.Remove(BookDataGrid.SelectedItems[i]);
        }
        OleDbCommand OleDbCommand_Delete = new OleDbCommand();
        OleDbCommand_Delete.Connection = OleDbConnect;
        OleDbConnect.Open();
        for (int i = 0; i < BookCodeSelectedItems.Length; i += 210)
        {
            OleDbCommand_Delete.CommandText = string.Join(null, "Delete From BookTable Where BookCode In (", string.Join(",", BookCodeSelectedItems.Skip(i).Take(210)), ")");
            OleDbCommand_Delete.ExecuteNonQuery();
        }
        OleDbConnect.Close();
        string[] UniqueISBN = ISBN_Value.Distinct().ToArray();
        OleDbCommand OleDbCommand_Update = new OleDbCommand();
        OleDbCommand_Update.Connection = OleDbConnect;
        OleDbConnect.Open();
        for (int i = 0; i < UniqueISBN.Length; i++)
        {
            OleDbCommand_Update.CommandText = string.Join(null, "Select Count(*) From BookTable Where ISBN = ", UniqueISBN[i]);
            OleDbCommand_Update.CommandText = string.Join(null, "Update BookTable Set Inventory = ", (int)OleDbCommand_Update.ExecuteScalar(), " Where ISBN = ", UniqueISBN[i]);
            OleDbCommand_Update.ExecuteNonQuery();
        }
        OleDbConnect.Close();
        BookDataGrid.ItemsSource = Rows;
    }

I don't mean convenience when I say quickest and most efficient, but rather quick execution and low RAM usage.
I can reload the database in BookDataGrid.ItemsSource using the following method, but I think changing the List<object> (I'm referring to Rows, which is defined in line 10) is faster and uses less RAM than restoring the database, but I don't know exactly how to do it.
If the database is large, the following method will take a long time and will consume a lot of RAM:
    public void BookDatagridRefresh()
    {
        DatabaseDataSet Database_DataSet = ((DatabaseDataSet)TryFindResource("Database_DataSet"));
        DatabaseDataSetTableAdapters.BookTableTableAdapter BookTable_TableAdapter = new DatabaseDataSetTableAdapters.BookTableTableAdapter();
        BookTable_TableAdapter.Fill(Database_DataSet.BookTable);
        BookDataGrid.ItemsSource = Database_DataSet.Tables["BookTable"].DefaultView;
    }

I think that something like this would be quicker than reloading:
To view the link, click here
However, the following link may also assist in answering this question:
To view the link, click here
I use the following tools:
.NET Framework 4.5.2, WPF
Thanks


text:
Q: Manifest spec/impl vs pom's version Well,

Package version numbers are present to identify differences
  between the specification and the implementation, i.e. bugs.

http://docs.oracle.com/javase/7/docs/technotes/guides/versioning/spec/versioning2.html
Assuming a vendor has a spec- and a impl- version offered.
Questions:

*

*Can a Maven spec-version be released twice when the impl is different?

*Why is no support for a optional spec-version in Maven?

*Does that mean i should use Spec-versions in Maven to keep beeing state of the art?

A: Maven and Java- Spec/Impl versions are slightly different concepts. They can be made to work with each other, however, it takes some effort.
Maven's multi-module approach encourages splitting modules into api (or spec) and implementation modules. So, to use the java versions, you would have to:

*

*split your module into two modules, e.g. my-module-api and my-module-impl

*define one or more properties inside your impl modules, pointing to the correct spec coordinates (version, and possibly groupId and artifactId as well)

*have your manifest file either filtered or configuring the archiver to create the entries

*(optionally) creating a shade artifact combining api and implementation (this somewhat negates the advantages of splitting your modules, however)

Look at the following example (I have ommited some best practices such as dependencyManagement for brevity's sake:
Specification Module:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.blackbuild.maven.demo.specimpl</groupId>
  <artifactId>module-spec</artifactId>
  <version>1.0</version>

  <name>Module Demo Specification</name>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-jar-plugin</artifactId>
          <version>2.4</version>
          <configuration>
            <archive>
              <manifest>
                <!-- This is an API project, use only specification entries -->
                <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
              </manifest>
            </archive>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

Specification Manifest:
Manifest-Version: 1.0
Built-By: xxx
Build-Jdk: 1.6.0_27
Specification-Title: Module Demo Specification
Created-By: Apache Maven 3.0.5
Specification-Version: 1.0
Archiver-Version: Plexus Archiver

Implementation Module
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.blackbuild.maven.demo.specimpl</groupId>
  <artifactId>module-impl</artifactId>
  <version>1.5-SNAPSHOT</version>

  <name>Module Demo Implementation</name>

  <properties>
    <!-- Define specification coordinates -->
    <spec-title>Module Demo Specification</spec-title>
    <spec-vendor>Spec Provider</spec-vendor>
    <spec-version>1.0</spec-version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>com.blackbuild.maven.demo.specimpl</groupId>
      <artifactId>module-spec</artifactId>
      <version>${spec-version}</version>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-jar-plugin</artifactId>
          <version>2.4</version>
          <configuration>
            <archive>
              <manifest>
                <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
              </manifest>
              <manifestEntries>
                <Specification-Title>${spec-title}</Specification-Title>
                <Specification-Version>${spec-version}</Specification-Version>
                <Specification-Vendor>${spec-vendor}</Specification-Vendor>
              </manifestEntries>
            </archive>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

Implementation Manifest:
Manifest-Version: 1.0
Implementation-Title: Module Demo Implementation
Implementation-Version: 1.5-SNAPSHOT
Implementation-Vendor-Id: com.blackbuild.maven.demo.specimpl
Built-By: xxx
Build-Jdk: 1.6.0_27
Specification-Vendor: Spec Provider
Specification-Title: Module Demo Specification
Created-By: Apache Maven 3.0.5
Specification-Version: 1.0
Archiver-Version: Plexus Archiver

Consequences:
Of course, you have to release both modules individually.
Back to your questions:

*

*Can a Maven spec-version be released twice when the impl is different?

With this model, you can have different implementations for the same specification, as long as they have different coordinates themselves (different versions, usually).

*

*Why is no support for a optional spec-version in Maven?

Maven uses a single coordinate pre artifact, spec version is implemented by using dependencies. In normal workflow, you are either interested in spec version or in the implementation version, but rarely in both at the same time. You can assure that the implementation matches the specification by using dependencyManagement and enforcer rules, if necessary

*

*Does that mean i should use Spec-versions in Maven to keep beeing state of the art?

No, I think the api/impl model of Maven is more widely used.
One more thing...
In this model, there is no way to read the specification version from the implementation (without looking into the Manifest).
You could use a {spec-version}_{impl-version} versioning scheme to resolve this, for the above example, impl-version could be 1.5_1.0.0-SNAPSHOT, however this makes version numbers much harder to read.

A: *

*
Can a Maven spec-version be released twice when the impl is different?

Yes, this is possible, because spec and impl-version value are defined by user.

*
Why is no support for a optional spec-version in Maven?

Maven has options for disabling Specifications and Implementations, so both are optional

*

*addDefaultSpecificationEntries

*addDefaultImplementationEntries
Read about Adding Implementation And Specification Details

Starting with version 2.1, Maven Archiver no longer creates the Implementation and Specification details in the manifest by default. If you want them in your manifest you have to say so explicitly in your configuration.

With Manifest Entries is possible to override default values.
Specification-Title: ${project.name}
Specification-Version: ${project.version}
Specification-Vendor: ${project.organization.name}
Implementation-Title: ${project.name}
Implementation-Version: ${project.version}
Implementation-Vendor-Id: ${project.groupId}
Implementation-Vendor: ${project.organization.name}

*
Does that mean i should use Spec-versions in Maven to keep beeing state of the art?

In my opinion JDK versioning is rarely used, common pattern is to use proper versioning for maven artifacts.
References:

*

*http://maven.apache.org/shared/maven-archiver/index.html

*http://docs.oracle.com/middleware/1212/core/MAVEN/maven_version.htm


text:
Q: If pmf is given how do I find estimator using moment method? So, the pmf for $X_1, X_2, ..., X_n$ is given as : $f(x) = \theta x^{\theta - 1}, \ \ if x \in ]0,1[ \text{ and } 0 \text{ otherwise.}$
So I try to find first moment: $E[x] = \int^1_0 x\theta x^{\theta -1} dx =x^{\theta +1} - \theta \int^1_0 x ^{\theta-1} dx = x^{\theta + 1} - 1  $
And $\bar{x} = \frac{1}{n} \Sigma_1^n x_i$. Then from there $x^{\theta+1} = \frac{1}{n} \Sigma_1^n x_i + 1 \Rightarrow  \theta = \ln(\frac{1}{n} \Sigma_1^n x_i + 1  - x)  - 1$
This is confusing and most probably incorrect, so where is my mistake and how should I solve this problem?
$$\frac{\hat{\theta}}{\hat{\theta}+1} = \frac{1}{n} \Sigma_1^n x_i \\ \hat{\theta} = \frac{\hat{\theta}+1}{n}\Sigma^1_0 x_i = \frac{1}{n} \left(\hat{\theta} \Sigma^1_0 x_i + \Sigma^1_0 x_i\right) \\ \hat{\theta} - \frac{\hat{\theta}}{n}\Sigma^1_0 x_i = \frac{1}{n} \Sigma_0^1 x_i \\ \hat{\theta} \left(1-\frac{1}{n}\Sigma^1_0 x_i   \right) = \frac{1}{n} \Sigma^1_0 x_i \\ \hat{\theta} = \frac{\bar{x}}{1-\bar{x}}$$

A: Note that this would be a beta distribution such as the one in here with $\alpha = \theta$ and $\beta = 1$.
First, consider that $E[x] = \int_0^1x\theta x^{\theta-1} dx= \theta \int_0^1x^\theta dx=\frac{\theta}{\theta+1} x^{\theta+1}|_0^1 = \frac{\theta}{\theta+1}$.
Then you can find $\hat{\theta}$ using the method of moments such that $\frac{\hat{\theta}}{\hat{\theta}+1} = \frac{1}{n} \sum_{i=1}^n x_i$.


text:
Q: Support library version I try to inject support libraries into my Android Studio project.
If I try anything lower than 20 it says:
library should not use a lower version then targetSdk version.
If I use compile 'com.android.support:support-v4:20' I get:
Failed to find: com.android.support:support-v4:20
If I use   compile 'com.android.support:support-v7:20.0.+' I get:
Avoid using + in version numbers, can lead to unpredictable and unrepeatable builds.
So the simple question is:
where can I find up-to-date, ready to use, version numbers that Do work?

A: To see the current Android Support Library revision number ...

*

*Android Studio > Tools > Android > SDK Manager ...

*Extras > Android Support Library: See the Rev. number e.g. (21.0.3).

For a quick insertion of the right revision number when in your gradle file you currently have something like 'com.android.support:appcompat-v7:21.0.+' with the 'Avoid using + in version numbers ...' warning, use the relevant IntelliJ Inspection ...

*

*Place your cursor over 'com.android.support:appcompat-v7:21.0.+' (anywhere in the colored section of the warning).

*Alt + Enter > "Replace with specific version".

There are plans to include the latest specific version number in the warning. See Issue 78737:     Have the "Avoid using + in version numbers" gradle library warning suggest the version currently in use.

A:
If I try anything lower than 20 it says: library should not use a lower version then targetSdk version.

That is because you set your targetSdkVersion to something higher than 19. If you did so intentionally, fine. If you did not do so intentionally, consider dropping it back to 19 for now, and use compile 'com.android.support:support-v4:19.1.0' (if you are using the backport of fragments) or compile 'com.android.support:support-v13:19.1.0' (if you are not using the backport of fragments).

If I use compile 'com.android.support:support-v4:20' I get: Failed to find: com.android.support:support-v4:20

That is because the Android Support package uses X.Y.Z semantic versioning, as do most artifacts in repositories. 20 does not match the X.Y.Z pattern.

If I use compile 'com.android.support:support-v7:20.0.+' I get: Avoid using + in version numbers, can lead to unpredictable and unrepeatable builds.

That is merely a warning. If you are using version control for your project files, and you feel that it is important to be able to check out some earlier version of your code and be able to reproduce that build, then using the + notation is not a good idea. OTOH, if being able to reproduce historical builds is not essential, using the + wildcard, as you are doing, ensures that you get updates automatically. Having the + in the third position (Z in X.Y.Z) means that you will automatically get patchlevel updates.

where can I find up-to-date, ready to use, version numbers that Do work?

On your hard drive, in $ANDROID_SDK/opt/extras/android/m2repository/com/android/support/$LIBRARY/, where $ANDROID_SDK is wherever you installed the Android SDK and $LIBRARY is whichever Android Support package library you are interested in (e.g., support-v13).

A: you can get the version list of support-v4 at here: \sdk\extras\android\m2repository\com\android\support\support-v4

A: You can see the versions at Google's Maven Repository. Just find the item entry com.android.support and click the plus to expand it. Scroll down and click on any artifact such as support-v13 and you'll see folders named after the version number.

A: This will work:
    apply plugin: 'com.android.application'

android {
    compileSdkVersion 20
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "com.example.myApp"
        minSdkVersion 19
        targetSdkVersion 20
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }

    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile 'com.android.support:support-v4:20.0.0')
}


text:
Q: How to keep Label style set in client-side during Postback Asp.net 4.0 webform web application...
I'm trying to wrap my head around this scenario and wanted to throw this out there to obtain an explanation.
On my page, I have an HTML table. In one of the cells, I have a checkbox that performs some functionality on the server-side when clicked. This has been in place. What I am trying to do is to perform manipulation of controls (styling, disabling, etc.) when this checkbox is clicked and then continue with the server-side call.
Here's a snipet:

                Team

                Primary Contact

                Status

                Type

            <asp:CheckBox ID="chkShowFavorites" runat="server" Text="Show Favorites"
                ForeColor="White" OnCheckedChanged="FavCheckChange" onclick="HighlightControls()"
                AutoPostBack="True" />

...
...
...

javascript

This is going to be expanded to include more controls than this one but I'm just trying to see what my options are before developing too much.
During debugging I see the label turn red but then returns to white after postback.
How can I perform my styling in the client-side and keep the settings after postback?

A: Any changes to your DOM elements (css classes, styles) will be lost between postbacks unless you find a way to persist it. You could use a hidden field to store the elementID + the new class name or style so when you post back, your code can interrogate the hidden field and perform the necessary changes.

A: The only thing that I can think of would be to interrogate the control state on the server side when the page is posted back and apply the same logic that you are applying client side.
So if you have a checkbox that when checked changed a cell to be red, you will need to write some server side code to check the value of that check box and then change the color of the cell.
Its either that or could you replace your postback with an ajax call and only update the parts of the form that need to be changed?


text:
Q: Arrays appended inside function not working in other class My problem is that I have 4 empty arrays:
var Names:[String] = []
var Amounts:[Int] = []
var Dates:[NSDate] = []
var Images:[UIImage] = []

Inside a class NewPersonViewController.
I also have a function inside NewPersonViewController:
func create(){
   Names.append(nameField.text)
   Amounts.append(amountField.text.toInt()!)
   Dates.append(dateToBePaid.date)
}

I call create() when a button is pressed. The function is just a button action, declared inside NewPersonViewController.
My problem: When I print out the arrays in another class (which is in another file) not including Images, I just get this:
[]
[]
[]

Yup, thats my output. Thank you in advance. Side note: I am new to swift :)

A: Unless you have just posted some toy code, it seems like there are a lot of problems with your design.
However, the specific problem you may be facing is that, in Swift, Arrays are "value types". Basically it means that if you pass around an Array, Swift is actually making copies every time. So if you edit copy 2 in a different class, it does not affect copy 1 in your original class.
If you just want to get your code working without refactoring to deal with this (and you should really refactor), the easiest thing to do is use NSMutableArray instead of Swift arrays. NSMutableArray is a class, which is a "reference type". You can pass that all around, make changes, and use it from anywhere. Because you are really only passing a "reference", there is only ever one array, and changes you make show up everywhere.

A: I'm relatively new here but if you move the arrays out of the ViewController they will become GLOBAL variables and accessible in any other View or Table Controller.  I just tried it and it worked just fine.
For Global variables I have always added a prefix of "gl_" so I know for a fact this is a global variable which means they need to be used with care.  In general, global variables are risky and IMHO should be used frugally and consider any risks that come from using them...especially security risks.
In my ViewController.swift file:

import UIKit

var gl_Names:[String] = []
var gl_Amounts:[Int] = []
var gl_Dates:[NSDate] = []
var gl_Images:[UIImage] = []

class ViewController: UIViewController {

    @IBOutlet weak var textInput1: UITextField!

    @IBOutlet weak var textInput2: UITextField!

    @IBOutlet weak var textInput3: UITextField!

etc etc


text:
Q: What is missing (if anything) from this SQL statement? SELECT EXTRACT(YEAR FROM created_at) AS yr, count(*) AS users_count
FROM users;

I'm new to SQL (so new that I can't find anything wrong with this). There may not be, and it may be a trick question. Would appreciate feedback!

A: You should use "Group BY" function too, because you use COUNT function with an another column.
For example:
SELECT EXTRACT(YEAR FROM created_at) AS yr, count(*) AS users_count FROM users group by YR;


text:
Q: Combobox dropDown selected I have a ComboBox which also gets controlled by two buttons. But I would like to separate the execution from using the ComboBox dropdown and the buttons.
comboBox3.DropDownClosed += (b, f) =>
{
    week = Convert.ToInt16(comboBox3.Text);
    Console.WriteLine(week);
};

I tried this approach but it seems to be not updating the week when the dropdown gets closed and selecting another value.

A: If you want to do something when user changes the selected index of the ComboBox, you need to handle SelectionChangeCommitted event (and not SelectedIndexChanged):

The SelectionChangeCommitted event is raised only when the user changes
  the combo box selection, and you can create a handler for this event
  to provide special handling for the ComboBox when the user changes the
  selected item in the list.

In the other hand, SelectedIndexChanged will raise whenever the user or code changes the selected index.
So, instead of handling SelectedIndexChanged, you should write different methods to do different things, for example, handle Button1.Click and call Action1, handle Button2.Click and call Action2 and handle ComboBox.SelectionChangeCommitted to detect when user changes the selected index and call Action3.


text:
Q: pandas gather first not null values from different columns on the same index I have queried a huge table where majority of the rows in each columns are null (None) for each single id (there are multiple rows for each id). I want to squash these so I'll have one row per id
I'll provide a mock example of the input:
    id  var1  var2
0   1  None  None
1   1  None     x
2   2  None     k
3   3  None  None
4   1  None  None
5   1     y   NOT
6   3     p  None
7   2    ss  None
8   2  None  None

And here would be the mock example of the output:
    id var1  var2
0   1    y     x
1   2   ss     k
2   3    p  None

Note how "NOT" from var2 column did not make it, because it's the second non-null value for id==1.
The following snippet works if there are only one value for each id:
df = df.set_index('id')
cs = [df[col].dropna() for col in df]
pd.concat(cs, axis=1)

But if there are multiple values (such as NOT in the example), this throw an error.
Is there an easy way to aggregate the first not null value for each column for each id? Thanks.
Here's the mock example pandas dataframe, I'll have a lot more columns and rows for the real dataframe:
df = pd.DataFrame([[1, None, None],[1, None, "x"],[2, None, "k"],[3,None, None], [1, None, None], [1, "y", "NOT"], [3, "p", None], [2, "ss", None], [2, None, None]])

A: idColumnName = 'id' # Define id column name
def funcGroup(x): # Define grouping function
    columns = [x for x in x.columns if x!=idColumnName] # Get columns that are not id column
    dictValues = {} # Init a dictionary
    for col_ in columns: # For each column ...
        nonNullValues = x.loc[~x[col_].isnull(), col_] # Get non null values
        firstNonNullValue = np.nan # Init result value as null
        if nonNullValues.shape[0]>0: firstNonNullValue = nonNullValues.iloc[0] # If there are not null values return first
        dictValues[col_] = firstNonNullValue # Fill the dictionary
    return pd.Series(dictValues, columns) # Return a pandas Serie

df.groupby([idColumnName]).apply(funcGroup).reset_index() # Group by your id column and apply defined function

A: You can check with first : first not null value will be returned
df.groupby(0).first().reset_index()
Out[582]:
   0     1     2
0  1  None  None
1  2  None     k
2  3  None  None