Q:

Notice: Object of class mysqli_result could not be converted to int and Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean

the code is for inserting user data in database
getting error on
$run = mysqli_query($con,$check_email);

Notice: Object of class mysqli_result could not be converted to int

and

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean

    <?php
    $con = mysqli_connect("localhost","root","","users_db");
    if (mysqli_connect_errno())
    {
    echo 'connection was not established'. mysqli_connect_error();
    }

        if(isset($_POST['submit'])){
             $user_name = $_POST['name'];
             $user_pass = $_POST['pass'];
             $user_email = $_POST['email'];

             if($user_name==''){
                 echo "<script>alert('please Enter your Nmae!')</script>";
                 exit();
             }
             if($user_pass==''){
                 echo "<script>alert('please Enter your password!')</script>";
                 exit();
             }
             if($user_email==''){
                 echo "<script>alert('please Enter your Email!')</script>";
                 exit();
             }

                 $check_email = "select * from users where user_email='$user_email'";

                $run = mysqli_query($con,$check_email);
                if(mysqli_num_rows($run>0)){
                    echo "<script>alert('Email $user_email is already exist in database please try another one')</script>";
                    exit();
                }
                $query = "insert into users(user_name,user_pass,user_email) values ('$user_name','$user_pass','$user_email')";
                if(mysqli_query($con,$query)){

                    echo "<script>alert('Registration completed')</script>";
                }
                else{
                    echo"<script>alert('Data not inserted')</script>";
                }

             }
    ?>

A:

Syntax is wrong
if(mysqli_num_rows($run>0)){

this should be
if(mysqli_num_rows($run) > 0){
                          ^ should be moved

This should fix both the errors.


Q:

Making .NET configuration environment-neutral

I want to get some thoughts on best practices around making .NET app configuration environment-neutral.
Background. Some background first. I come from the Java world, not the .NET world, and in Java there are certain things that we can do to build packages that are environment-neutral. They are generally based on abstracting the configuration in some fashion. Here are a few examples:

JNDI allows apps to reference enterprise resources (e.g., databases, JavaMail sessions, JCR repositories, etc.) by name, and then the name is mapped to a specific configuration according to the environment (dev, test, prod).
Another example would be properties files. You might have a bunch of properties (e.g., "encryption_key", "smtp.server.url", "admin.email", etc.) that the app grabs from a properties file in a known location when the app starts up. The property keys are mapped to different values depending again on the environment.
Some app development frameworks (like Spring) know how to pull properties files in so the properties can be integrated with the framework configuration.

Another approach I've seen in Java is a build-time approach, where you use Ant (token substitution) or Maven (build profiles) to build environment-specific packages. I don't like this approach quite as much just because I strongly prefer to deploy exactly the same package to test and prod. But it's an approach I've seen.
Desired solution. I'm assuming that in .NET there are some comparable strategies for decoupling a configuration (and by extension the containing package) from its environment.
Ideally I'd like a solution that allows me to keep non-environmental configuration closely associated with the app, externalizing only the environmental stuff. To go back to the Java examples, a lot of times the "configuration" is really something that the developers control, such as including a Sitemesh servlet filter for page decorations, dependency injection or app wiring, mapping such-and-such MVC controller method to a request URI, etc. That stuff I don't want to be externalized. But encryption keys, DB connection strings, log levels and so forth, yes.

A:

.NET executables and web applications by default implement .config files which do exactly what you describe.  There's an entire namespace, System.Configuration, that deals with .config files.
Go look for reference material on App.config and Web.config.  App.config is a generic term for an executable's default config file, which is named foo.exe.config, where foo.exe is the name of the executable.  Web.config applies to web applications.
This seems to be a decent primer on App.config.


Q:

Can't excute a function when i click on li element

I have an HTML list like this:

2014

2015

2015

when I click on "2014" for example, I need to hide other list and show only the clicked one then pass this year to php file, catch this year and connect to a database baking with other data related to this year then list this new data at the end of list, and I tried this:
jQuery part:

test.php:
if(isset($_POST['p']){
$year=$_POST['p'];
$db_connection=new mysqli(localhost,USER,PASS) ;
$query="select*from user.info where year=$year" ;
$db_connection->query($query);
$rows=$db_connection->num_rows;
for($i=0;$i<$rows;$i++){`
$result->data_seek($rowP);
$result->fetch_assoc()["col_1"];
$returned_data.="
$result
";
}
echo "$returned_data";
}

All of this work well and the data show up in the web page but the last part of script doesn't work and nothing happen when i click on any element of this list. Is the reason because the
 coded by php or what?.. Thanks for help.

A:

just move $(".col_1").click(function(){ inside Success function in ajax

$('.year').click(function(){
  debugger;
  var path=$(this).text();
  $(".year").toggle(200);
  $(this).toggle(200);
  $.post("test.php",{p:path},function(data){
    $(".years").append(data);
    $(".col_1").click(function(){
    //alert();
    });
  });
});

2014

2015

2015


Q:

Replacing column values in R

Example df:
index    name    V1    V2   etc
1        x       2     1
2        y       1     2
3        z       3     4
4        w       4     3

I would like to replace values in columns V1 and V2 with related values in name column for particular index value. Output should look like this:
index    name    V1    V2   etc
1        x       y     x
2        y       x     y
3        z       z     w
4        w       w     z

I have tried multiple merge statements in loop but not sure how I can replace the values instead of creating new columns and also got a duplicate name error.
V<-2 # number of V columns
names<-c()
for (i in 1:k){names[[i]]<-paste0('V',i)}
lookup_table<-df[,c('index','name'),drop=FALSE] # it's at unique index level

for(col in names){
df<- merge(df,lookup_table,by.x=col,by.y="index",all.x = TRUE)
}

A:

We can do
df[3:4] <- lapply(df[3:4], function(x) df$name[x])

Or without looping
df[3:4] <- df$name[as.matrix(df[3:4])]
df
#  index name V1 V2
#1     1    x  y  x
#2     2    y  x  y
#3     3    z  z  w
#4     4    w  w  z

data
df <- structure(list(index = 1:4, name = c("x", "y", "z", "w"), V1 = c(2L,
1L, 3L, 4L), V2 = c(1L, 2L, 4L, 3L)), .Names = c("index", "name",
"V1", "V2"), class = "data.frame", row.names = c(NA, -4L))


Q:

Rails Display Current Facebook Share Count

so I'm trying to display the current facebook share count in a Rails application. I keep getting the "can't convert string to text" error when trying to grab the current URL in my Rails app.
The code works if I put in something like facebook_shares("http://www.google.com")
The code does not work if I use facebook_shares("#{request.protocol}#{request.host_with_port}#{request.fullpath}")
Not sure how to fix this problem
Here is my current code...
helper.rb:
def facebook_shares(url)
    data = Net::HTTP.get(URI.parse("http://graph.facebook.com/?ids=#{URI.escape(url)}"))
    data = JSON.parse(data)
    data[url]['shares']
end

view.html.erb:
<% current_url = "#{request.protocol}#{request.host_with_port}#{request.fullpath}" %>
<%= facebook_shares(current_url) %>

When I run this I get a "can't convert string into integer" error. It works if I do the code below:
<% current_url = "http://www.google.com" %>
<%= facebook_shares(current_url) %>

Super lost...

A:

I figured it out. This was a horrible oversight by myself :p.
I'm in development running on a local server, so I'm pulling localhost:3000/something.
Pushing this and running the function in production works fine. Sorry everyone, but thanks for the help!


Q:

Is there a way to create a searchable picklist in a visualforce page?

I have a picklist field and I was wondering if there is a way to add a searchbox at the top of the picklist where we enter a picklist value and it searches through the picklist to find the values. Something like this:

A:

There is no standard component/way available to do this. You need to write your custom code to achieve it.
First you can use the dataList tag to achieve it.
<datalist id="browsers">
    <option value="Internet Explorer">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
  </datalist>

Or you can use third part JS like Select2.


Q:

Finding the fraction $\frac{a^5+b^5+c^5+d^5}{a^6+b^6+c^6+d^6}$ when knowing the sums $a+b+c+d$ to $a^4+b^4+c^4+d^4$

How can I solve this question with out find a,b,c,d
$$a+b+c+d=2$$
$$a^2+b^2+c^2+d^2=30$$
$$a^3+b^3+c^3+d^3=44$$
$$a^4+b^4+c^4+d^4=354$$
so :$$\frac{a^5+b^5+c^5+d^5}{a^6+b^6+c^6+d^6}=?$$
If the qusetion impossible to solve withot find a,b,c,d then is there any simple way to find a,b,c,d
Is there any help?

A:

One way to approach such questions is to view $a, b, c, d$ as roots of a single quartic equation $x^4-s_1x^3+s_2x^2-s_3x+s_4=0$, when we have Vieta's relations
$$s_1=a+b+c+d$$$$s_2=ab+ac+ad+bc+bd+cd=(a+b)(c+d)+ab+cd$$$$s_3=abc+abd+acd+bcd$$$$s_4=abcd$$
We then let $p_k=a^k+b^k+c^k+d^k$ with: $$p_0=4$$$$p_1-s_1=0$$$$p_2-p_1s_1+2s_2=0$$$$p_3-p_2s_1+p_1s_2-3s_3=0$$
With the given values of $p_1, p_2, p_3$ these determine $s_1, s_2, s_3$.
For higher powers $(k\ge4)$ we have $$a^k-s_1a^{k-1}+s_2a^{k-2}-s_3a^{k-3}+s_4a^{k-4}=0$$ using the quartic equation. Adding together the corresponding equations for $a , b, c, d$ we obtain the recurrence for $p_k$$$p_k-s_1p_{k-1}+s_2p_{k-2}-s_3p_{k-3}+s_4p_{k-4}=0$$
Since we know $p_4$ we can use the recurrence to find $s_4$, and this is then sufficient to compute $p_5, p_6$ from the recurrence.
If this looks complicated, this is misleading. The relations between the elementary symmetric functions $s_r$ and the sums of powers $p_r$ are useful to know, and render this kind of problem essentially mechanical. You can see that you can solve the problem without solving explicitly for $a, b, c, d$.

Following this scheme we find successively $s_1=2, s_2=-13, s_3=-14, s_4=24$. Then the recurrence gives:$$p_5-2p_4-13p_3+14p_2+24p_1=0$$ and$$p_6-2p_5-13p_4+14p_3+24p_2=0$$
And this gives $p_5=812, p_6=4890$

A:

Here's an approach which involves AM-GM inequality(To bound the numbers).
I have considered the positive values of $(a,b,c,d)$. I can consider $a^2,b^2,c^2$ and $d^2$, since they are all strictly positive.
$\dfrac{a^2+b^2+c^2+d^2}{4} \ge \sqrt{abcd}$
$\dfrac{30}{4} \ge \sqrt{abcd} \implies 56.25 \ge abcd$
Since $a^2+b^2+c^2+d^2=30$ and $56 >|abcd|$, One of the $|a|,|b|,|c|,|d|$ is at most $5$.
Considering $a^4+b^4+c^4+d^4$, one of the $|a|,|b|,|c|,|d|$ is atmost $4$, since $5^4=625$ .
Now we have $a^2+b^2+c^2+d^2=30$, the value of $(|a|,|b|,|c|,|d|)$ is from set  $(1,2,3,4)$.
And also:
Considering $4th$ degree polynomial such that $a,b,c,d$ are the roots of the equation.
$x^4+px^3+qx^2+rx+s=0$
$a+b+c+d=2=-p$
$(a+b+c+d)^2-a^2+b^2+c^2+d^2=2(ab+bc+cd+ad+ac+bd)=q=-13$
Finding $\sum abc$ and $abcd$ with the help of other inequalities and finding the roots of equation is another way to go. (Not quite sure whether constructing polynomial is a great way to go. )

Edit: I have considered the absolute values of $(a,b,c,d)$ . I didn't assume them to be $+ve$.


Q:

Displaying headers and footers in a PDF generated by Rotativa

I'm trying to specify headers and footers in a PDF generated by Rotativa library. As the author answered here it should be possible using CSS (described here). However, I'm not able to do this.
I have a stylesheet loaded in the meta tag:
<link href="print.css" rel="stylesheet" type="text/css" media="print" />

And in the stylesheet at the bottom:
@page {
    @top-left {
        content: "TOP SECRET";
        color: red
    }
    @bottom-right {
        content: counter(page);
        font-style: italic
    }
}

And then generating PDF by:
public ActionResult ShowPdf()
{
     var model = new Model();
     return new ViewAsPdf("view.cshtml", model)
                {
                    FileName = "Report.pdf",
                    CustomSwitches = "--print-media-type"
                };
}

And then nothing appears in the header and footer of the PDF. Any ideas?

A:

I've found a documentation of wkhtmltopdf and it is described there how to manage headers and footers.
Basically you can just add --header-center "text" (or similar switches) to the argument list and that's all.
So using it with Rotativa it would be:
public ActionResult ShowPdf()
{
     var model = new Model();
     return new ViewAsPdf("view.cshtml", model)
                {
                    FileName = "Report.pdf",
                    CustomSwitches = "--print-media-type --header-center \"text\""
                };
}

(I don't know if --print-media-type is necessary.)

A:

If you wanted to display a View instead of text in the header/footer then you can do so like this:
public ActionResult ViewPDF()
{
      string customSwitches = string.Format("--print-media-type --allow {0} --footer-html {0} --footer-spacing -10",
                Url.Action("Footer", "Document", new { area = ""}, "https"));

     return new ViewAsPdf("MyPDF.cshtml", model)
                {
                    FileName = "MyPDF.pdf",
                    CustomSwitches = customSwitches
                };
}

[AllowAnonymous]
public ActionResult Footer()
{
    return View();
}

Don't forget to add the  [AllowAnonymous] attribute on the Footer action otherwise Rotatina can't get access to the path.

A:

Here is how I did it (in full):
public ActionResult PrintPDF(int? selectedSiteRotaId, int selectedSiteId)
{
    string footer = "--footer-center \"Printed on: " + DateTime.Now.Date.ToString("MM/dd/yyyy") + "  Page: [page]/[toPage]\"" + " --footer-line --footer-font-size \"9\" --footer-spacing 6 --footer-font-name \"calibri light\"";

    return new ActionAsPdf("RenderPDF", new { selectedSiteRotaId = selectedSiteRotaId, selectedSiteId = 7 })
    {
        FileName = "PDF_Output.pdf",
        PageOrientation = Orientation.Landscape,
        MinimumFontSize = 10,
        //PageMargins  = new Margins(5,5,5,5),
        PageSize = Size.A3,
        CustomSwitches = footer
    };

    //var pdfResult = new ActionAsPdf("RenderPDF", new { selectedSiteRotaId = selectedSiteRotaId, selectedSiteId = 7 })
    //{
    //    FileName = "PDF_Output.pdf",
    //    PageOrientation = Orientation.Landscape,
    //    MinimumFontSize = 10
    //};

    //var binary = pdfResult.BuildPdf(this.ControllerContext);

    //return File(binary, "application/pdf");
}

public ActionResult RenderPDF(int? selectedSiteRotaId, int selectedSiteId)
{
    return RedirectToAction("Index", "PrintPDF", new { selectedSiteRotaId = selectedSiteRotaId, selectedSiteId = 7 });
}


Q:

jQuery datatable custom sorting and filtering

I am using jquery datatables in my MVC4 application. The most simple configuration of jquery datatables.
Infact, I have placed this small jquery snippet in my layout.cshtml file which will take care of all tables in my application without doing anything custom.
$(".dataTable").dataTable({
   "bJQueryUI": true,
   "sPaginationType": "full_numbers"
}).columnFilter();

this works perfectly when I format the table with
,
 and
.
Here's the image :
Ofcourse, not everything will work work with this basic configuration.

The problem
The payment status column contains not just some text, it contains a span and a hidden dropdown list. on click of , The span gets hidden and dropdown becomes visible. on dropdown change it reverts back to a visible span and hidden dropdown.
The code :

                Completed

           <select name:"paymentstatus"="" style="display:none;" onchange="changepaymentStatus($(this).parent().attr('paymentId'),$(this).val(),10);">
               <option value="0" selected="'selected'">Completed</option>
               <option value="1">Pending</option>
               <option value="2">Cancelled</option>
           </select>

With all this mess present in the  element, it is not able to filter at all (for that column and sorting works incorrectly (for that column).

A:

Hi take a look at this http://datatables.net/examples/plug-ins/sorting_sType.html this will do the job for you.


Q:

I am using RealVNC to connect from my Windows 7 x64 machine to Mac OSX Lion

I am using RealVNC to connect from my Windows 7 x64 machine to Mac OSX Lion.
The cursor I see on the Mac desktop is just a dot rather than a normal cursor. What setting have I missed that will give a familiar arrow cursor?

A:

On the viewer machine, check your options and make sure "View only (inputs ignored)" is not checked.


Q:

How do I use Ruby to connect to a SQLite3 database outside of Rails as a scripting language

Hi Im using Ruby as a scripting language. Not for web development, but to connect to a local database on my computer and manipulate it.
Id like to know how I can connect. Do I need to download/import tools? What do I need to get started?
Thanks,

A:

You need to install the sqlite3 gem:
gem install sqlite3

You can then use the library in your code. Here's an example, adapted from the project's README.rdoc file:
require 'sqlite3'

# Open a SQLite 3 database file
db = SQLite3::Database.new 'file.db'

# Create a table
result = db.execute <<-SQL
  CREATE TABLE numbers (
    name VARCHAR(30),
    val INT
  );
SQL

# Insert some data into it
{ 'one' => 1, 'two' => 2 }.each do |pair|
  db.execute 'insert into numbers values (?, ?)', pair
end

# Find some records
db.execute 'SELECT * FROM numbers' do |row|
  p row
end

A:

If you have knowledge on Rails apps, you would like to have those Models features on your app. And you can have it, using the ActiveRecord gem. Unless the data in your app is really simple and easy to query you should tink about use active record, or something like it.
Here are some links

http://www.agileadvisor.com/2008/01/using-activerecord-outside-rails.html
http://snippets.dzone.com/posts/show/3097


Q:

How to deal with non-exhaustive pattern matching?

I'm giving my function a list as a parameter but I know that it can ever be either empty list or list with one single element.
When I do pattern matching I get a warning about non-exhaustive patterns.
I can ignore it and the code works but what are some idiomatic ways of doing this?

A:

There are several techniques. (Some untested code follows.)
Restricting the domain
Instead of
useList :: [a] -> T

we can use a type for non-empty-lists:
useList :: NonEmptyList a -> T

Willem's answer already explains this.
Weakening the codomain
We can instead use
useList :: [a] -> Maybe T
useList (x:xs) = Just (...) -- as before
useList []     = Nothing

and make the pattern matching to be exhaustive. This is however less convenient for the caller who has to handle the Nothing case, which we might know to never happen.
Partial, but documented function
We can instead error out:
useList :: [a] -> T
useList (x:xs) = (...) -- as before
useList []     = error "useList: empty list"

This also makes the pattern matching to be exhaustive. It suppresses the warning, at the cost of producing a runtime error message, which we can customize.
In some cases, there is no pragmatic better alternative. For instance, assume we are using an algorithm to solve a complex task, and said algorithm keeps (or at least, should keep) an invariant where the list is always non empty. Then, instead of
useList :: [a] -> Int
useList (x:xs) = (...)
useList []     = -1          -- it never happens, so we can return anything

it is better to use
useList :: [a] -> Int
useList (x:xs) = (...)
useList []     = "useList: internal error -- non null list invariant broken!"

The latter makes it possible to detect a bug as early as possible.
GADTs proofs
Sometimes we can pass information using GADTs which help to make pattern matching exhaustive. For instance, one could use a type for tagged lists, where the tag represents the emptiness
data Tag = Empty | NonEmpty

data List (t :: Tag) a where
   Nil  :: List 'Empty a
   Cons :: a -> List t a -> List 'NonEmpty a

Then,
useList :: List 'NonEmpty a -> T
useList (Cons x xs) = ...

is exhaustive, even if we never handle the Nil case.
GHC also allows the "non emptiness proof" to be passed separately:
data IsNonEmpty (t :: Tag) where
   IsNE :: IsNonEmpty 'NonEmpty

useList :: IsNonEmpty t -> List t a -> T
useList IsNE (Cons x xs) = ...

is also considered to be exhaustive.


Q:

Linking Policies of copied Usecase in different space of IBM Blueworks Live?

I have created one Usecase and linked policies like BR and Error Msg to that Usecase. Then I copied that Usecase to another space.
My trouble is that the copied Usecase is linked to the policies of a different space.  How can I use policies in the same space and link to those?

A:

When you say "Usecase" I assume you are talking about a Process Blueprint.
If you copy a Process Blueprint, only the process is copied. None of the linked assets like Policies are going to be copied with it, so the copy will point to the same Policy as the original.
If instead you want to create copies of everything, you can copy the space instead of just copying the process.  Assuming all the linked assets (i.e. Policies) are in the same space as your process, this will create copies of everything and the copy of your process will be correctly linked to the copy of the policies.
If all the assets are not in the same space, one workaround is to temporarily move the items you are wanting to copy into a temp space, copy that temp space and then move everything back to the original location.


Q:

Error ReportViewer 14.0.0.0 Window.$RSjQuery

Ao clicar no botão para expandir grupos no reportview, ele fica carregando eternamente e dá erro na linha abaixo:
// error Uncaught TypeError: window.$RSjQuery is not a function

if ($) {
     window.$RSjQuery(window).on("resize", function () {
         self.ResizeToolbarIcons();
     });
}

A:

Isso está ocorrendo porque o ReportViewer depende do $RSjQuery no momento de exibir a ToolBar.
Adicione a seguinte linha de código no evento Page_Load ou Pre_Render
    If Not Page.IsPostBack Then
        Me.Page.Controls.OfType(Of HtmlForm).First().Controls.Add(New ReportViewer With {.ID = "rdlcRSQuery", .Width = 0, .Height = 0)
    End If

Isso fará com que os Scripts que o ReportViewer depende estejam registrados na Página no momento de sua exibição.
Lembre de chamar
Imports Microsoft.Reporting.WebForms

E adicione o seguinte CSS
<style type="text/css">
    #rdlcRSQuery_ReportViewer { display:none;}
</style>


Q:

Android change google map tile with custom tiles

Is it possible to change google map API v3 standart map to my own custom map coming from url? I know that OSMdroid provide it but i want work with google map API. Is it possible?

A:

it is indeed possible by using WMS services (if you don't know what they are, please google it).
Here is some code you can use:
The WMSTile provider is used by GoogleMapsAPI to set the map provider:
public abstract class WMSTileProvider extends UrlTileProvider {

// Web Mercator n/w corner of the map.
private static final double[] TILE_ORIGIN = { -20037508.34789244, 20037508.34789244 };
// array indexes for that data
private static final int ORIG_X = 0;
private static final int ORIG_Y = 1; // "

// Size of square world map in meters, using WebMerc projection.
private static final double MAP_SIZE = 20037508.34789244 * 2;

// array indexes for array to hold bounding boxes.
protected static final int MINX = 0;
protected static final int MAXX = 1;
protected static final int MINY = 2;
protected static final int MAXY = 3;

// cql filters
private String cqlString = "";

// Construct with tile size in pixels, normally 256, see parent class.
public WMSTileProvider(int x, int y) {
    super(x, y);
}

@SuppressWarnings("deprecation")
protected String getCql() {
    try {
        return URLEncoder.encode(cqlString, Charset.defaultCharset().name());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return URLEncoder.encode(cqlString);
    }
}

public void setCql(String c) {
    cqlString = c;
}

// Return a web Mercator bounding box given tile x/y indexes and a zoom
// level.
protected double[] getBoundingBox(int x, int y, int zoom) {
    double tileSize = MAP_SIZE / Math.pow(2, zoom);
    double minx = TILE_ORIGIN[ORIG_X] + x * tileSize;
    double maxx = TILE_ORIGIN[ORIG_X] + (x + 1) * tileSize;
    double miny = TILE_ORIGIN[ORIG_Y] - (y + 1) * tileSize;
    double maxy = TILE_ORIGIN[ORIG_Y] - y * tileSize;

    double[] bbox = new double[4];
    bbox[MINX] = minx;
    bbox[MINY] = miny;
    bbox[MAXX] = maxx;
    bbox[MAXY] = maxy;

    return bbox;
}
}

And you can instantiate a custom one from your URL in such a way:
public static WMSTileProvider getWMSTileProviderByName(String layerName) {
        final String OSGEO_WMS = "http://YOURWMSSERVERURL?"
                + "LAYERS=" + layerName
                + "&FORMAT=image/png8&"
                + "PROJECTION=EPSG:3857&"
                + "TILEORIGIN=lon=-20037508.34,lat=-20037508.34&"
                + "TILESIZE=w=256,h=256"
                + "&MAXEXTENT=-20037508.34,-20037508.34,20037508.34,20037508.34&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&SRS=EPSG:3857"
                + "&BBOX=%f,%f,%f,%f&WIDTH=256&HEIGHT=256";

        return new WMSTileProvider(256, 256) {

            @Override
            public synchronized URL getTileUrl(int x, int y, int zoom) {
                final double[] bbox = getBoundingBox(x, y, zoom);
                String s = String.format(Locale.US, OSGEO_WMS, bbox[MINX], bbox[MINY], bbox[MAXX], bbox[MAXY]);
                try {
                    return new URL(s);
                } catch (MalformedURLException e) {
                    throw new AssertionError(e);
                }
            }
        };
    }

Add to your map:
TileProvider tileProvider = getWMSTileProviderByName("MYLAYERNAME");
TileOverlay tileOverlay = myMap.addTileOverlay(new TileOverlayOptions()
    .tileProvider(tileProvider));

You should also set the map type to MAP_NONE when using a custom tile provider (if it is not transparent), so you avoid to load gmaps tiles that are hidden behind your custom map.


Q:

Alkaline cells vs. LED flashlight

I have (had, actually) an El Cheapo pocket LED flashlight powered by 3 AAA cells. It was shipped with very low quality "salt" cells (regular, low weight - someone please suggest a proper English name for them). I tried to beef-up this flashlight by installing powerful Varta alkaline cells but flashlight blinked couple of times and gone dead. Now I have slight memories about what I read somewhere what LED drivers does not allow alkaline (higher current) feeding. Are my memories correct? Can I actually install alkaline cells to LED lighting devices? (Yes, No or Sometimes depending on driver)

A:

by installing powerful Varta alkaline cells but flashlight blinked
  couple of times and gone dead.

Yep. You definitely fried it there. I once had a cheap keychain flashlight that I didn't want so I hooked it up to 5V and it had exactly those symptoms. When I hooked it up again, it didn't work. No big deal, I just wanted to see what would happen, and I didn't really have a use for it.
However, if the person who designed that flashlight has greater than 0 electronic knowledge, they would add a resistor to limit the current. The only reason a resistor wouldn't limit the current correctly is if you had more voltage, which both more voltage and current allowed is a huge problem. Current is supplied on demand, but the LED sucks up as much as it can, but the resistor should limit it no matter the amount of current that can be supplied, unless the voltage is increased.

Edit: One thing I forgot: Quote from jippie's comment:

Alkaline batteries probably have much lower internal impedance than
  the original ones. The designer used the battery's internal impedance
  as series resistor. Done quite a lot in el Cheapo stuff.

Batteries have a internal resistance, and that's why the designer used the original ones to save on money. It's a smart trick, but you should have put a resistor in. How you would know this before, I don't know. But, if you have another one, you would just need to add a quick one from the store. At my RadioShack, I can get a five pack of 1/8W, 1/4W, or 1/2W for $1.49. (Yes they are all the same price... I have been wondering why anybody would want the more flimsy wires and a smaller piece that has less capacity but is the same price as the others.) But... you don't know how much current the LED can handle, unless you measured the current with the old batteries and used Ohm's Law.
If you have another and a multimeter, you can fix it on the other, but this one is toast. Gone. Bad. Broken. Fried.

A:

Your LED flashlight depended on the internal resistance of the batteries to limit current through the LEDs. With the original batteries, the internal impedance was high enough to limit LED current to safe levels.
This is common practice in many low price, non critical electronic devices. The saving is not just in the cost of the resistor, but also in incremental cost of assembly, however small. Anyone familiar with the so-called design of cheap consumer electronics will know how common this practice is.
Alkaline batteries typically have lower internal resistance i.e. can support much higher current than the cheaper zinc-carbon batteries. Without any other form of current limiting, the ”improved” capability of alkaline batteries has caused the death of the LED.


Q:

What town is in the Samsung Galaxy S default wallpaper?

This is the default wallpaper of Samsung Galaxy S smartphone, does anyone know where this place is?

A:

It is Annecy in France.
And you can see on the picture le Palais de l'Isle.

A:

Yes it's Annecy and its Old Town. This building is "Le Palais de l'Ile". It used to be a jail and now it's a place for exhibitions.
See more : http://goo.gl/hUoCJm


Q:

How to set alignment for UIScrollView in ios

i am creating an application, where i am using UIScrollView for displaying the number of available colors of each product. I am getting number of available colors at run time, so i have used for loop and displaying on my scroll view. Its working fine, but the problem if i am getting only one available color then my output is coming as below screen :

But the output should be as below screen :

It seems like i need to do kind of center alignment for my UIScrollView, so every available color will suppose to display from center. here is my code :
UIScrollView *availableColorScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
availableColorScrollView.backgroundColor = [UIColor clearColor];
availableColorScrollView.showsHorizontalScrollIndicator = YES;
availableColorScrollView.showsVerticalScrollIndicator=NO;
availableColorScrollView.pagingEnabled = YES;

for (int i = 0; i < arrayAvlbleColors.count; i++) {
    CGRect frame;
    frame.origin.x = 23 * i;
    frame.origin.y = 0;
    frame.size = availableColorScrollView.frame.size;
    UIView *subview = [[UIView alloc] initWithFrame:frame];

    UILabel *label = [[UILabel alloc] init];
    [label setFrame:CGRectMake(15, 14, 16, 16)];
    [label.layer setCornerRadius:8];

    NSString *strColorCode = [arrayAvlbleColors objectAtIndex:i];
    strColorCode = [strColorCode substringFromIndex:1];
    [label setBackgroundColor:[self colorWithHexString:strColorCode]];
    [subview addSubview:label];
    [availableColorScrollView addSubview:subview];
}

 [self.view addSubview:availableColorScrollView];

availableColorScrollView.contentSize = CGSizeMake(24 * arrayAvlbleColors.count, availableColorScrollView.frame.size.height);

Please suggest me to achieve my output, Thanks!

A:

this is the simple answer but working fine if u taken any Mainview or subview or else,
set the frame size/2 for height and width it automatically set it into center of the  subview.
here i used static color , customize urself
just change your line this
 NSString *strColorCode = [arrayAvlbleColors objectAtIndex:i];
strColorCode = [strColorCode substringFromIndex:1];
[label setBackgroundColor:[self colorWithHexString:strColorCode]];
[subview addSubview:label];
[availableColorScrollView addSubview:subview];

into
    NSString *strColorCode = [arrayAvlbleColors objectAtIndex:i];
     strColorCode = [strColorCode substringFromIndex:1];
    [label setBackgroundColor:[self colorWithHexString:strColorCode]];

    //use any one

    //option no 1:

    //[label setCenter:subview.center];

     //option no 2:

    [ label setCenter:CGPointMake(subview.frame.size.width / 2, subview.frame.size.height / 2)];

    [subview addSubview:label];
    [availableColorScrollView addSubview:subview];

final out put is


Q:

Java 8: Reflection Field.get() try-catch error

Issue
I am receiving an error in Eclipse stating that I have an unhandled exception with my call to Field.get(Object). When I wrap the code in the recommended try-catch, the error persists. I assume that I have to wrap the parameter, in the get() method, with a try-catch. Is this possible?
Error

Unhandled exception type IllegalAccessException

Line in question:
return list.stream().map(e -> fieldType.cast(f.get(e))).collect(Collectors.toList());

Code
Main.java
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Entity> entities = Arrays.asList(
                new Item(0, "Apple"),
                new Item(1, "Banana"),
                new Item(2, "Grape"),
                new Item(3, "Orange")
                );

        List<Long> ids = null;
        try {
            ids = pluck("id", Long.class, entities, Entity.class, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(ids);
    }

    public static <E extends Entity> List<Long> pluckIds(List<E> list) {
        return list.stream().map(e -> e.getId()).collect(Collectors.toList());
    }

    public static <T,F> List<F> pluck(String fieldName, Class<F> fieldType,
            List<T> list, Class<T> listType, boolean useLambda)
            throws NoSuchFieldException, IllegalAccessException,
            IllegalArgumentException {
        Field f = listType.getDeclaredField(fieldName);
        f.setAccessible(true);

        if (useLambda) {
            return list.stream().map(e -> fieldType.cast(f.get(e))).collect(Collectors.toList());
        } else {
            List<F> result = new ArrayList<F>();
            for (T element : list) {
                result.add(fieldType.cast(f.get(element)));
            }
            return result;
        }
    }
}

Item.java
public class Item extends Entity {
    private String name;

    public Item(long id, String name) {
        super(id);
        this.setName(name);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Entity.java
public abstract class Entity {
    private long id;

    public Entity(long id) {
        this.id = id;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }
}

A:

Eclipse is kind of stupid right now (there's probably a bug open).
You have a lambda expression in here
return list.stream().map(e -> fieldType.cast(f.get(e))).collect(Collectors.toList());

Field#get(Object) is declared as throwing a checked exception. But Function#apply(Object), which is the functional interface method you're implementing, does not. Eclipse is stupid in that it recommends that you wrap the statement in a try block, but it adds the try block around the whole thing
try {
    return list.stream().map(e -> fieldType.cast(f.get(e))).collect(Collectors.toList());
} catch (Exception e) {
}

when in reality it should be adding it to the body of the lambda
return list.stream().map(e -> {
    try {
        return fieldType.cast(f.get(e));
    } catch (Exception e) {
        return /* something else */ null; // or throw an unchecked exception
    }
}).collect(Collectors.toList());

This seems to happen when your lambda body is a simple expression rather than a block.


Q:

how do i check the data in an array with indexOf in java

i'm fairly new to java and i'm trying to use indexOf to check if a persons name ends with the letters in the array and output a word it rhymes with. Where am i going wrong? e.g. Dean ends in "ean" so it rhymes with green. Thanks guys
    String [] first = new String [3];
    first [0] = "eem";
    first [1] = "een";
    first [2] = "ean";

    for (int i = 0; i < first.length; i++) {

        if (first[i].indexOf(first.length) != -1){
            System.out.println("That rhymes with green");
        }
    }

A:

You should use endsWith instead of indexOf. indexOf will return the index where the passed string exactly matches the current string and, as the name suggests, endsWith will check if the current string ends with the passed string.
Take a look at the following code:
String personName = "Dean";
String[] suffix = {"eem", "een", "ean"};
String[] names = {"greem", "green", "grean"};

for(int i = 0; i < suffix.length; i++) {
    if (personName.endsWith(suffix[i])){
        System.out.println("That rhymes with " + names[i]);
    }
}

Also, ideally, you would want to keep a map of suffix -> name for maintainability, but for simplicity/exploring this should be fine.


Q:

How many distinct subgroups does the symmetric group $S_3$ have?

How many distinct subgroups does the symmetric group $S_3$ have?
So when I do this question, is there a general technique to use?
I know that the order of a subgroup divides that of the group.
But the because $S_3$ is not cyclic, there may not be bijection between divisors of $6$ and
the subgroups of it. (Or there is?)
So is the only way by trial and error?
For $S_3$ it may help to know that it is equal to the group of symmetries of a regular triangle.
But for $S_4$ and higher, is there any simpler method?
Anyway, is the answer $6$?

A:

I think that for small groups like $S_3$ this not very difficult to do by hand.
$S_3=\{id,(12),(13),(23),(123),(132)\}$
Clearly, $\{id\}$ and $S_3$ are subgroups of $S_3$
Now let us have a look at subgroups generated by one elements (cyclic subgroups). (We only have 6 elements to try, and we have already considered $[id]=\{id\}$.)
$[(12)]=\{id,(12)\}$
$[(13)]=\{id,(13)\}$
$[(23)]=\{id,(23)\}$
$[(123)]=[(132)]=\{id,(123),(132)\}$
Is this list of all subgroups? Yes, it is.
We can do this by trial and error -- trying adding one element to subgroup from our list and checking whether they generate the whole group $S_3$. (Which seems tedious, but in fact we only have to check whether any subgroup containing at least one 2-cycle and at least one 3-cycle is the whole $S_3$; and also observe that two different 2-cycles give us a 3-cycle.)
But quicker way is to notice that any proper subgroup of $S_3$ must have 1, 2 or 3 elements. (Order of subgroup must divide order of the group.) And any group of prime order is cyclic. So by enumerating cyclic subgroups we have obtain list
of all proper subgroups of $S_3$.
We can check our result at groupprops wiki (or elsewhere): Subgroup structure of symmetric group:S3.
You also asked about $S_4$. As I have mentioned in my comment, there is another question on this site about subgroups of $S_4$: How to enumerate subgroups of each order of $S_4$ by hand

A:

An important theorem to use is that the order of any subgroup must divide the order of $S_3$. Now, the order of $S_3$ is just 3! = 6. Hence, any candidate subgroup must have order 6, 3, 2, or 1. Note that the group of order 1 is just the trivial subgroup { e }, the group containing the identity element of $S_3$. Now, this is the only subgroup of order 1. The subgroup of order 6 must be $S_3$ itself, the only possible subgroup of order 6. Hence, we are left with subgroups of order 2 or order 3.
Subgroups of order 2: Note any subgroup must contain the identity element e.
Hence, we are interested in sets of the form K = { e $\in $ K and |K| = 2 and s $\in$ S$_3$, such that s$\circ$s=e }. This is because we want closure and we need an identity and inverse for any subgroup. It is not difficult to check that the only elements in $S_3$ satisfying the conditions on K are the transpositions on $S_3$.
Subgroups of order 3: For subgroups of order three we are interested in sets of the form F = { e $\in$ F and |F| = 3, and $s_1$,$s_2$ $\in$ S$_3$ such that $s_1$$\circ$$s_2$=$s_2$$\circ$$s_1$= e }. This is because we want to make sure our set is closed, and contains inverses and the identity. It is not difficult to check that there are only two elements in $S_3$ with unique inverses (inverses that are not the element itself) that satisfy all of the conditions imposed on F.
So you are done, and the number of unique subgroups of $S_3$ is 6.


Q:

How does this TypeScript function parameter work

I found this code online and trying to understand it.
public searchFunctionFactory($index: any): (text: Observable<string>) => Observable<any[]> {

    //Create a function that considers the specified $index parameter value
    let getCities = (text$: Observable<string>) =>
        text$
            .debounceTime(300)
            .distinctUntilChanged()
            .switchMap( query => {

                //some logic involving $index here
                //...

                //query.length < 2 ? [] : this.apiService.getCities(query).catch(() => {
                //return Observable.of([]);
            });

    //Return that "custom" function, which will in turn be called by the ngbTypescript component
    return getCities;
}

My question revolves around the method signature.
public searchFunctionFactory($index: any): (text: Observable<string>) => Observable<any[]>

I understand
$index: any is an input parameter of type Any.
The function returns Observable an observable of any.
But what is
: (text: Observable<string>)
Is it a second parameter?
If its a second parameter shouldn't it be
public searchFunctionFactory($index: any ,text: Observable<string>) => Observable<any[]>

A:

That indicates that the return value of the searchFunctionFactory function is a function which takes a parameter of text, whose type is Observable<string>, and calling that function returns an Observable<any[]>. It's a higher-order function.
public searchFunctionFactory($index: any): (text: Observable<string>) => Observable<any[]> {
                        /*   ^^^^^^^^^^^   searchFunctionFactory parameter */
public searchFunctionFactory($index: any): (text: Observable<string>) => Observable<any[]> {
  /* searchFunctionFactory return value     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */

As comment notes, this is not Javascript syntax, but Typescript syntax.
So, if you call
const result = searchFunctionFactory(someVar);

result will be of the type
(text: Observable<string>) => Observable<any[]>

and you could then call it with
const resultTwo = result(someOtherVar)

to get a value whose type is Observable<any[]>.


Q:

Composite of an immersion with the inverse map of another immersion is a diffeomorphism

Let $U\subset \mathbb{R}^k$ be an open set, $n>k$ and $\varphi_1,\varphi_2 : U\to \mathbb{R}^n$ be immersions, meaning continuously differentiable such that the differential taken in any point of $U$ is injective. Also, let $\varphi_1(U)=\varphi_2(U)=:U'$ and $\varphi_1$ and $\varphi_2$ be injective (and homeomorphisms $U\to U'$).
Then $\varphi_1^{-1} \circ \varphi_2 : U\to U$ is a diffeomorphism.
My problem is that $\varphi_1^{-1}$ need not be differentiable in the usual analysis sense, because $U'$ is not an open subset of $\mathbb{R}^n$. I am guessing that $d (\varphi_1^{-1}\circ \varphi_2)(x)$ should be $d(\varphi_1)(\varphi_1^{-1}(\varphi_2(x)))^{-1}\cdot d(\varphi_2)(x)$, because this is what happens if $k=n$ and it is still defined for $k<n$. However, I would need a way to apply the theorem on inverse functions to $\varphi_1$.

A:

I managed to solve this after all now (which is in part thanks to Sam's post, but I use a different idea).
Let $x\in U$ and $a:=\varphi_1(x)\in U'$. Choose $y\in U$ with $\varphi_2(y)=a$. It is enough to show that there is an open neighbourhood $V$ of $a$ in $U'$ such that $\varphi_1^{-1} \circ \varphi_2 : \varphi_2^{-1}(V)\to U$ is differentiable (by symmetry and because differentiability is a local property).
Without loss of generality, let the first $k$ rows of $d\varphi_1(x)$ be independent.
I want to use the fact that for suitably small $V$ as above, $V=W\cap U'$ with $W$ open in $\mathbb{R}^n$, there is a diffeomorphism $\Phi:W\to W'\subseteq \mathbb{R}^n$ such that $\Phi (V) = W'\cap \{ (x_1,..,x_n)\in W'\, |\, x_{k+1},..,x_n = 0 \}$.
In fact, one can be chosen as $\Phi: (x_1,..,x_k,x_{k+1},..,x_n)\mapsto (x_1,..,x_k,x_{k+1}-\varphi_{1,k+1}(\psi(x_1,..,x_k)),..,x_{n}-\varphi_{1,n}(\psi(x_1,..,x_k)))$
where, using the inverse function theorem, $\psi$ is the locally defined inverse function of $(\varphi_{1,1},..,\varphi_{1,k})$. (The differential of $\Phi$ is everywhere lower triangular with determinant 1.)
Let $p:\mathbb{R}^n\to\mathbb{R}^k$ be the projection to the first $k$ coordinates. The map $f:=p\circ \Phi \circ \varphi_1$ (defined on a suitable open set in $U$ containing $x$ and mapping to $\mathbb{R}^k$) is differentiable and injective.
For any $x'$ close to $x$, $df(x') = dp(\Phi(\varphi_1 (x'))) \cdot d\Phi (\varphi_1 (x')) \cdot d\varphi_1 (x')$. Now the first $k$ rows of $d\varphi_1(x')$ are independent (since $x'$ is close to $x$ and this is the case for $d\varphi_1(x)$) and  for $1\leq i\leq k$, the $i$th row of $d \Phi$ taken at any point is simply a $1$ at the $i$th coordinate and zeroes otherwise. The same goes for $dp$. So this composition of three matrices still has its first $k$ rows independent, so it is an invertible $k\times k$ matrix. It follows that $f$ is a diffeomorphism onto its image.
$\varphi_1^{-1}\circ \varphi_2$ equals the composition $f^{-1} \circ p \circ \Phi \circ \varphi_2$ on a suitably small neighbourhood of $y$ and all these maps are differentiable.


Q:

Knockout attr binding with attributes like 'readonly' and 'disabled'

What's the suggested "best practice" way to use Knockout's "attr" data binding with standalone attributes like "readonly" and "disabled"?
These attributes are special in that they are generally enabled by setting the attribute value to the attribute name (although many browsers work fine if you simply include the attribute names without any values in the HTML):
<input type="text" readonly="readonly" disabled="disabled" value="foo" />

However, if you don't want these attributes to be applied, the general practice is to simply omit them altogether from the HTML (as opposed to doing something like readonly="false"):
<input type="text" value="foo" />

Knockout's "attr" data binding doesn't support this scenario. As soon as I provide an attribute name, I need to provide a value as well:
<input type="text" data-bind="attr: { 'disabled': getDisabledState() }" />

Is there a cross-browser way turn off 'disabled' or 'readonly'? Or is there a trick with a custom binding that I can use to not render anything if I don't want the item disabled or made read-only?

A:

Knockout's "attr" data binding does support this scenario just return null or undefined from your getDisabledState() function then it won't emit the attribute.
Demo Fiddle.

A:

You can also create a binding for readonly like this:
ko.bindingHandlers['readonly'] = {
'update': function (element, valueAccessor) {
    var value = ko.utils.unwrapObservable(valueAccessor());
    if (!value && element.readOnly)
        element.readOnly = false;
    else if (value && !element.readOnly)
        element.readOnly = true;
}
};

Source: https://github.com/knockout/knockout/issues/1100

A:

Knockout has an enable binding as well as a disable binding.
I'm not sure if these were available when the question was asked, but anyone referring back to this issue should be aware.


Q:

Chef just ignores return block

Chef noob alert!!!!
So, I have this code
ohai 'reload' do
  action :reload
end

if node['packages'].keys.include?('ffmpeg')
  return
end

I want the recipe to return control if 'ffmpeg' is installed
I didn't do any installation or config for Ohai. Chef zero run says the plugin path /etc/chef/ohai/plugins does not exist but it also says :
"- re-run ohai and merge results into node attributes" .. So I guess that works
But Chef just ignores the if block. Chef doesn't even mention it when I run chef zero with "info" level enabled.
I have tried another variation of it too
return if node['packages'].keys.include?('ffmpeg')

But the same results. Why is Chef so weird? Or does it seems so to be because I didn't bother learning ruby? Why do all Chef resources assume that everybody knows all the basics.

A:

You should familiarize yourself with the Chef Client Overview. Especially the order of the Reset node attributes phase, Compile the resource collection phase, and Converge the node phase.
Ohai information is reloaded every time before resources are compiled, during the reset phase. If the goal is to reload Ohai for your if statement then the Ohai resource you have here isn't need. That Ohai resource will run during the converge phase. The if block runs before that Ohai resource, during the compile phase. This also means that if statement will return during the compile phase and not during the chef client run.
As a general rule; resources run during convergence but any ruby code that's not in a ruby_block resource runs during compilation. This means any if statement is completed during compilation with the state of the node before the current client run.
Hopefully this helps clear up some confusion.


Q:

Cómo validar campo select con JQuery

¿Cómo puedo validar en un campo select que al seleccionar una opción haga x función? Intenté hacerlo pero no funcionó. ¿Alguna forma de hacerlo?
registerGenderCheck = false;
$(function() {
    $('#registergender').on('click', function() {
        var x = $('#registergender');
        var bt = $('.button');

        if(x.val()){
            registerGenderCheck = true;
            x.css('border', '1px solid #40de49');
        }
        // else {}
    });
});

<select id="registergender">
    <option value="">Selecciona tu género</option>
    <option value="">Masculino</option>
    <option value="">Femenino</option>
</select>

A:

Para lograr lo que quieres debes cambiar la forma en la que intentas capturar el cambio de valor del elemento select, debes utilizar el evento change y no click, de la siguiente forma:

$(function() {
  $('#registergender').on('change', function() {
    if($(this).val() == 'masculino'){
      $(this).css('border', '1px solid #40de49');
    }else{
      $(this).css('border', '1px solid red');
    }
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="registergender">
  <option value="">Selecciona tu género</option>
  <option value="masculino">Masculino</option>
  <option value="femenino">Femenino</option>
</select>

En el código HTML de tu select, te faltaba asignar los value de cada option.


Q:

Why can `s => x.Append(s)` can be passed as an Action but `x.Append` can't?

I noticed something strange when trying to pass a StringBuilder's Append method to a function that took an Action<string>.
public void DoStuff(Action<string> handler)
{
    // Do stuff, call handler("data");
}

For testing purposes, I just want to write the data into a StringBuilder, so I tried to call it like this:
var output = new StringBuilder();
DoStuff(output.Append);

However, this gives a compile error, because the Append method does not match the required signature (it returns a reference back to the StringBuilder, not void as my method wants):

'System.Text.StringBuilder System.Text.StringBuilder.Append(string)' has the wrong return type

Without thinking, I changed the code to this:
var output = new StringBuilder();
DoStuff(s => output.Append(s));

This compiled fine.
Then I got confused; realising that s => output.Append(s) should also return the StringBuilder, aren't they the same?
So, why does this work? Why can s => output.Append(s) have the return value discarded silently, yet output.Append cannot?

A:

s => output.Append(s) creates a new lambda expression, which is inferred (from the context) to have a return type of void.
Therefore, the value of the expression body is ignored.
This is compiled to a separate method that calls Append() and returns void (this exactly matching the delegate)
In contrast, when you attempt to convert a method group to a delegate, the conversion must match exactly.
The spec (§6.5) says:

Specifically, an anonymous function F is compatible with a delegate type D provided:

If the body of F is an expression, and either D has a void return type or F is async and D has the return type Task, then when each parameter of F is given the type of the corresponding parameter in D, the body of F is a valid expression (wrt §7) that would be permitted as a statement-expression (§8.6).


Q:

QTreeView policy subclass. Is this sane?

I am kinda sick of making subclasses for each minor modification I need to make in QWhateverView behaviour so I got an idea:
What if I make a ProxyView for most commonly overriden functions that will essentially do stuff like:
//(mousePress used as an example)
void ProxyView::mousePressEvent ( QMouseEvent * event )
{
    if(mousePressFunctionHandler != nullptr)
       functionHandler(this, event);
    else
       QTreeView::mousePressEvent(event);
}

While it's true that I won't have access to view's internals this way, I often don't need it anyway... The only thing stopping me so far is that I am not sure if this idea is sane or not... :)
Or is there better way?

A:

It seems you need to use event filters.


Q:

This row has been removed from a table and does not have any data

This row has been removed from a table and does not have any data.  BeginEdit() will allow creation of new data in this row.
I have a method where I'm trying to delete all duplicate rows (using the date) and I'm getting the above exception with my code. I understand what the exception means but I don't understand what I'm doing wrong in my code to cause it. I have looked over it several times with no luck.
            using (OldStockRatingsTableAdapter ratingsAdapter = new OldStockRatingsTableAdapter())
            using (DataSet.OldStockRatingsDataTable ratingsTable = new DataSet.OldStockRatingsDataTable())
            {
                ratingsAdapter.ClearBeforeFill = true;
                ratingsAdapter.Adapter.UpdateBatchSize = 500;
                ratingsAdapter.FillByMarketSymbol(ratingsTable, market, symbol);

                var masterQuery = from c in ratingsTable
                            where c.Symbol == symbol && c.Market == market
                            select c;
                List<DataSet.OldStockRatingsRow> masterRows = masterQuery.ToList();
                List<DataSet.OldStockRatingsRow> masterDistinctRows = masterQuery.DistinctBy(i => i.Date).ToList();

                for (int i = 0; i < masterDistinctRows.Count; i++)
                {
                    var dateQuery = from c in masterRows
                                    where c.Date == masterDistinctRows.ElementAtOrDefault(i).Date
                                    select c;
                    List<DataSet.OldStockRatingsRow> dateRow = dateQuery.ToList(); // getting the exception here

                    if (dateRow.Count > 1)
                    {
                        for (int j = 1; j < dateRow.Count; j++)
                        {
                            ratingsTable.RemoveOldStockRatingsRow(dateRow.ElementAtOrDefault(j));
                            Console.WriteLine("Stock rating deleted for " + symbol + " in the " + market + " market!");
                        }
                    }
                }

                // update everything here
                DataSet.OldStockRatingsDataTable tempRatingsTable = new DataSet.OldStockRatingsDataTable();
                tempRatingsTable = (DataSet.OldStockRatingsDataTable)ratingsTable.GetChanges();

                if (tempRatingsTable != null)
                {
                    ratingsAdapter.Adapter.UpdateCommand.UpdatedRowSource = UpdateRowSource.None;
                    ratingsAdapter.Adapter.DeleteCommand.UpdatedRowSource = UpdateRowSource.None;
                    ratingsAdapter.Adapter.InsertCommand.UpdatedRowSource = UpdateRowSource.None;
                    ratingsAdapter.Update(tempRatingsTable);
                    tempRatingsTable.Dispose();
                    Console.WriteLine("Stock rating calculations finished for " + symbol + " in the " + market + " market!");
                }
 }

A:

I don't know about your code but if all that you are trying to do is delete duplicates then maby this code is of some use to you:
delete duplicate query
with x as (
select *, row_number() over(partition by <COLUMN>, checksum(<Columns to validate>) order by <COLUMN>) as rn
from <TABLE>
)
delete x where rn > 1
//it will validate multiple columns if more are given

Note: this code was not made by me, I'll link the origional post here. The code was posted by @dean.


Q:

If I deleted a question of mine, does other user's rep go away?

Say I have a question and somebody answers. He gets upvotes and I even make him the best answer. But later I delete my question. Does his rep go away because I deleted my own question? Or only the rep I gave him. Like when I gave him an upvote and best answer. And the other people who upvoted for him stays?

A:

Someone else would need to downvote the answer for you to be able to delete it (questions that have an answer with a positive score cannot be deleted by their author), but if someone else did cast such a downvote, then yes, the answerer would lose the 8 rep they had gained from the answer.


Q:

react HOC and losing reference to this

I'm trying to understand and use HOC with react and redux.  I have the following setup.  I will have multiple buttons using the hoc and passing in their own onClick. and would like to know:
a. Is this a good usage of the HOC pattern?
b. with this setup inside of the render function of FooterButton, this references DesignatedWorkerGlobalScope and iconHeigh, iconWidth, and iconColor inside HomeButton become either undefined or unexpected values.
Any advice would be appreciated.
import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';

import { connect } from 'react-redux';
import { compose } from 'redux';

import { getColors, getStylesheet} from "../../styles/StyleManager";

const FooterButtonWrapper = (FooterButtonWrapped, onClick) => {
    return class FooterButton extends React.Component {

        constructor(props) {
            super(props);

            this.state = {
                Theme: getStylesheet(),
                colors: getColors()
            }
        }

        _onClick = () => {
            onClick(this.props.dispatch);
        }

        render() {
            const { Theme, colors } = this.state;

            return(
                <TouchableOpacity onPress={this._onClick}>
                    <FooterButtonWrapped iconWidth={15} iconHeight={15}  iconColor={"white"}/>
                </TouchableOpacity>
            )
        }

    }
}

const mapStateToProps = (state, ownProps) => ({});

const composeFooterButton = compose(
    connect(mapStateToProps),
    FooterButtonWrapper
);

export default composeFooterButton;

and then a button that uses it:

import React from 'react';
import { View, Text } from 'react-native';

import { push as gotoRoute } from 'react-router-redux';

import { FooterButtonWrapper } from './';
import { Home } from '../../assets';

const HomeButton = ({iconHeight, iconWidth, iconColor}) => (

    <View>
        <Home width={ iconWidth } height={ iconHeight } color={ iconColor }/>
        <View><Text>Home</Text></View>
    </View>
);

const _onClick = dispatch => {
    dispatch( gotoRoute( '/' ));
}

export default FooterButtonWrapper(HomeButton, _onClick);

A:

It happens so, as you use
const composeFooterButton = compose(
    connect(mapStateToProps),
    FooterButtonWrapper
);

export default composeFooterButton;

for HOC function instead of Component.
Both compose and connect can wrap your Component.
So your HOC could be:
import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';

import { connect } from 'react-redux';
import { compose } from 'redux';

import { getColors, getStylesheet } from '../../styles/StyleManager';

export default function FooterButtonWrapper(FooterButtonWrapped, onClick) {
  class FooterButton extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        Theme: getStylesheet(),
        colors: getColors(),
      };
    }

    _onClick = () => {
      onClick(this.props.dispatch);
    };

    render() {
      const { Theme, colors } = this.state;

      return (
        <TouchableOpacity onPress={this._onClick}>
          <FooterButtonWrapped
            iconWidth={15}
            iconHeight={15}
            iconColor={'white'}
          />
        </TouchableOpacity>
      );
    }
  }
  const mapStateToProps = (state, ownProps) => ({});

  return connect(mapStateToProps)(FooterButton);
}


Q:

XML to Python Class to C Struct

I need some advice. Two questions, does something already exist for this, what modules should I use to develop this.
I have some structures that come from an XML file. I want to represent them in Python Classes (maybe using a factory to create a class per structure). But I want these classes to have a function that will emit the structure as a C Struct.
From my research ctypes seems like the recommended thing to use to represent the structures in Python classes, but I don't see any methods for anything that will emit C Stucts for the creation of a header file.

A:

From OP's comment I think the minimal solution a set of helper functions instead of classes.  the xmltodict library makes it easy to turn the XML data into nested dictionaries, more or less like JSON.  A set of helpers that parse the contents and generate appropriate C-struct strings is all that's really needed.  If you can work with dictionaries :
 {
    "name": "my_struct",
    "members": {
                  [
                    "name":  "intmember",
                    "ctype": "int"
                   },
                  {
                    "name":  "floatmember",
                    "ctype": "float"
                   }
                 ]
 }

You can do something like:
from string import Template
struct_template_string = '''
typedef  $structname struct {
$defs
} $structname;
'''
struct_template = Template(struct_template_string)
member_template = Template("    $ctype  $name;")

def spec_to_struct(spec_dict):
    structname = spec_dict['name']
    member_data = spec_dict['members']
    members = [member_template.substitute(d) for d in member_data]
    return struct_template.substitute(structname = structname, defs = "\n".join(members))

Which will produce something like:
typedef  my_struct struct {
   int  intmember;
   float  floatmember;
} my_struct;

I'd try to get it working with basic functions first before trying to build up a class scaffold. It would be pretty easy to hide the details in a class using property descriptors:
class data_property(object):
    def __init__(self, path, wrapper = None):
        self.path = path
        self.wrapper = wrapper

    def __get__(self, instance, owner):
        result =  instance[self.path]
        if self.wrapper:
            if hasattr(result, '__iter__'):
                return [self.wrapper(**i) for i in result]
            return self.wrapper(**result)
        return result

class MemberWrapper(dict):
    name = data_property('name')
    type = data_property('ctype')

class StructWrapper(dict):

      name = data_property('name')
      members = data_property('members', MemberWrapper )

test = StructWrapper(**example)

print test.name
print test.members
for member in test.members:
    print member.type, member.name

# my_struct
# [{'name': 'intmember', 'ctype': 'int'}, {'name': 'floatmember', 'ctype': 'float'}]
# int intmember
# float floatmember


Q:

Chrome dev tools display of printing array of jQuery objects to the screen

I've the the following sample code with a fiddle here
JS
   $(document).ready(function () {
                var bKids = $('.contained').find('button');
                var pKids = $('.contained').find('p');
                console.log('this is from bKids: ' + bKids.length)
                console.log('this is from pkids: ' + pKids.length);
                console.log(bKids);
                console.log(pKids);
            });

HTML

first child p tag

second child p tag

third child p tag

When I open up Chrome dev tools (and I assume other dev tools e.g. Firebug) if I inspect the bKids object I see that there are no selectors and the first property in the object is prevObject.  In the pKids object, we have an array of p tags inside a div, and before the prevObject property there are three p's.  What part of the jQuery object is this exactly, and if I wanted to refer to it by a property name, i.e. context, selector, etc.  how could I do it?

A:

The properties you're looking at/for, I gather, are the numbered properties containing the elements you're looking to select with the jQuery object - as in, any button elements for bKids and any p elements in pKids.
The current elements of a jQuery object can be accessed via the object's .get() method:
pKids.get()

will return an array of HTMLElement objects (your p elements). You can use pKids.get(n) to retrieve just one of these elements by array index. You could also access a single HTMLElement by its index as pKids[n]


Q:

Pipe Viewer with Nmap (progress bar)

I would like to know if there is a way to use "pipe viewer" with "Nmap" together.
Example:
pv | Nmap -sP 192.168.1.0/24

But I couldn't get the progress bar working properly. I mean it should be telling me the percentage of Nmap. Starts from 0%, when Namp is done, it will be 100%.

A:

Pipe viewer is for reporting percentage completion of files, pipes, and other file-like things. Nmap's completion times depend on network latencies, bandwidth, responsiveness of targets, and the features used to scan.
You can get a periodic status update with the --stats-every flag, like so: nmap --stats-every 10s, which gives an update every 10 seconds. You can get more verbose output from Nmap with the -v flag.


Q:

PHP Doctrine2 persisted Entity vs new Entity

I've looking all over the web, and it looks like I'm the only one that's annoyed/frustrated by this...
Let me explain.
I'm using Doctrine2 to build a series of entities
Something like this
(leaving out all the Doctrine annotations, getters & setters):
<?php

class Article
{
    protected $id;
    protected $name;
    protected $categories = [];
}

class Category
{
    protected $id;
    protected $name;
    protected $articles = [];
}

// create some categories
$cat1 = new Category();
$cat1->setName('cat-01');

$cat2 = new Category();
$cat2->setName('cat-02');

$cat3 = new Category();
$cat3->setName('cat-03');

// new Article
$article = new Article();
$article->setName('foo');
$article->setCategories([$cat1, $cat2, $cat3]);

Now, if you need to filter the Article's categories, you have to use array_filter();
$cats = array_filter($article->getCategories(), function($cat) {
    return $cat->getName() === 'cat-01';
});

Right.... that makes sense.
BUT, once the Article object is persisted and recovered from DB, you can use the PersistentCollection::filter(Closure $c) method
array_filter won't work though
$entityManager->persist($article);
$entityManager->flush();

$article = $entityManager->getRepository('Article')->findById(1);
$cats = $article->getCategories()->filter(function($cat) {
    return $cat->getName() === 'cat-01';
});

Same thing with array_map() vs PersistentCollection::map()
or current() vs PersistentCollection::current()
etc. etc. etc.
Now...
The question is, is there a way for my non persisted Entity to work the same way as a persisted one?
Or is there a way to make this work on persisted AND non persisted entities ?
$cats = $article->getCategories()->filter(function($cat) {
    return $cat->getName() === 'cat-01';
});

A:

Instead of using a native array, try using doctrine's ArrayCollection, which is probably the same type that your persisted entity is using:
use Doctrine\Common\Collections\ArrayCollection;

class Article
{
    protected $id;
    protected $name;
    protected $categories;

    function __construct() {
       $this->categories = new ArrayCollection();
    }
}

class Category
{
    protected $id;
    protected $name;
    protected $articles;

    function __construct() {
       $this->articles = new ArrayCollection();
    }
}

The following should now work on non-persisted entities:
// create some categories
$cat1 = new Category();
$cat1->setName('cat-01');

$cat2 = new Category();
$cat2->setName('cat-02');

$cat3 = new Category();
$cat3->setName('cat-03');

// new Article
$article = new Article();
$article->setName('foo');
$article->setCategories([$cat1, $cat2, $cat3]);

$cats = $article->getCategories()->filter(function($cat) {
    return $cat->getName() === 'cat-01';
});

You did not show the code but I'm guessing the problem lies with your Articles::setCategories method.  I suspect you have
class Articles {
  public function setCategories(array categories) {
    $this->categories = $categories;

This causes your ArrayCollection to be overwritten by a regular php array.
Instead do something like:
class Articles {
  public function setCategories(array categories) {
    foreach($categories as $category) {
      $this->categories[] = $category;

This will preserve the array collection and allow the filter function to work for new entities as well as retrieved ones.


Q:

Getting unable to open database file while inserting bulk data in sqlite db

I am using following code to insert rows more than 5000 in my ios app. if i am not using line sqlite3_close(dbv); statement i got an error unable to open database. and if i use the statement sqlite3_close(dbv) data insertion taking around 10-15 mins. what can i do to insert record faster without getting error.
-(void)insertrecordIntoTable:(NSString*)SQLStatement
{
    NSString *sqlStr=SQLStatement;
    const char *sql=[sqlStr UTF8String];
     const char* key = [@"StrongPassword" UTF8String];
    sqlite3_stmt *statement1;
    @try {

        int res = sqlite3_open([[self.databaseURL path] UTF8String], &dbv);
        if (res != SQLITE_OK)
            sqlite3_open([[self.databaseURL path] UTF8String], &dbv);

        sqlite3_key(dbv, key, (int)strlen(key));

        if(sqlite3_prepare_v2(dbv, sql, -1, &statement1, nil)==SQLITE_OK)
        {
            NSLog(@"done");
        }
        else
        {
             NSLog(@"the error occurred here is %s ",sqlite3_errmsg(dbv));
        }

        res =sqlite3_step(statement1);

        if(res !=SQLITE_DONE)
          NSLog(@"Error upadating table");

        sqlite3_finalize(statement1);
        sqlite3_close(dbv);
    }
    @catch (NSException *exception) {

    }
    @finally {
        sql=NULL;
        sqlStr=NULL;
        SQLStatement=NULL;
    }
}

A:

After opening database add this code
sqlite3_exec(mDb, "BEGIN TRANSACTION", NULL, NULL, &errorMessage);

And, before closing database add this code
sqlite3_exec(mDb, "COMMIT TRANSACTION", NULL, NULL, &errorMessage);

For more details check this link-
How to insert 40000 records fast into an sqlite database in an iPad


Q:

Filtering a numpy meshgrid

I would like to filter the values of a numpy meshgrid:
X,Y = np.mgrid[-10:10,-10:10]

in this case, I would like to remove all coordinates for which x**2 + y**2 <= 2.  However, when I try to filter the array directly, for example
filter(lambda x,y: x**2 + y**2 >= 2, np.meshgrid[-10:10,-10:10])

I get errors because I'm not properly dealing with the array's structure.
Any tips for doing this right would be appreciated!

A:

X,Y = np.mgrid[-10:10,-10:10]
idx = (X**2 + Y**2 > 2)
X, Y = X[idx], Y[idx]

The problem is that you no longer have 2D arrays, which may be an issue for things like matplotlib.

Seeing your own answer, and that you basically want to replace with 0 entries not fulfilling the condition, it is probably going to be cleaner and more efficient to do:
idx = X**2 + Y**2 > 2
X[~idx] = 0
Y[~idx] = 0


Q:

Verilog Arithmetic and Logic Unit (ALU) Compilation Error

I am getting a compilation error as such:

Error (10663): Verilog HDL Port Connection error at jdb_Blogic_v.v(7):
output or inout port "f" must be connected to a structural net
expression

I commented the line with the error. How do I fix it?
I also included the mux2to1 function code.
module jdb_Blogic_v (FS2_in, FS1_in, B_in, Y_out);

input FS2_in, FS1_in;
input [3:0] B_in;
output reg [3:0] Y_out;

jdb_mux2to1_v stage0 (B_in[0], FS1_in, FS2_in, Y_out[0]); //ERROR IS HERE ACCORDING TO COMPILER
jdb_mux2to1_v stage1 (B_in[1], FS1_in, FS2_in, Y_out[1]);
jdb_mux2to1_v stage2 (B_in[2], FS1_in, FS2_in, Y_out[2]);
jdb_mux2to1_v stage3 (B_in[3], FS1_in, FS2_in, Y_out[3]);

endmodule

module jdb_mux2to1_v (s, x1, x2, f);

input x1, x2, s;
output f;
wire    k, g, h;

not (k, s);
and (g, k, x1);
and (h, s, x2);
or (f, g, h);

endmodule

A:

Change the declaration of Y_out from output reg [3:0] to just output [3:0]. This will change it from being a reg to a wire.
A reg can only be assigned to from within a procedural statement, such as an always block.


Q:

queryBroadcastReceivers does not find receivers registered with registerReceiver

I need to find out which broadcast receivers can handle a given Intent.
It seems that queryBroadcastReceivers() does not return receivers registered in code using registerReceiver() but only receivers declared in AndroidManifest.xml.
Is this behavior by design?
Any other way to find all installed receivers for some Intent ?
Thanks.

A:

It looks like it's not possible to detect receivers registered in code, as per this recent message on the mailing list: http://groups.google.com/group/android-developers/msg/5fd1cdb24b2a6760
This is disappointing as I was looking for a way to do the same thing.


Q:

Msg 4104, Level 16, State 1, Procedure AddItemToCurrentItems, Line 11 The multi-part identifier "INSERTED.IsActive" could not be bound

I have following trigger written for my application which gives me this error "Msg 4104, Level 16, State 1, Procedure AddItemToCurrentItems, Line 11 The multi-part identifier "INSERTED.IsActive" could not be bound."
My intension with this trigger is to copy the inserted data in table "Item" to table "CurrentItems" but only if the bit field in Items table is set to True i.e. 1. Both tables have the same table structure
CREATE TRIGGER AddItemToCurrentItems
   ON ITEMS FOR INSERT
--,UPDATE
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for trigger here
    IF INSERTED.IsActive = 1
    BEGIN
       INSERT INTO CurrentItems
           SELECT * FROM INSERTED
    END
END

Any ideas, what I am doing wrong here.

A:

You are missing a reference to the INSERTED table in you if clause, would need to look something like this:
IF exists (select * from inserted i where i.IsActive = 1) BEGIN
...

NOTE however that the inserted/updated tables can always contain multiple records, just like any SQL table, so you'll need to be sure your logic handles multi-record possibilities, for example your insert within your IF block should likely contain an additional where clause, something like this:
IF exists (select * from inserted i where i.IsActive = 1)
BEGIN
    INSERT CurrentItems SELECT * FROM INSERTED where IsActive = 1
END

Or, you could just leave out the IF block alltogether and do something like this:
INSERT CurrentItems SELECT * FROM INSERTED where IsActive = 1

NOTE that you probably should also consider including a column list in both your insert and select statements...


Q:

схожесть действий стандартных алгоритмов is_partitioned и all_of

Никак не смог понять чем отличаются эти два алгоритма.
string s = "(double) k / 12";
auto pred = [](char c) { return c == '/'; };
bool b1 = is_partitioned(s.begin(), s.end(), pred);
bool b2 = all_of(s.begin(), s.end(), pred);
cout << boolalpha << b1 << endl /*false*/ << b2; /*false */

Читал как они реализованы, но не нашел разницу. И чем же отличаются эти два алгоритма, кто поможет разобраться?
Добавление к вопросу:
Для того, чтобы я лучше понял,  прошу на моем примере добавить символы  или поменять предикат так, чтоб  результат двух алгоритмов был разным.

A:

all_off вовращает true если все элементы диапазона при проверке pred выдают true. Т.е. ни один элемент при проверке не даст false.
is_partitioned возвращает true если все элементы диапазона, которые при проверке выдают true находятся перед элементами, которые при проверке выдают false. Т.е. некоторые элементы могут при проверке давать false, но должны находиться после элементов, которые дают true:
[true, true, true, true, false, false] будет true.
[true, true, false, true, false, false] будет false, потому что после первого false еще есть true (или, что то же самое, до последнего true встречается как минимум один false).


Q:

Joining fields from 2 tables

I have 2 tables :
table 'g'
+------+
| id   |
+------+
|    1 |
|   32 |
|    3 |
|    6 |
|    5 |
|   22 |
|   54 |
|   21 |
+------+

table 'h'
+------+------+
| id   | sl   |
+------+------+
|    1 |  323 |
|   11 |  423 |
|    1 |  333 |
|   33 |   32 |
|   44 |  443 |
+------+------+

How can I show records from 2 tables like (select distinct id from 'g' and 'h' table and joining maximum 'sl' from 'h' table for each id. the 'id's of 'g' table which does not match with 'id' of table 'h', those 'sl' fields will be null)
+------+------+
| id   | sl   |
+------+------+
|    1 |  333 |
|   32 | null |
|    3 | null |
|    6 | null |
|    5 | null |
|   22 | null |
|   54 | null |
|   21 | null |
|   11 |  423 |
|   33 |   32 |
|   44 |  443 |
+------+------+

-Thanks.

A:

This can be done with a UNION between the two, left joined as a derived table against the h to get the MAX() values:
SELECT
  allids.id,
  MAX(sl) AS sl
FROM
  /* Subquery gets UNION (distinct, not UNION ALL) of ids from both tables */
  (SELECT id FROM g UNION SELECT id FROM h) allids
  /* LEFT JOINed back against `h` for the MAX() aggregates */
  LEFT JOIN h ON allids.id = h.id
GROUP BY id

http://sqlfiddle.com/#!2/2c348/3
Update after comments:
To force them to sort in the arbitrary (un-ordered) order that they were inserted, it may sort of work to place a number literal into the subquery which gets used in the ORDER BY.
The order rows are inserted isn't really meaningful to the RDBMS though. You cannot reliably assume that they would always be given back to you in the same order, absent an ORDER BY clause.
SELECT
  allids.id,
  MAX(sl) AS sl
FROM
  /* Awful hack adds a number literal which is used in the ORDER BY */
  /* This still won't guarantee that the rows from each table will be in the original order though */
  (SELECT id, 1 AS sort FROM g UNION SELECT id, 2 AS sort FROM h) allids
  LEFT JOIN h ON allids.id = h.id
GROUP BY id
ORDER BY sort

http://sqlfiddle.com/#!2/2c348/6


Q:

From within a function, how to view the result that so far will be returned to the pipeline

Recently I had to add an intermediate variable to a PowerShell script, otherwise the New-Item result would be part of the function result:
      # Put in local varible, otherwise we will return it as part of the function result
      $Local:logDirectory = New-Item -ItemType directory -Path $Local:logDir
      Write-Host "Created directory '$Local:logDir'"
  }
  return "$Local:logDir\$LogFileName"

While debugging this, I would have loved to be able to dump (Write-Host or something) the current bits that the function already has queued up to end in the pipeline upon function return.
So:
From within a PowerShell function, how to view the result that so far will be returned to the pipeline

A:

Use PowerGUI (a powershell IDE), you will be able to insert breakpoints and inspect the runtime variables.
http://en.community.dell.com/techcenter/powergui/m/
You can also use piping to Out-Null, i.e:
New-Item -ItemType directory -Path $Local:logDir | Out-Null
to get rid of spurious output. Unfortunately you might have to go through your code line by line.


Q:

Convert a String[] in C# to a Char *[] in C++

I am currently using Visual Studio 2010.  This is my first time writing a wrapper for a C++ class.  The class in C++ looks like this:
bool exampleCode(char* arrayOfStrings[], int number, char* regularString)

I created the header file which looks like:
bool exampleCode(array<String^>^ arrayOfStrings, int number, String^ regularString)

and the .cpp file class looks like:
bool exampleCode(array<String^>^ arrayOfStrings, int number, System::String^ regularString)

I figured out how to marshal the regularString data but I'm not sure how to convert the String array into a char*[].  Any help would be appreciated.

A:

Here's an easily reusable version (complete with demonstration) that improves on @ildjarn's answer by reducing the number of allocations and improving locality.  It also uses your choice of encoding such as UTF-8.
#include <iostream>
#include <vector>

#include <windows.h>
#include <vcclr.h>

using namespace System;

template <typename T>
struct advanced_marshal;

template <>
struct advanced_marshal<char*[]>
{
    char** get() { return &m_strings[0]; }

    advanced_marshal( array<System::String^>^ strings, UINT code_page = CP_ACP ) : m_strings(strings->Length)
    {
        if (int count = strings->Length) {
            int i;
            size_t total_length_estimate = count; // one NUL byte per string
            for( i = 0; i < count; ++i ) {
                total_length_estimate += strings[i]->Length * 4;
            }

            m_buffer.resize(total_length_estimate);
            auto tail = m_buffer.begin(), end = m_buffer.end();
            i = 0;
            do {
                m_strings[i] = &*tail;
                pin_ptr<const WCHAR> pwsz = PtrToStringChars(strings[i]);
                tail += 1 + WideCharToMultiByte(code_page, 0, pwsz, strings[i]->Length, &*tail , end - tail, nullptr, nullptr);

                ++i;
            } while (i < count);
        }
    }

    advanced_marshal(advanced_marshal<char*[]>&& other) { m_buffer.swap(other.m_buffer); m_strings.swap(other.m_strings); }

private:
    advanced_marshal(const advanced_marshal<char*[]>&); // = delete
    void operator=(const advanced_marshal<char*[]>&); // = delete

    std::vector<char> m_buffer;
    std::vector<char*> m_strings;
};

void print_some_strings( char* strings[], int num )
{
    for( int i = 0; i < num; ++i )
        std::cout << strings[i] << "\n";

    std::cin.get();
}

int main(array<System::String ^> ^args)
{
    print_some_strings(advanced_marshal<char*[]>(args).get(), args->Length);
    return 0;
}


Q:

Finding near-integers in a range

I have a (transcendental) constant $\alpha$ and a fixed parameter $\varepsilon>0.$ I'd like to find all positive integers $n<\ell$ for which $\|n\alpha\|<\varepsilon,$ where $\|x\|$ is the distance between $x$ and the nearest integer. Is there a good way to do this?
The first natural thought is to use continued fractions but at best this would give me a few good examples rather than all of the numbers in the range.
For concreteness let's say $\ell>10^{10}$ and $\varepsilon\approx\ell/\log\ell$. In short I'm searching a big range for integers which are very close to a multiple of $\alpha.$

A:

If you know how to solve problems of the form "find the least integer $n(\eta) \ge 1$ such that $n\alpha \in [- \eta - \varepsilon; - \eta + \varepsilon]  \pmod 1$" where $|\eta| \le \varepsilon$, then you can easily find all those integers one after the other.
Thus, you want to keep a list of the integers $n$ such that $n \alpha$ is closer to $0$ than for any other smaller multiple. You need two lists, one made of the positive records and one of the negative records (those will contain the multiples corresponding to the continued fractions, so they are still relevant to the problem).
Both lists start with $n=1$, corresponding to $+(\alpha-\lfloor \alpha \rfloor)$ and $-(\lceil \alpha \rceil - \alpha)$.
To continue the lists, one can prove by induction that the next record is the sum of the two current records. Add it to the list corresponding to its sign, and repeat.
Once the difference between the two current records gets smaller than $2\varepsilon$, you can stop, and use the few records smaller than $2\varepsilon$ to compute the piecewise constant function $n(\eta)$ for $|\eta| \le \varepsilon$.
Finally, you obtain the sequence you want recursively by $N_0 = n(0)$ and $N_{k+1} = N_k + n(N_k \alpha \mod 1)$.

For example, suppose you want to find the multiples of $\sqrt 2$ that are less than $10^{-2}$ to an integer.
Modulo $1$, you have the following records :
$\begin{matrix}1\sqrt 2 & = + 0.4142 & = -0.5857 \\
2\sqrt 2 && = -0.1715 \\
3\sqrt 2 &= +0.2426& \\
5\sqrt 2 &= +0.0711& \\
7\sqrt 2 &&= -0.1005 \\
12\sqrt 2 &&= -0.0294 \\
17\sqrt 2 &= +0.0416& \\
29\sqrt 2 &= +0.0122& \\
41\sqrt 2 &&= -0.0172 \\
70\sqrt 2 &&= -0.0051\end{matrix} $.
Since $29\sqrt 2 = +0.0122$ and all the previous values are bigger than $0.02$, this shows that $n(\eta) = 29$ for $|\eta + 29\sqrt 2| \le 0.01 \pmod 1$, which means $\eta \in [-0.01 ; -0.0022] = [-0.01 ; -29\sqrt 2 + 41.01]$
Next, we have $n(\eta) = 41$ for the remaining $\eta$ satisfying $|\eta + 41\sqrt 2| \le 0.01 \pmod 1$, which means $\eta \in [+0.0072 ; +0.01] = [-41\sqrt 2 + 57.99 ; +0.01]$.
Finally, we have $n(\eta) = 70$ for the remaining $\eta$ satisfying $|\eta + 70\sqrt 2| \le 0.01 \pmod 1$, which means $\eta \in [-0.0022 ; +0.0072] = [-29\sqrt 2 + 41.01 ; -41\sqrt 2 + 57.99]$.
So if the current multiple falls in $[-0.01 ; -0.0022]$, we add $29\sqrt 2$, if it falls in $[-0.0022 ; +0.0072]$, we add $70\sqrt 2$, if it falls in $[+0.0072 ; +0.01]$, we add $41\sqrt 2$ :
Now we obtain the sequence :
$70\sqrt 2 = -0.0051\\ 99\sqrt 2 = +0.0071 \\ 169\sqrt 2 = +0.0021 \\ 239\sqrt 2 = -0.0030 \\ 268\sqrt 2 = +0.0092 \\ 309\sqrt 2 = -0.0080 \\ \ldots$

If you want to skip ahead and start from $\ell_1$, it's a bit more difficult, because from $\ell_1 \alpha$ you have to to solve a problem of the form "find the smallest $n$ such that $n\alpha$ is in such interval of length $2\varepsilon$", and this interval is unlikely to contain $0$. To find that first integer, you need to enlarge the target interval so that it contains $0$, then use the list of records to solve the problem with the enlarged interval. You will then get a bit closer to the target interval, so the next target interval will be closer to $0$, and repeat.


Q:

Tomcat write permission apache server user uploads

When a user uploads an image, the file is created in "/var/www/example.com/uploads" by the tomcat webapp so that apache can serve the image. However, the tomcat group/user creates the file so it is not accessible through example.com/uploads/image.jpg unless I manually change the read permissions, then the file is no longer forbidden. But, every file is created without read permissions. I am not fluent with ubuntu and I do not know if I need to change something within the java servlet or to the folder/group/user. Any help would be greatly appreciated.
-rw-r----- 1 tomcat tomcat 120264 Jul 14 19:26 second-image.jpg
-rw-r--r-- 1 tomcat tomcat 172853 Jul 14 19:05 image.png

Edit:
The file is submitted as multipart config form data. After checking the types, size, etc., it is written to the system simply as:
Path imageDir = Path.of("/var/www/example.com/uploads");
Path imageFile = Files.createFile(imageDir.resolve(fileName).toAbsolutePath());
part.write(imageFile.toString());

A:

Your application code is already calling a method that is able to set permissions, but isn't providing a parameter to do so. You can read this tutorial on File Attributes to see an example of setting file permissions. I'm guessing you'd want to create the permissions from a string, since you're already working with the format:
Set<PosixFilePermission> perms =
PosixFilePermissions.fromString("rw-------");
FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
Files.createFile(file, attr);


Q:

Can't access Alamofire Request body

I'm facing a problem while requesting from server, everything was fine
suddenly the Alamofire.request can't access responseJSON and can't access the body of the function and it returns , what I have to do?
I'm using multi Alamofire request in the navigationController but after two or three requests this happens!
I'm really in trouble please help me!
this code can't execute
    let group = DispatchGroup()
    group.enter()
    Alamofire.request(url, method: .get, parameters: nil,
      encoding:
        JSONEncoding.default, headers: header as? HTTPHeaders)
        .responseJSON { (response) in
            if response.result.isSuccess{
                if let response = response.result.value {

                    let json = JSON(response)
                    self.updateAnswers(json: json)
                    print(json.arrayValue)
                    group.leave()
                }
            }
    }

A:

If it’s not successful, you should dive in and take a look at the error that was returned. You might even want to look at the body of the response (if its a development server, it might provide some useful error messages in the body of the response).
let group = DispatchGroup()
group.enter()
Alamofire.request(...)
    .responseJSON { response in
        defer { group.leave() }

        switch response.result {
        case .failure(let error):
            print(error)
            print(response.response ?? "no HTTPURLResponse")
            if let data = response.data {
                if let string = String(data: data, encoding: .utf8) {
                    print(string)
                } else {
                    print(data as NSData)
                }
            } else {
                print("no data")
            }

        case .success(let json):
            print(json)
        }
}

By the way, I’d suggest moving the leave call outside of any if/switch statement because you want to make sure your dispatch group is satisfied regardless of whether it was successful or not.
But, bottom line, you won’t be able to diagnose the problem until you start to look at precisely what error was returned.


Q:

javascript sdk is opening multiple login dialogs

Im having an issue where the Javascript SDK opens multiple dialogs to log in.
if i log in and then out it works fine, but the next time i log in it will open 2 popups. next time it will open 3 and so on.
The Page is using PHP, Javascript/Jquery
The code is a tweaked version of this tutorial
http://thinkdiff.net/facebook/new-javascript-sdk-oauth-2-0-based-fbconnect-tutorial/
Here is my Code:

A:

if i log in and then out it works fine, but the next time i log in it will open 2 popups. next time it will open 3 and so on.

Are you staying on the same page – without reloading it in between?
That would explain what you’re describing, because then every time your function updateButton is called and goes into the else branch, it will add a new additional click event handler to #loged, so they would start “accumulating”, and therefor FB.login will be called multiple times – because each single click will trigger multiple handlers (that all do the same stuff).


Q:

Does the order of columns in a covering index matter?

I have the following covering indices:
INDEX (col1, col3); -- index 1
INDEX (col1, col2, col3); -- index 2

because I would like to support the following type of queries:
1)
  SELECT col3
    FROM my_table
   WHERE col1 = ... AND
         col2 = ...
ORDER BY col3

2)
  SELECT col3
    FROM my_table
   WHERE col1 = ...
ORDER BY col3

I am unfamiliar with how a covering index works.  Is index 1 redundant? Or does a covering index requires that the columns be side by side?

A:

"Covering" is the wrong term to start with.  I'll get back to that in a minute.
The optimal index for your queries can be summarized:

The first columns in the index must be all the = columns in the WHERE, in -any_ order.
The last columns in the index must be the ORDER BY columns in the same order, and either be all ASC or all DESC.  (MySQL 8.0 has an exception here.)

Your index 1 is necessary and sufficient for query 2.
Your index 2 is necessary and sufficient for query 1.
Anything different would be sub-optimal.
Note that they would also be "covering" in that all the columns anywhere in the SELECT are found in the respective indexes.
Index 2 "covers" both queries, but it is not very good for Query 2.

Devise the optimal index for each important query.
Eliminate redundancy.  Example: Given INDEX(a), INDEX(a,b), toss the former.
Then think about adding some columns on the end to make an index "covering".

For those tips, plus more, see http://mysql.rjweb.org/doc.php/index_cookbook_mysql
This is "covering", but not efficient because col99 in first in the index, but not used for filtering or sorting:
INDEX(col99, col1, col2, col3)

It might be used, but only because it is covering.  It can't be used for filtering or sorting.
This is "covering" and might be used to avoid sorting because the ORDER BY column(s) are first:
INDEX(col3, col2, col1)

Query 1 would be just as happy with this regardless of the cardinality of the individual columns:
INDEX(col2, col1, col3)

Back to the title question:

Does the order of columns in a covering index matter?

Answer:

For the sake of "covering":  No.
For speeding up the query:  It depends.  And that is why I recommend starting with other 'rules' for building a good index.

An analogy

A table is an unordered set of things.  Analog:  a textbook.
An index is an ordered list, referencing those things.  Analog:  the index in the back of the textbook.
When everything you need to answer a question is sitting in the index (and you don't need to leaf back into the body of the textbook), then the index is "covering".

A B+Tree has two important properties:

It is quick to jump into the middle at any specific word.
It is fast to scan forward from that word.


Q:

Best practice for initializing member variables?

Possible Duplicate:
Best Practice: Initialize class fields in constructor or at declaration?

I am working with C# but this probably applies to Java (or any other language that allows this behavior as well)...
Which way is preferable/best practice?  Assume I will ALWAYS need _memberVar
1.
class MyClass
{
    private Dictionary<int, string> _memberVar = new Dictionary<int, string>();

    public MyClass() {}
}

- OR -
2.
class MyClass
{
    private Dictionary<int, string> _memberVar = null

    public MyClass()
    {
        _memberVar = new Dictionary<int, string>();
    }
 }

Now lets say that MyClass has upwards of 10 constructors...  So I don't want to have _memberVar = new Dictionary<int, string>(); in all of those constructors lol.  Is there anything wrong with the 1st way?  Thanks
Edit:
I realize I can chain the constructors, but this is a rather complex class... some constructors call the base, some call other constructors already etc etc.

A:

You do not have to initialise member variables, but it does not hurt if you do. Member variables acquire their default values automatically, usually a null for objects and the default value for primitive types (such as 0 for an int).
As for having different constructors, you do not have to repeat the member initialisation in each version since you can call an overloaded constructor from any other just as you would with an overloaded method.
Regarding best practice, personally I initialise member variables in the constructor as this is where I want to "construct" my object into a stable state. In other words, even if I would have initialised member variables where I declare them, when the constructor is called, it would be as if I was wiping the slate clean.


Q:

Javascript - regex to validate document files - PDF, TXT, DOC

I'm using blueimp File Upload plugin to upload files. There's an example regex to restrict the upload to images only:
var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;

How can I change this to upload image files, and documents like PDF, TXT, DOC?

A:

var acceptFileTypes =
/^image\/(gif|jpe?g|png)$|^application\/(pdf|msword)$|^text\/plain$/i;

This seems to assume that the correct mime type is checked against acceptFileTypes