text:
Q: twil python linux errors I've a raspberry PI whit raspbian. When i try to start a python application whit selenium it give me some errors.
This is the application:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep

browser = webdriver.Firefox(executable_path=r'/home/pi/Desktop/geckodriver')

This is errors:
Traceback (most recent call last):
  File "uno.py", line 5, in <module>
    browser = webdriver.Firefox(executable_path=r'/home/pi/Desktop/geckodriver')
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/firefox/webdriver.py", line 160, in __init__
    self.service.start()
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/common/service.py", line 76, in start
    stdin=PIPE)
  File "/usr/lib/python3.5/subprocess.py", line 676, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.5/subprocess.py", line 1282, in _execute_child
    raise child_exception_type(errno_num, err_msg)
OSError: [Errno 8] Exec format error

How can i fix?

A: An exec error indicates you took the wrong OS file for geckodriver. See the below for all release
https://github.com/mozilla/geckodriver/releases
As of today (27th Jun 2018), you should probably be picking below
https://github.com/mozilla/geckodriver/releases/download/v0.21.0/geckodriver-v0.21.0-arm7hf.tar.gz
Also make sure to do
chmod +x /home/pi/Desktop/geckodriver

So that it has executable rights


text:
Q: Why is MCA so much slower than PCA? I have a large (50k rows, 2k columns) sparse binary dataset, and thus PCA isn't the best option for dimensionality reduction. I downloaded  this mca package, and am running the following code:
import mca
import pandas as pd
data_dummy = mca.dummy(pd.DataFrame(data))
mca_counts = mca.MCA(data_dummy)
mca_components = mca_counts.fs_r(1)

I've let it run for over an hour, and still nothing. In comparison, sklearn's PCA implementation churns through the same dataset in under 30 seconds. Am I doing something horribly wrong? Or is MCA not a deterministic global optimization algorithm, unlike PCA which is. If so, is there another implementation I should be looking at? I'm just trying to find a fast, descent dimensionality reduction technique for sparse categorical (binary) data.

A: Don't use the MCA package I was using. Use Prince, like @LazyCoder suggested. I'm not quite sure why it's so much faster, but that seemed to solve it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Control fog density in rgl I am looking for a way to change the overall fog density of an rgl scene (there is no parameter to directly do this, and all fogtype=... choices are way too dense)
Any tips?
Thanks!

A: You can do this using the development version 0.102.9.  For example, this code
gives the standard fog:
library(rgl)
shade3d(cube3d(), col = "black", lit = FALSE)
bg3d(fogtype = "exp", col = "white")

After some rotation, you see this:

If you then run this:
bg3d(fogtype = "exp", col = "white", fogScale = 0.5)

the plot darkens to this:

To get this development version, see https://stackoverflow.com/a/37142971/2554330.


text:
Q: Conditional JOIN with two different keys I have a query that produces two separate IDs:
SELECT
date,
user_id,
vendor_id,
SUM(purchase) user_purchase
SUM(spend) vendor_spend
GROUP BY 1,2,3
FROM tabla.abc

This produces results like this:
date   user_id   vendor_id   user_purchase   vendor_spend
1/1/18   123      NULL         5.00             0.00
1/1/18   NULL     456          0.00             10.00

I want to join it on a table that looks like this:
client_id   user_id   vendor_id
456789      123       NULL
101112      NULL      456

But the problem is, I obviously want to join it on both the appropiate IDs so my final output can look like this:
date    client_id  user_id   vendor_id   user_purchase   vendor_spend
1/1/18   456790     123      NULL         5.00             0.00
1/1/18   101112     NULL     456          0.00             10.00

So is there a way I can do like, a conditional join? Something like WHERE user_id IS NULL THEN... etc...

A: Use not distinct from because one of the argument may be null:
select *
from (
    select
        date,
        user_id,
        vendor_id,
        sum(purchase) user_purchase,
        sum(spend) vendor_spend
    from table1
    group by 1,2,3
    ) t1
join table2 t2
    on (t1.user_id, t1.vendor_id)
    is not distinct from (t2.user_id, t2.vendor_id)

Note that for performance reasons you should join already aggregated table (hence I have placed the original query in a derived table).

A: Try this:
SELECT
date,
COALESCE(lu.client_id, lv.client_id) AS client_id,
user_id,
vendor_id,
SUM(purchase) user_purchase
SUM(spend) vendor_spend
FROM tabla.abc
LEFT JOIN tabla.link AS lu USING (user_id)
LEFT JOIN tabla.link AS lv USING (vendor_id)
GROUP BY 1,2,3,4

A: I think the sufficient join is just this:
FROM aggregated_table t1
LEFT JOIN client_id_table t2
ON t1.user_id=t2.user_id
OR t1.vendor_id=t2.vendor_id

because as I understand you need to join by user id if there is user id and by vendor id if there is vendor id. Using a left join with OR does exactly that.
Also, conditional join is possible as well. If you're familiar with a CASE statement it works perfectly well in join conditions. Similar thing can be expressed as:
FROM aggregated_table t1
LEFT JOIN client_id_table t2
ON CASE
    WHEN t1.user_id is not null THEN t1.user_id=t2.user_id
    WHEN t1.vendor_id is not null THEN t1.vendor_id=t2.vendor_id
END

but this is too verbose compared to the previous option that I think should produce the same result


text:
Q: RegEx catching character space character character group I am trying to write a RegEx expression to find the following:
Space character preceded by a-z or A-Z or 0-9 or ) following by two characters falling in to the following category a-z or A-Z or 0-9 or - or (; i.e. char1-space-char2-char3
char1 = [0-9 a-z A-Z )]
char2 = [0-9 a-z A-Z - ]
char3 = [0-9 a-z A-Z (]

For example:
cos(x) + sin(x){S}-0.3 * cos(x){S}k * sin(x) - z0{S}ke-1{S}-ke-3
where {S} would be spaces I want to catch
I am new to RegEx and from what I can find online I need to use look ahead and look behind, but I am not sure how to make sure how to catch char-space-char-char group.
So far I have this but its not working at all
[\w\d\)]([ ]{1})[\w\d-]

I hope it makes sense.

A: If you want to use the look around assertions, that will handle overlapping that you need.
Just use your same constructs, but wrap before/after space with the  look around
syntax.
(?i)(?<=[\da-z)])[ ](?=[\da-z-][\da-z(])
Expanded:
 (?i)                       # Case insensitive
 (?<= [\da-z)] )            # Lookbehind, alnum or ')'
 [ ]                        # Consume space
 (?= [\da-z-] [\da-z(] )    # Lookahead, alnum or '-' followed by alnum or '('


text:
Q: how to handle If a subquery (inner query) returns a null value to the outer query I have a vertical table like this:

id
Profile_id
feature_id
value

1
1
1
Rick

2
1
2
Novak

3
5
3
5428

4
5
1
Joe

...
...
...
...

(above table is short part of profile_features table)
I have a query:
SELECT * FROM(SELECT `value` TelNum FROM `profile_features` WHERE `feature_id` IN (10, 64, 103) AND `profile_id` = 16752 LIMIT 1) as TelNum,
    (SELECT `value` NCode From `profile_features` WHERE `feature_id` IN (5, 61, 100) AND `profile_id` = 16752 LIMIT 1)  AS NCode,
    (SELECT `value` Fname From `profile_features` WHERE `feature_id` IN (1, 55, 86) AND `profile_id` = 16752 LIMIT 1) AS Fname,
    (SELECT `value` Lname From `profile_features` WHERE `feature_id` IN (2, 56, 95) AND `profile_id` = 16752 LIMIT 1) AS Lname

but if one of the subqueries returns null, query have not any output.
I want a row result with TelNum, NCode, Fname, Lname either they are Null or not null.

A: You could use scalar subqueries in the select-list instead of your current Cartesian product:
SELECT (SELECT `value` FROM `profile_features` WHERE `feature_id` IN (10, 64, 103) AND `profile_id` = 16752 LIMIT 1) as TelNum,
  (SELECT `value` From `profile_features` WHERE `feature_id` IN (5, 61, 100) AND `profile_id` = 16752 LIMIT 1)  AS NCode,
  (SELECT `value` From `profile_features` WHERE `feature_id` IN (1, 55, 86) AND `profile_id` = 16752 LIMIT 1) AS Fname,
  (SELECT `value` From `profile_features` WHERE `feature_id` IN (2, 56, 95) AND `profile_id` = 16752 LIMIT 1) AS Lname;

Alternatively, you could learn to use LEFT OUTER JOIN:
SELECT TelNum.TelNum, NCode.NCode, Fname.Fname, Lname.Lname
FROM (SELECT NULL AS dummy) AS dummy
LEFT OUTER JOIN (SELECT `value` TelNum FROM `profile_features` WHERE `feature_id` IN (10, 64, 103) AND `profile_id` = 16752 LIMIT 1) AS TelNum ON true
LEFT OUTER JOIN (SELECT `value` NCode From `profile_features` WHERE `feature_id` IN (5, 61, 100) AND `profile_id` = 16752 LIMIT 1) AS NCode ON true
LEFT OUTER JOIN (SELECT `value` Fname From `profile_features` WHERE `feature_id` IN (1, 55, 86) AND `profile_id` = 16752 LIMIT 1) AS Fname ON true
LEFT OUTER JOIN (SELECT `value` Lname From `profile_features` WHERE `feature_id` IN (2, 56, 95) AND `profile_id` = 16752 LIMIT 1) AS Lname ON true;


text:
Q: VSCode / Intellisense : Exclude ES2020 support I work with an "old" version of NodeJS (Node 10) which does not support a few features like Promise.allSettled().
So, I would like exclude es2020 support in VSCode / Intellisense to remove autocomplete for theses features and VSCode/Intellisense and to show an error (like "unknown function").
How can I do this?


text:
Q: Saving / Restoring Eclipse state (open files, layout, ...) When working in Eclipse with CDT, I frequently have the need to switch contexts to work on a different issue within the same project for a while. This context switch usually requires me to have a different set of files open and sometimes also to use a different layout.
I have searched for quite some time but so far did not find a good solution (other than exiting Eclipse and copying the settings files), to simply store my current state (i.e. open files, layout, ...) and later restore it within Eclipse.
So my question is, is this context switch somehow possible in an easier way, e.g. with a plugin that I am not aware of?


text:
Q: Altering PDF through iTextSharp to Replace some existing text with a new text Please tell me if is there any function in iTextSharp that dose replace("xx","yy") function in the pdf file without altering remaining parts of the file.

A: Short answer: NO you cannot do that with iText.
Longer Answer: PDF is a display format, so when the PDF is rendered many decisions are made about page and character layout and positioning.  Chapter 6 of iText in Action has a great description in the introduction of why it is not a trivial task.  You can read Chapter 6 for free from the publisher's website.

A: I found a way to do this through PDF form Fields.
    String formFile = Server.MapPath("~/") + "source.pdf";

    String newFile = Server.MapPath("~/") + "sink.pdf";

    PdfReader reader = new PdfReader(formFile);

    PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create));

    AcroFields fields = stamper.AcroFields;

    // set form fields

    fields.SetField("{TO}", "John Doe");

    fields.SetField("{FROM}", "2 Milky Way, London");

    stamper.FormFlattening = true;

    stamper.Close();


text:
Q: VBA Basics - Calling Function From a Sub I want to write a Function Macro that calculates the days between two dates.  It looks like I have that.
Function daysRem(today As Date, eoc As Date) As Integer
    daysRem = Abs(DateDiff("d", today, eoc))
End Function

Now, I need to "Call" that function from a Sub to roughly estimate the number of weeks remaining.  I'd like that to be in a message box.  That's where I've hit about 2 hours of frustration.  This has got to be simple, but I just can't figure out what to do.

A: Try this:
Private Sub DisplayDaysDiff()
 Dim dtDate1 as Date
 Dim dtDate2 as Date

 dtDate1 =ThisWorkbook.Worksheets("Sheet1").Range("A2")
 dtDate2=ThisWorkbook.Worksheets("Sheet1").Range("B2")

 MsgBox "Days difference: " & CStr(daysRem(dtDate1, dtDate2)), vbInformation

End Sub

Call it from a button_click event

A: Sub Main
    x = MyFunction(Param1)
End Sub

MyFunction(MyDate as Date)
    MyFunction = DateDiff("ww", Date(), MyDate)
End Function

You assign the value to the function name. The inbuilt Date() function is todays date.
Functions return something. Subs don't. Macros ARE SUBS.
Functions return something.
So
Function Test
    Test = 5
End Function

Sub Main
    x = Test() + 5
End Sub

So x = 10.
Sub Main
    Param1 = #2/2/2017#
    Range("B4").Value = MyFunction(Param1)
End Sub

MyFunction(MyDate as Date)
    MyFunction = DateDiff("ww", Date(), MyDate)
End Function

Date is both a data type and a function. One doesn't have brackets and one does.


text:
Q: Example use of ARMA forecasting method  I have no experience in forecasting, so can anyone give me a step-by-step example or link to example-real values with ARMA forecasting method application?

A: In R, you can look at the help documents for arima and auto.arima (from the forecast package) for some short examples of arima modeling.
For example:
fit <- auto.arima(WWWusage)
plot(forecast(fit,h=20))


text:
Q: pandas groupby: can I select an agg function by one level of a column MultiIndex? I have a pandas DataFrame with a MultiIndex of columns:
columns=pd.MultiIndex.from_tuples(
    [(c, i) for c in ['a', 'b'] for i in range(3)])
df = pd.DataFrame(np.random.randn(4, 6),
                  index=[0, 0, 1, 1],
                  columns=columns)
print(df)

          a                             b
          0         1         2         0         1         2
0  0.582804  0.753118 -0.900950 -0.914657 -0.333091 -0.965912
0  0.498002 -0.842624  0.155783  0.559730 -0.300136 -1.211412
1  0.727019  1.522160  1.679025  1.738350  0.593361  0.411907
1  1.253759 -0.806279 -2.177582 -0.099210 -0.839822 -0.211349

I want to group by the index, and use the 'min' aggregation on the a columns, and the 'sum' aggregation on the b columns.
I know I can do this by creating a dict that specifies the agg function for each column:
agg_dict = {'a': 'min', 'b': 'sum'}
full_agg_dict = {(c, i): agg_dict[c] for c in ['a', 'b'] for i in range(3)}
print(df.groupby(level=0).agg(full_agg_dict))

          a                             b
          0         1         2         0         1         2
0  0.498002 -0.842624 -0.900950 -0.354927 -0.633227 -2.177324
1  0.727019 -0.806279 -2.177582  1.639140 -0.246461  0.200558

Is there a simpler way? It seems like there should be a way to do this with agg_dict without using full_agg_dict.

A: I would use your approach as well. But here's another way that (should) work:
(df.stack(level=1)
   .groupby(level=[0,1])
   .agg({'a':'min','b':'sum'})
   .unstack(-1)
)

For some reason groupby(level=[0,1] doesn't work for me, so I came up with:
(df.stack(level=1)
   .reset_index()
   .groupby(['level_0','level_1'])
   .agg({'a':'min','b':'sum'})
   .unstack('level_1')
)


text:
Q: AG_E_PARSER_BAD_PROPERTY_VALUE (Line 7;Position 51) This is my XAML code in my project, in this first i display MainListBox then display ChatListBox depending on user selection. When user select to chat then i got run time Xaml parseing exception.
this is my whole Xaml code...
<phone:PhoneApplicationPage
x:Class="DocomoMessenger.View.Buddies"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
shell:SystemTray.IsVisible="True" Loaded="PhoneApplicationPage_Loaded">

<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="126"/>
        <RowDefinition Height="580*"/>
        <RowDefinition Height="75"/>
    </Grid.RowDefinitions>

    <!--TitlePanel contains the name of the application and page title-->
    <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="2,2,0,2">
        <ProgressBar Height="3" Name="waitprogess" Margin="0,2,0,0" />
        <TextBlock x:Name="txtload" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,5,12,0" />
        <TextBlock x:Name="PageTitle" Text="page name" Margin="1,0,0,0" Style="{StaticResource PhoneTextTitle1Style}" HorizontalAlignment="Center" />
    </StackPanel>

    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="2,0,2,0">
        <Border BorderThickness="5" BorderBrush="DarkGray" CornerRadius="10" Name="buddyborder">
                <ListBox x:Name="MainListBox" >
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <Grid Height="100" >
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="50"/>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="50"/>
                                </Grid.ColumnDefinitions>
                                <Image Grid.Column="0" Source="{Binding IM}" Stretch="Fill" Width="50" Height="50" VerticalAlignment="Center" HorizontalAlignment="Center" ></Image>
                                <StackPanel Margin="1,4,0,0" Grid.Column="1" x:Name="details" Height="100">
                                    <TextBlock Text="{Binding Name}" Style="{StaticResource PhoneTextNormalStyle}" Foreground="Brown" Padding="10"/>
                                    <TextBlock Text="{Binding StatusMsg}" FontSize="{StaticResource PhoneFontSizeSmall}" TextWrapping="Wrap" Padding="10" />
                                </StackPanel>
                                <Image Tag="{Binding Name}" Source="{Binding IMChat}" Grid.Column="2" Stretch="Uniform" Width="40" Height="40" VerticalAlignment="Center" HorizontalAlignment="Center" Name="imgchat"  MouseLeftButtonUp="imgchat_MouseLeftButtonUp"></Image>
                                <Line Stretch="UniformToFill" Grid.ColumnSpan="3" Stroke="DarkGray" StrokeThickness="2" Margin="0,10,0,0" X1="10" Y1="10" Y2="10" VerticalAlignment="Bottom" />
                            </Grid>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
        </Border>

        <ListBox x:Name="ChatListBox" Margin="2,2,0,0" Opacity="1" Visibility="Collapsed" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid Name="megrid" Margin="3,5,0,0">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="40*"/>
                            <RowDefinition Height="40"/>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="{Binding FirstCol}"/>
                            <ColumnDefinition Width="20"/>
                            <ColumnDefinition Width="{Binding LastCol}"/>
                        </Grid.ColumnDefinitions>

                        <Image Name="imgbud" Source="{Binding IM}" Grid.Column="{Binding ImgCol}" Grid.Row="1" Stretch="Uniform" Width="50" Height="50"/>
                        <Rectangle Grid.RowSpan="2" RadiusY="20" RadiusX="20" Grid.Column="{Binding RectCol}" Fill="{Binding Bru}" />
                        <TextBlock Text="{Binding Name}" Grid.Row="0" TextWrapping="Wrap" Grid.Column="{Binding RectCol}" Padding="10" />
                        <TextBlock Text="{Binding Time}" Grid.Row="1" Grid.Column="{Binding RectCol}" Padding="10" />
                        <Path Data="{Binding Obj}" Fill="{Binding Bru}" Margin="0,0,-5,0" HorizontalAlignment="{Binding HorAlig}" Grid.Row="1" Grid.Column="1" VerticalAlignment="Center" />
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

    </Grid>

    <Grid x:Name="sendmsg" Height="75" VerticalAlignment="Bottom" Grid.Row="2" Visibility="Collapsed">
        <TextBox Name="txtmsg" Text="type" Padding="5" Opacity="0.8" MouseLeftButtonUp="txtmsg_MouseLeftButtonUp" Width="370" HorizontalAlignment="Left" />
        <Image Name="imgsend" Width="100" Height="46" Source="/DocomoMessenger;component/Themes/send.png" HorizontalAlignment="Right" Stretch="UniformToFill" Margin="0,12,4,17" MouseLeftButtonUp="imgsend_MouseLeftButtonUp"/>
    </Grid>
</Grid>

<!--Sample code showing usage of ApplicationBar-->
<!--<phone:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
        <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
        <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
        <shell:ApplicationBar.MenuItems>
            <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
            <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
        </shell:ApplicationBar.MenuItems>
    </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>-->

when I run this code i got following XamlParsinException error.

Anyone help me.
Thanks in Advance
Pavan.

A: I can't pin it down, it is a nearly generic message that doesn't say much.
Here is what I would do:

*

*Comment out all content so you are left with <PhoneApplicationPage ...>

*Comment out all C# code that depends on the XAML you just commented out

*Make sure the application compiles.

*Now slowly, step by step, add xaml elements back in. Until you find the offending line.

If 4. is too hard you could reverse this trick; comment out part by part.

A: whats in your PhoneApplicationPage_Loaded method?
apart from a missing end tag
   </phone:PhoneApplicationPage>

in your snippet above I was able to build and run this in WP7 7.1.  I did have to omit your Loaded and MouseLeftButtonUp refers though as I don't have your full code.


text:
Q: Scala: What is :: in { case x :: y :: _ => y}? Method or case class? object Test1 extends App {
    val list: List[Int] => Int = {
        case x :: y :: _ => y    //what is ::? method or case class?
    }
    println(list(List(1, 2, 3)))    //result is 2.
}

I set "syntax coloring" in scala IDE, foreground color of method I set Red. code snapshot:

And I can't open declaration of black ::, so I don't know what it is.
If black :: is method, it should be called by this way:
... {case _.::(y).::(x) => y}     //compile failed!

So, What is black ::? method or case class?
Thanks a lot!

A: I think it's a method as described here. For history's sake, in case that page goes away, here's the blurb:

About pattern matching on Lists
If you review the possible forms of patterns explained in Chapter 15,
  you might find that neither List(...) nor :: looks like it fits one of
  the kinds of patterns defined there. In fact, List(...) is an instance
  of a library-defined extractor pattern. Such patterns will be treated
  in Chapter 24. The "cons" pattern x :: xs is a special case of an
  infix operation pattern. You know already that, when seen as an
  expression, an infix operation is equivalent to a method call. For
  patterns, the rules are different: When seen as a pattern, an infix
  operation such as p op q is equivalent to op(p, q). That is, the infix
  operator op is treated as a constructor pattern. In particular, a cons
  pattern such as x :: xs is treated as ::(x, xs). This hints that there
  should be a class named :: that corresponds to the pattern
  constructor. Indeed there is such as class. It is named scala.:: and
  is exactly the class that builds non-empty lists. So :: exists twice
  in Scala, once as a name of a class in package scala, and again as a
  method in class List. The effect of the method :: is to produce an
  instance of the class scala.::. You'll find out more details about how
  the List class is implemented in Chapter 22.

So it's scala.::(a,b)

A: Here Sequence pattern is applied.
case x :: y :: _ => y
means, the passed sequence first value is mapped to x and second value is mapped to y and all remaining values are applied with wildcard pattern (_).
Here finally the case returns y means second value.
another ex: case x :: y :: z :: _ => z
this case returns third element from the sequence.
another ex: case _ :: _ :: z :: _ => z
in this example first and second element are used underscore as we don't need THESE elements hence replaced with _.
Also it throws Exception if the passing list size is less than what it expects, for Example the below throws exception:
val third: List[Int] => Int = {case _ :: _ :: z :: _ => z}

third(List(1, 2))


text:
Q: ¿Cómo funciona un archivo .ASP y cómo puedo acceder por url, si está en un servidor? Estoy aprendiendo recién todo lo que es javascript, jQuery y me encontré con el método ajax() para mandar peticiones y recibir respuestas de un servidor, y en la w3schools.com hay un ejemplo de jQuery con el método POST(), en donde se mandan datos a un servidor que contiene un archivo ASP para recibir una respuesta concreta, en este caso son sugerencias o suggestion para completar una frase. Dejo el ejemplo en código:
<!DOCTYPE html>

Start typing a name in the input field below:

    First name:

    <input type="text">

Suggestions:

The file used in this example (demo_ajax_gethint) is explained in our Ajax tutorial

En este ejemplo en el apartado de Suggestion aparece una frase de acuerdo a la inicial que se ingrese en el input, dejo el link del ejemplo para que puedan revisarlo bien. Mi problema es que cuando intento acceder al contenido del archivo .ASP solo me aparece "no suggestion" cuando debería aparecer todas las sugerencias de palabras posibles. En el mismo código se puede ver que explican lo que contiene el archivo .ASP , pero muestran su contenido desede un archivo .txt
<%
    response.expires=-1
    dim a(30)
    'Fill up array with names
    a(1)="Anna"
    a(2)="Brittany"
    a(3)="Cinderella"
    a(4)="Diana"
    a(5)="Eva"
    a(6)="Fiona"
    a(7)="Gunda"
    a(8)="Hege"
    a(9)="Inga"
    a(10)="Johanna"
    a(11)="Kitty"
    a(12)="Linda"
    a(13)="Nina"
    a(14)="Ophelia"
    a(15)="Petunia"
    a(16)="Amanda"
    a(17)="Raquel"
    a(18)="Cindy"
    a(19)="Doris"
    a(20)="Eve"
    a(21)="Evita"
    a(22)="Sunniva"
    a(23)="Tove"
    a(24)="Unni"
    a(25)="Violet"
    a(26)="Liza"
    a(27)="Elizabeth"
    a(28)="Ellen"
    a(29)="Wenche"
    a(30)="Vicky"

    'get the "suggest" parameter from URL
    q=ucase(request.querystring("suggest"))

    'lookup all hints from array if length of q>0
    if len(q)>0 then
      hint=""
      for i=1 to 30
        if q=ucase(mid(a(i),1,len(q))) then
          if hint="" then
            hint=a(i)
          else
            hint=hint & " , " & a(i)
          end if
        end if
      next
    end if

    'Output "no suggestion" if no hint were found
    'or output the correct values
    if hint="" then
      response.write("no suggestion")
    else
      response.write(hint)
    end if
    %>

Pero cuando se ejecuta el código y utilizo el depurador de Chrome me aparece que estoy recibiendo datos del archivo .ASP y cuando me dirijo al archivo por medio del url que me arroja el depurador, no aparece todo el contenido. Dejo pantallazos para que se entienda mejor

Se puede ver que hago una consulta con la inicial "a" que arroja como resultado la carga al archivo .ASP donde dice XHR ha terminado de cargar: POST "https://www.w3schools.com/jquery/demo_ajax_gethint.asp". que incluso al hacer clic en el enlace me muestra detalles de la respuesta del archivo y claramente dice que he recibido los nombres "Anna, Amanda"

Lamentablemente el depurador no me deja explorar más allá de la respuesta del archivo .ASP, pero cuando copio el url del archivo y lo pongo en el navegador solo aparece "no suggestion" aunque modifique el url y ponga el data de la petición en ella que sería "suggest=a" lo que dejaría la url así: https://www.w3schools.com/jquery/demo_ajax_gethint.asp?suggest=a

¿Alguien me podría explicar cómo funciona el archivo .ASP? Ya que no me arroja los datos que aparecen en el ejemplo del archivo de texto y tampoco me aparece la repuesta que me arroja el depurador de Chrome ("Anna, Amanda"). Obviamente el problema es que no sé acceder al contenido del archivo, dado que no soy experimentado en código, pero sí me gustaría entender el proceso que hay de fondo.


text:
Q: Javascript Imports a single bootsrap JS file Is it possible to create a bootsrap JS file to Import files?
E.g
Bootsrap.js
I want to have all my JS imports to be handled by this file and like the __autoload() in PHP
so in my Index.js, I want to import Bootstrap from './Imports';
Then call any Constant or Variable imported by the Bootstrap.js file in my Index.js anytime
e.g <View/>, <Text>My text</Text> anywhere in my Index.js

A: It's not possible to do this natively, at least not yet.
It has been a planned feature for some time though, at least according to this source.

The module loader API has various hooks for configuration. It is still work in progress. A first system loader for browsers is currently being implemented and tested. The goal is to figure out how to best make module loading configurable.
The loader API will permit many customizations of the loading process. For example:

*

*Lint modules on import (e.g. via JSLint or JSHint).

*Automatically translate modules on import (they could contain CoffeeScript or TypeScript code).

*Use legacy modules (AMD, Node.js).

Configurable module loading is an area where Node.js and CommonJS are limited.

AFAIK, there hasn't been much progress on this yet.


text:
Q: How to handle get requests automatically if template exists (using node.js+express) I'm using node.js with express (and EJS as the template language) and would like to know if there is an easy way to automatically handle serving pages matching a given path if a template exists in the template directory.
For example:
app.get('/subdir/:pagename', function(req, res, next) {
    // Automatically & securely load 'pagename' only if
    // '/subdir/pagename.ejs' exists in my template dir
    res.render(subdir/pagename);
});

I know I could just write a secure handler for this myself by striping everything that isn't A-z0-9-_ from :pagename and then checking if the file exists (and serving a 404 if it doesn't) but curious to know if there is a better way built into node.js than writing some boilerplate to handle it it.
NB: I have static pages served this way already, the only reason these pages are not static are they use the layout system to give them a common header+footer.
Will happily accept "No there isn't." as an answer if there are any Express experts or anyone who's looked into this already!

A: Been using express since the beginning – sorry, the answer is no. TJ did this for good reason as this functionality is specific to your use case and doesn't belong in a framework. You could look to see if anyones written a module in npm for this feature, but as you know, its not very hard to roll your own.
Happy Hacking! =)


text:
Q: Include zero counts when grouping by multiple columns and setting filters I have a table (tbl) containing category (2 categories), impact (3 impacts), company name and date for example:
category | impact   | company | date      | number
---------+----------+---------+-----------|
Animal   | Critical | A       | 12/31/1999|1
Book     | Critical | B       | 12/31/2000|2
Animal   | Minor    | C       | 12/31/2001|3
Book     | Minor    | D       | 12/31/2002|4
Animal   | Medium   | E       | 1/1/2003  |5

I want to get the count of records for each category and impact and be able to add rows with zero count and also be able to filter by company and date.
In the example result set below, the count result is 1 for category = Animal and company = A. The rest is 0 records and only the Critical and Medium impacts appear
category | impact   | count
---------+----------+-------
Animal   | Critical |   1
Animal   | Medium   |   0

I've looked at the responses to similar questions by using joins however, adding a WHERE clause doesn't include the zero records.
I also tried doing outer joins but it doesn't produce desired output. For example
select a.impact, b.category, ISNULL(count(b.impact), 0) from tbl a
left outer join tbl b
on b.number = a.number
and (a.category = 'Animal' and a.company in ('A'))
group by a.impact, b.category

produces
impact   | category   | count
---------+------------+--------
Medium   |  NULL      | 0
Medium   | Animal     | 1
Critical |  NULL      | 0
Minor    |  NULL      | 0

but the desired output should be
category | impact   | count
---------+----------+-------
Animal   | Critical |   1
Animal   | Medium   |   0
Animal   | Minor    |   0

Any help will be appreciated. Answers to associated questions don't have filtering so I will appreciate if someone can help with a query to produce desired output.

A: You need a master table with all the possible combinations of Categories and Impacts for this. Then Left join your table with the master and do the aggregation. Something like below
;WITH CAT
AS
(
    SELECT
        category
        FROM Tbl
        GROUP BY category
),
IMP
AS
(
    SELECT
        Impact
        FROM Tbl
        GROUP BY Impact
),MST
AS
(
    SELECT
        *
        FROM CAT
            CROSS JOIN IMP
)
SELECT
    MST.category,
    MST.Impact,
    COUNT(T.Number)
    FROM MST
        LEFT JOIN Tbl T
            ON MST.category = T.category
                AND MST.Impact = T.Impact
                AND T.Company = 'A'
        WHERE MST.Category = 'Animal' GROUP BY MST.category,
    MST.Impact


text:
Q: Check if all bodies are stopped I am new to physics engines. I am using Cocos2dx v3.4 with physics engine Chipmunk.
How can I check whether all bodies are stopped or not?

A: Try method body.isSleeping() during iterating over all bodies.
Link: https://chipmunk-physics.net/forum/viewtopic.php?f=4&t=1103

A: This is the way I check if one sprite is stopped:
#define STOP_VELOCITY 1.

if (sprite->getPhysicsBody()->getVelocity().x > STOP_VELOCITY || sprite->getPhysicsBody()->getVelocity().x < -STOP_VELOCITY ||
    sprite->getPhysicsBody()->getVelocity().y > STOP_VELOCITY || sprite->getPhysicsBody()->getVelocity().y < -STOP_VELOCITY) {
        return false;
    } else {
        sprite->getPhysicsBody()->setVelocity(Vec2(0,0));
        return true;
    }
}


text:
Q: MongoDB&NodeJS: How to display a certain field on a Jade file on a server So I just started learning MEAN and I want to show only a certain field of a database I've made to a Node server. I'm using Express as well. Here is my code so far.
index.js
router.get('/generate', function(req, res) {
// get out mongoclient to work with our mongo server
var MongoClient = mongodb.MongoClient;

// where the mongodb server is
var url = 'mongodb://localhost:27017/data';

MongoClient.connect(url, function(err, db) {
    if(err) {
        console.log('Unable to connect to server', err);
    } else {
        console.log('Connection established');

        var collection = db.collection('compliments');

        collection.find({}).toArray(function(err, result) {
            if (err) {
                res.send(err);
            } else if (result.length) {
                res.json(result); // problem here
            } else {
                res.send('No documents found');
            }

            db.close();
        });
    }
});

});
generate.jade
doctype html
html
head
    title("Compliment Generator")
body
    h1 !{title}
    block content
        h3.
            !{compliment}

This is what it looks like on localhost:3000/generate
[{"_id":"570b50f8265f2536d2fd6ed6","type":"compliment","content":"You are absolutely gorgeous."},{"_id":"570b50f8265f2536d2fd6ed7","type":"compliment","content":"You are wonderful."},{"_id":"570b50f8265f2536d2fd6ed8","type":"compliment","content":"I could look at you all day."}]

How do I make it so that it only displays the "content"? Thanks!

A: If I understand correctly you only want the content to be returned from the query.
The below link should be of use:
https://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/
You essentially want to modify the query to only retrieve the "Content" part like so:
collection.find({}, { content: 1, _id:0 })

This will specify that you don't want to include the "_id" (which is included by default) and you do want to include the "content".


text:
Q: Find all installed modules QML I'm creating app which ui is defined in json, from which i instatiate components in qml files from C++. But i would be glad if users can use built-in qml types.

*

*Is there some way to find what qml modules (mainly visible components, but listing of all qml modules is huge plus) are installed in system?

*Is there other solution for this problem. I'm thinking like create qml string manually, but what about imports?
Any other tips will be apreciated.


text:
Q: Plivo SIP problems with NAT traversal Ok, I've looked and looked, and can't seem to find anyone that's written about this problem. I have a simple office setup where there are two SIP phone extensions (Polycom 331) behind a Sonicwall TZ180. I'm using Plivo as the PBX. The extensions register directly with Plivo.
Plivo --> [Internet] --> TimeWarner Modem --> Sonicwall TZ180 --> POE Switch --> Polycom 331s x2

I've setup the firewall & NAT rules on the TZ180 such that everything works... for a while. After the sonicwall & phones are rebooted, the phones can both receive and make calls without issue. Once some time has passed (not sure how much, but more than a few hours, may even be a few days), the phones stop accepting INCOMING calls, but outgoing calls are fine.
So, to me this seems like a NAT issue, except for the part where everything works fine for awhile! And I really do mean it works fine. Call phone 1, talk for a bit, then call phone 2, talk for a bit, call phone 1 again, talk for a bit, call phone 2, talk for a bit, repeat. But then, after some unknown amount of time with no calls, the above ceases to work for both phones.
The Sonicwall firewall is set to pass UDP 5060-5061 and UDP/TCP 10000-20000. The phones are provided with static private IPs by the Sonicwall. The Sonicwall's consistent NAT is enables, and SIP transformations are disabled (which seems to be the consensus I found elsewhere).
Any ideas? The only way we can seem to detect that the phones have stopped working for incoming calls is to wait until a voicemail is delivered, but someone was sitting next to the phone. Also, I'd rather not have to reboot my entire network just to get another day or two each time.

A: Ok, after struggling with wireshark, I've essentially discovered that the Sonicwall TZ180, being as old as it is, just doesn't like holding multiple NAT paths open. I've solved the problem with a Raspberry Pi running asterisk and acting as a SIP Proxy.


text:
Q: How can I transform the intrinsic and extrinsic matrix into opengl projection and view matrix correctly I have some 3D points near origin, camera intrinsic and extrinsic matrix. I can get correct 2D points through projectPoints(using x = intrinsic * extrinsic * X) function in opencv. But when I want to render these 3D points using opengl, it can't work well.
I just transformed intrinsic matrix into glm mat4 as follow:
proj[0][0] = 2 * fx / width;
proj[1][0] = 0.0f;
proj[2][0] = (2 * cx - width) / width;
proj[3][0] = 0.0f;
proj[0][1] = 0.0f;
proj[1][1] = -2 * fy / height;
proj[2][1] = (height - 2 * cy) / height;
proj[3][1] = 0.0f;
proj[0][2] = 0.0f;
proj[1][2] = 0.0f;
proj[2][2] = -(far_clip + near_clip) / (near_clip - far_clip);
proj[3][2] = 2 * near_clip * far_clip / (near_clip - far_clip);
proj[0][3] = 0.0f;
proj[1][3] = 0.0f;
proj[2][3] = 1.0f;
proj[3][3] = 0.0f;

The fx,fy are focal length, width and height are the width and height of image, cx and cy is width / 2 and height / 2 (I get camera matrix through it).
Then I transposed the 4*4 extrinsic matrix as glm view matrix because of the column major in opengl. In my shader, I got gl_Position through
gl_Position = proj * view * vec4(3Dpointposition, 1.0f)

But I got wrong rendering result in screen. I got my camera matrix with the origin in the top-left, and the origin in opengl is in the bottom-left, It also seems that the camera in opencv looks down the positive z-axis but the opengl camera looks down the negetive z-axis. How can I modify the code to the correct version?


text:
Q: Using Slider to show dowloading progress in WP7? Can I use Slider to show downloading progress? What about usability, user experience and main one Market Place limitation. Or you have another idea how to show not only process, but progress to?

A: The progress bar can be used in IsIndeterminate=False mode can give you what you're looking for. The progress is indicated using the Value property, which you can keep updating. See documentation.
See this article


text:
Q: How to remove duplication from UITableView sections Swift 3 I am having issue in removing duplicate from section of tableview. I am using 2 section so I want to remove duplication of items from second section which are already available in section 1 so kindly guide me about it? I am using two array which are coming from sql server using WCF web-service. Here is my cellforrowAt code
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

var cell : UITableViewCell!

if tableView == self.diseasetableview
{
let cell1 = tableView.dequeueReusableCell(withIdentifier: "diseasenamecell", for: indexPath) as! FoodTableViewCell

cell1.selecteddiseasename.text = selectedDiseaseName[indexPath.row]
    cell = cell1

}
if tableView == self.foodtableview
{
    if indexPath.section == 0
    {
        print(indexPath.section)
    let cell2 = tableView.dequeueReusableCell(withIdentifier: "foodnamecell", for: indexPath) as! FoodnameTableCell

   cell2.foodnamelbl.text = food[indexPath.row]
    cell = cell2
    }
    if indexPath.section == 1
    {

        print(indexPath.section)
        print(notRecomended[indexPath.row])

        let cell3 = tableView.dequeueReusableCell(withIdentifier: "foodnamecell", for: indexPath) as! FoodnameTableCell

            cell3.foodnamelbl.text = notRecomended[indexPath.row]
            cell = cell3

    }

}
return cell

}

A: Check for duplicates in your second array and remove duplicates items.
secondArray = secondArray.filter {firstArray.contains($0) == false}

A: Have a filered array using the below code and for that section use filtered array
     let notRecomended = ["food1", "food3", "food4", "food2", "food6","food2"]
     let food = ["food1", "food2"]
     let filteredResult = notRecomended.filter { !food.contains($0) }) }


text:
Q: Is the Prism Template Studio available for Visual Studio for Mac 8.0? I started using the Prism Template Studio with Visual Studio for Mac version 7.x a few days ago.  Today Visual Studio updated and I no longer have access to the handy Prism extensions.
I've tried opening the Extensions Manager and going to the Gallery tab to re-install the Template Studio, but when I search for Prism, nothing shows up.
I expected to find the Prism Template Studio listed.  Is there a version that supports Visual Studio for Mac 8.0 or is there plan to add support?
TIA


text:
Q: Send $_POST to 2 php files at once i have no idea how to solve a problem with sending $_POST. I want to fill a form at example.com
//at example.com
<form action="foo.php" method="post" >
<input name="bar1" type="text" />
<input name="bar2" type="text" />
<input name="bar3" type="text" />
<input value="Send" type="submit" />
</form>

and then it goes to foo.php :
<?php //foo.php
echo 'added:
'.$_POST['bar1'].'
'.$_POST['bar2'].'
'.$_POST['bar3'];
?>

and in the same time it also send
$_POST['bar1'], $_POST['bar2'], $_POST['bar3']

to exampledomain.com/foobar.php where it can be saved to a file - that's not a problem.
I don't know how to send info to both php scripts at once - one is external one. I guess i have to send it somehow inside foo.php
There is kind of solution - redirecting to exampledomain.com/foobar.php inside foo.php but it isn't acceptable in my case - I want to do it without making user exit example.com
Thanks in advance and hope you can undestand my problem - if not just ask a comment
EDIT: Based on Pete Herbert Penito's answer:
 <?php //inside foo.php
 $url = 'http://exampledomain.com/foobar.php';
 $fields_string='';
 foreach($_POST as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
 rtrim($fields_string,'&');

 //open connection
 $ch = curl_init();

 //set the url, number of POST vars, POST data
 curl_setopt($ch,CURLOPT_URL,$url);
 curl_setopt($ch,CURLOPT_POST,count($_POST));
 curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

 //execute post
 $result = curl_exec($ch);

 //close connection
 curl_close($ch);

  ?>

A: I would use CURL to construct a post request:
<?php
 // these variables would need to be changed to be your variables
 // alternatively you could send the entire post constructed using a foreach
 if(isset($_POST['Name']))     $Name   = $_POST['Name'];
 if(isset($_POST['Email']))   $Email   = $_POST['Email'];
 if(isset($_POST['Message']))   $Message= htmlentities($_POST['Message']);

 $Curl_Session = curl_init('http://www.site.com/cgi-bin/waiting.php');
 curl_setopt ($Curl_Session, CURLOPT_POST, 1);
 curl_setopt ($Curl_Session, CURLOPT_POSTFIELDS, "Name=$Name&Email=$Email&Message=$Message");
 curl_setopt ($Curl_Session, CURLOPT_FOLLOWLOCATION, 1);
 curl_exec ($Curl_Session);
 curl_close ($Curl_Session);
?>

From Link:
http://www.askapache.com/php/sending-post-form-data-php-curl.html

A: In your foo.php:
<?php
include 'http://exampledomain.com/foobar.php';

Note: you need to enable allow_url_fopen in your php.ini file.

A: You will need to do one of the POST's with javascript ajax.
Then the real post which will redirect the browser like normal.
http://www.w3schools.com/jquery/ajax_post.asp
$(selector).post(url,data,success(response,status,xhr),dataType)


text:
Q: How to I parse tuple value as an Person Object? I have implemented a Logger Bolt in storm, the input of the tuple is coming from Kafka Topic. I am using Kafka Connect to listen to changes to mySQL database.
public class LoggerBolt extends BaseBasicBolt {

  private static final long serialVersionUID = 1L;
  private static final Logger LOG = Logger.getLogger(LoggerBolt.class);

  public void execute(Tuple input, BasicOutputCollector collector) {
     System.out.println(input.getValue(0));
  }

  public void declareOutputFields(OutputFieldsDeclarer declarer) {
  }
}

When run on local cluster below gets printed.

Q�%Buckley, Rose     RoseBuckley"BuckleyR@univ.edu"963.555.6855x5018963.777.5233Curator
  Q� Stanton, Kathie KathieStanton"StantonK@univ.edu963.555.7095963.777.1015Professor
  Q�Banks, Shannon Shannon
  BanksBanksS@univ.edu963.555.7198963.777.6979Professor
  Q�/Barnes, Cleo CleoBarnes
  BarnesC@univ.edu"963.555.7463x7335963.777.1583$Research Professor

I want to cast these details to Person Object, which is a model class?
How do we parse the Tuple input into an object?
I tried input.getValues(0) , input.getFields(0) and other method, none seems to work.

A: If you're using storm-kafka-client, it assumes Strings by default. You can choose something else by doing e.g. kafkaSpoutConfig.setProp(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class);. The class you set just has to implement the Kafka Deserializer interface https://kafka.apache.org/11/javadoc/org/apache/kafka/common/serialization/Deserializer.html.
There's an equivalent setting for setting the key deserializer.


text:
Q: Android - Remove file from removable SD Card using its path (Kitkat and above) issue I'm creating Android app with possibility to show images. It also allows to remove them. I have problem with dealing with removable SD Card (KitKat and above).
I'm prompting user to give permissions to SD Card:
startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), REQUEST_SD_CARD_PERMISSION);

Here's my code in onActivityResult(int requestCode, int resultCode, Intent data):
if (requestCode == REQUEST_SD_CARD_PERMISSION && resultCode == RESULT_OK) {
    int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    Uri uri = data.getData();
    getContentResolver().takePersistableUriPermission(uri, takeFlags);
}

I have uris for images in form like this: /storage/7255-A3FF/test/gtfht.jpeg
When I try to delete it after calling takePersistableUriPermission(Uri, int):
new File("/storage/7255-A3FF/test/gtfht.jpeg").delete();

I get exception:
EACCES (Permission denied) : /storage/7255-A3FF/test/gtfht.jpeg

Removing files from internal storage is working fine (WRITE_EXTERNAL_STORAGE permission is granted).
What am I doing wrong? Is it even possible to remove file using its path? If not how to do that?
I want to avoid situation that user should select every file using Intent.ACTION_OPEN_DOCUMENT.

edit:
I have filesystem paths to images from
    String[] projection = new String[]{
            MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
            MediaStore.Images.Media.DATA,
            MediaStore.Images.Media._ID
    };

    Cursor cur = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            projection,
            null,
            null,
            null
    );


text:
Q: Error creating bean with name 'costsEntityManagerFactory' defined in class path resource We are getting exception

Error creating bean with name 'costsEntityManagerFactory' defined in class path resource...Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: consolidatedCosts] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.search.util.common.SearchException: HSEARCH000573: Invalid configuration passed to Hibernate Search: some properties in the given configuration are obsolete.Configuration properties changed between Hibernate Search 5 and Hibernate Search 6 Check out the reference documentation and upgrade your configuration.

Here is the code snippet
 @Bean
public LocalContainerEntityManagerFactoryBean costsEntityManagerFactory(
        final EntityManagerFactoryBuilder builder,
        final @Qualifier("awsCostsDataSource") DataSource costsDataSource) {
    final Map<String, String> properties = new HashMap<>();
    properties.put(
            "hibernate.dialect",
            "com.x.y.consolidatedcosts.client.xxxxxPostgresDialect");
    properties.put(
            "hibernate.physical_naming_strategy", CostsTableNamingStrategy.class.getName());
    return builder.dataSource(costsDataSource)
            .packages("com.xxx.xxx.consolidatedcosts")
            .persistenceUnit("consolidatedCosts")
            .properties(properties)
            .build();
}


text:
Q: Should a field be left null or initialized to a default value when fetching data from an API in null safe Dart? Should I set a value to every null fields when retrieving something something from an api? Or should I keep them null and check when displaying them if they aren't null?
Ex:
  factory Geo.fromJson(Map<String, dynamic> json) => Geo(
    type: json["type"] == null ? 'Point' : json["type"],
    coordinates: json["coordinates"] == null ? [] : List<double>.from(json["coordinates"].map((x) => double.tryParse(x))),
  );

or
  factory Geo.fromJson(Map<String, dynamic> json) => Geo(
    type: json["type"] == null ? null : json["type"],
    coordinates: json["coordinates"] == null ? null : List<double>.from(json["coordinates"].map((x) => double.tryParse(x))),
  );

Edit --> or should I be doing this in an other way like this maybe?
  factory Location.fromJson(Map<String, dynamic> json) {
    return Location(
      geo: json["geo"] = Geo.fromJson(json["geo"]),
      city: json["city"] = json["city"],
      country: json["country"] = json["country"],
      area: json["area"] = json["area"],
    );
  }

A: null-safety in Dart is not a campaign to get rid of null. null is a valid information.
Take the easiest example: does my wife want a pizza? Seems like an easy true/false question. Until you consider that "I haven't asked her yet" is indeed a real world state that is just as valid.
So no, you should not replace all your null values with something else. You would lose information.
So again: null safety does not mean you get rid of the null value. It means you no longer get surprised by the null value.
If you have values that can legitimately be null, then let them be.
You got improved compiler support now to make sure you don't drop the ball and mistakenly assume they are always non-null. That's great. Be happy about it.


text:
Q: ActiveRecord::RecordNotFound "Couldn't find user with id=new" Whenever I click on update button in my form it redirects to /users/new.1 raising the error Couldn't find User with id=new. Help Please!
user_controller.rb
  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      redirect_to @user
    else
      render "edit"
    end
  end

  private
  def user_params
    params.require(:user).permit(:id, :name, :password, :password_confirmation, :email, :password_salt, :password_hash, :phone)
  end

edit.html.erb
<%= form_for @user, url: user_path(@user), method: :patch do |f| %>

        <%= f.label :name %>

        <%= f.text_field :name %>

        <%= f.label :mobile %>

        <%= f.text_field :phone %>

        <%= f.label :email %>

        <%= f.text_field :email  %>

        <%= f.label :role %>

        <%= f.text_field :role  %>

<%= f.submit "Update"%>

<% end %>

routes.rb
  get "logout" => "pages#destroy", :as => "logout"
  get 'welcome/index'
  get 'users/new', :as => 'user'
  root :to => 'welcome#index'
  resources :users

A: Remove the extraneous get 'users/new', :as => 'user' line from your routes.rb file.  The resources :users handles all CRUD routes for you.

A: For redirect_to you have to give it the path (or controller and action).
You'll want to use this:
redirect_to user_path(@user)
Here's the rails reference on the subject: http://api.rubyonrails.org/classes/ActionController/Redirecting.html


text:
Q: Pasar valores de un listbox a un textbox Tengo el siguiente problema, quisiera pasar un valor de un listbox concatenado a una base de datos a un textbox, pero en mi codigo no funciona ello.
Uso VS 2019
Codigo cs
namespace User_Login_CS
{
    public partial class usuariossistemas : System.Web.UI.Page
    {
        public DataTable CargarDatos()
        {
            string str = "Data Source=IP; Initial Catalog=iLogistica; Persist Security Info=True; user id=USER; password=PASS;";
            SqlConnection con = new SqlConnection(str);
            string com = "SELECT * FROM  [dbo].[UsuariosSistema] ORDER BY Nombre ";
            SqlDataAdapter adpt = new SqlDataAdapter(com, con);
            DataSet myDataSet = new DataSet();
            adpt.Fill(myDataSet, "UsuariosSistema");
            DataTable myDataTable = myDataSet.Tables[0];
            return myDataTable;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dt = CargarDatos();
                foreach (DataRow fila in dt.Rows)
                {
                    ListBox1.Items.Add(fila[0] + " (" + fila[1] + ") (" + fila[2] + ")");
                }
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            DataTable tabla = CargarDatos();
            int indice = ListBox1.SelectedIndex;
            TextBox1.Text = Convert.ToString(tabla.Rows[indice]["Nombre"]);
        }
    }

}

Codigo ASPX
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="usuariossistemas.aspx.cs" Inherits="User_Login_CS.usuariossistemas" %>
    <asp:ListBox ID="ListBox1" class="form-control listadenombres" runat="server"></asp:ListBox>
    <asp:Button ID="Button1" runat="server" Text="Button" />
    <asp:TextBox class="form-control nombresyapellidos" ID="TextBox1" runat="server"></asp:TextBox>

A ver si me hechan una ayuda.
Saludos !
pd. Saben de algun emulador para estos codigos tipo jsfiddle.net ?

A: Mi error, lo había tratado como un DataGridView, prueba agregando el .ToString()
Prueba cambiando esta funcion:
protected void Button1_Click(object sender, EventArgs e)
{
            DataTable tabla = CargarDatos();
            int indice = ListBox1.SelectedIndex;
            TextBox1.Text = Convert.ToString(tabla.Rows[indice]["Nombre"]);
}

por esta:
protected void Button1_Click(object sender, EventArgs e)
{
            DataTable tabla = CargarDatos();
            int indice = ListBox1.SelectedIndex;
            TextBox1.Text = CargarDatos().Rows[indice ]["Nombre"].ToString();
}


text:
Q: Analyzing RAM dump in Android In case of Kernel Panic in Android we dump all RAM data in a file. In this case RAM addresses are Physical addresses. But in logs if we print address of any variable then that address is Virtual address. From dump if I want to know what data is stored in that virtual address (printed via logs) then how can I get that information from RAM dump.
Also is there any Swap area like thing in Android? Swap concept is in Linux OS.

A: you program running in user mode should not cause Kernel Panic, but application crash.
anyhow kernel development is completely different, I think the physical address for virtual address should be found in the process's page table.


text:
Q: PHP if else to check ipaddress against ones stored in table I've got just a quick little poll and a query to check and see if the IPaddress is already in the table to know if someone has already voted. I have the table created already and it works.
My question is with the if else statement it is not working. I am trying to make it
if ip address is in the table show string
else show poll
$ip=$_SERVER['REMOTE_ADDR'];

include("../db/config.php");
include("../db/opendb.php");

$result = mysql_query("SELECT * FROM Poll WHERE ip='$ip'");

if ($result==$ip) {
    echo "Thank you for voting.";
} else {
    echo "<form action=logvote.php method=post>" .
         "<input type=radio name=ans value=ans1> Answer1
" .
         "<input type=radio name=ans value=ans2> Answer2
" .
         "<input type=radio name=ans value=ans3> Answer3
" .
         "<input type=radio name=ans value=ans4> Answer4
" .
         "<input type=submit value=Submit>";

    echo "<input type=hidden name=ip value=";
    echo "$ip>";

    echo "</form>";

 include("../db/closedb.php");

}

Thanks in advance.

A: You simply forgot to fetch a row first. Also, you can get the necessary information with a simple count:
$result = mysql_query("SELECT COUNT(*) as 'count' FROM Poll WHERE ip='$ip'");
$row = mysql_fetch_assoc($result);

if ($row['count']) {
    // show string
} else {
    // show poll
}

A: Your code should be:
$query = mysql_query("SELECT ip FROM Poll WHERE ip='$ip'");
$info = mysql_fetch_object($query);
$result = $info->ip;

if($result == $ip)

mysql_query() returns a reference not a string.
Also, using ip in the SELECT statement will speed up your code.

A: mysql_query does not return the data directly but rather a reference to the result.
You can get the number of rows found for the query with:
$num = mysql_numrows($result);
So you can check by:
$result = mysql_query("SELECT ip FROM Poll WHERE ip='$ip'");
if (mysql_numrows($result)) {
    // dostuff
} else {
    // do other stuff
}

// you can retrieve the ip like so:
$data = mysql_fetch_assoc($result);
$ip = $data['ip'];


text:
Q: Unable to setup a connection to Amazon EC2 and run pig I have made an EC2 key pair and saved it to a location under my home directory on mac. Also I have changed permissions with 'chmod 600 /path/to/saved/keypair/file.pem'. Now I have followed the following instructions to run pig on EC2:
To set up and connect to a pig cluster, perform the following steps:

*

*Go to http://console.aws.amazon.com/elasticmapreduce/home signing
in if necessary.

*Click the "Create Cluster".

*Enter "Data Science Assignment Cluster" or anything you wish as the Cluster Name.

*Uncheck the Logging box so that it is disabled.

*Scroll down to Software Configuration and select AMI Version 2.4.2  (We will be using Hadoop 1.x for compatibility with the version of Pig)

*Scroll down to "Security and Access" and select the Key Pair you created above.

*Scroll to the bottom and select "Create Cluster"

*On the next page, information about your cluster will be displayed.  It will begin in the "Starting" state and may take
several minutes to startup completely.

*Once the cluster has started, you will see a "Master Public DNS" name of the form ec2-XX-XXX-X-XXX.compute-1.amazonaws.com. Make a
note of this; we will refer to it as
master.public-dns-name.amazonaws.com.

*Now you are ready to connect to your cluster and run Pig jobs. From a terminal, use the following command:  $ ssh -o
"ServerAliveInterval 10" -i /path/to/saved/keypair/file.pem
hadoop@master.public-dns-name.amazonaws.com

Having done this I only get a '>' prompt after hitting enter. Further if I write pig at the '>' prompt then I get again a '>' prompt in the next line i.e. no 'grunt' prompt. I have checked that ssh is installed on my mac and remote login is enabled for all users. What seems to be the problem here?

A: If you managed to ssh to the Cluster's master instance, typing in "pig" in the prompt should result in something (either a grunt prompt or an error message of some sort). Did you make sure that pig is installed on the EMR cluster? (I don't see it in your directions)

A: The problem seemed to be generating from the path name of the EC2 key pair in the ssh command. My key pair was on desktop. So earlier, I tried executing the ssh command from the HOME$ prompt and mentioned the pathname of key pair file in the ssh command from the last step of the instructions as '/desktop/key-pair-filename.pem', and it dint work.
But then, at the terminal window I changed to the desktop directory. After that I executed the ssh command this time with simply putting 'key-pair-filename.pem' instead of '/desktop/key-pair-filename.pem' and it worked.


text:
Q: Unable to change the working directory inside a docker container using python script I am able to get inside a docker container using below command
os.system('docker exec -ti $(docker ps -q -a --filter "name=XXXXX") /bin/bash')

and then i need to change to the following directory in the container.
/u01/oracle/weblogic/*****

when i use os.chdir("/u01/oracle/weblogic/*****"), i am getting No such Directory error.
I could see that os.getcwd() is still printing the previous directory where the python script is running instead of docker directory.
Could someone let me know what i am missing ?

A: Why don't you use the container name as exec parameter, instead of using a query to get the id?
You can use the -c parameter of bash to execute multiple commands. Like:
os.system('docker exec -ti XXXXX /bin/bash -c "cd /tmp;ls -alrt"')


text:
Q: How do I know which GPU would be sufficient for a problem? I'm using https://github.com/tensorflow/models/blob/master/research/object_detection for object detection, and am finding that running the vanilla Faster R-CNN algorithm on my computer for inference is running entirely too slowly (~15s to process one image).
I don't have much experience with building real-world applications using GPUs, and am not sure whether I should go with a cloud instance or buy a lower-end GPU (in the $200-$500 range). I anticipate a very small amount of traffic to my application, so even the smaller instances will be quite pricey for what I'm trying to accomplish.
Question: What is the best way to for me to determine if a GPU would be fast enough without actually going out and buying it first? All of the cloud GPUs (Amazon, Google) use hardware that is way out of my budget, so running my code on these instances wouldn't give me a good comparison.

A: With the rapid rise of cloud computing and services, I don't see many benefits of buying your own GPU and setting up their own servers other than restrictions of sending data to Cloud. Not only is it time consuming, but perhaps doesn't scale well. Checkout services like AWS Sagemaker (They offer free trials) where you can certainly upload your faster RCNN code and you could then hit the service through an endpoint.
Services like sagemaker are relatively cheap ($4/hour for a very fast Tesla V100 gpu) if you want to run some experimentation or relatively have a small load.
The best way for you to determine which GPU is best suitable for you is to boot up an EC2 Instance with the GPU of your choice, upload the Faster RCNN repository along with some test environment which calculates time to process the images. EC2 instance have a variety of GPUs that you can test out your code with. From there, you should be able to see which GPU is good enough for your use-case.
But if you are looking for 300-500 dollar gpu, then you would probably have to switch to a lighter model like SSD or YOLO since Faster RCNN is a relatively big model. In my previous projects where I had to also use Faster RCNN, I find that even with a Tesla K80 (costs $5000) is still not fast enough for my use-case. So I ended up upgrading to a a Tesla V100 gpu(costs ~ $10 000) which finally is enough for me.
All this is done in EC2 of course.


text:
Q: VBA to Combine Header with Subheaders in EXCEL? Sub insertHeader()

    Dim rng1 As Range
    Dim ws As Worksheet
    Dim c1 As Range
    Dim rng2 As Range

    Set ws = Worksheets("Sheet1")
    Set rng1 = ws.Range("A2:AV2")

    For Each c1 In rng1
        If c1.Value <> "" Then
            c1.Value = c1.Offset(-1) & "_" & c1.Value
        End If
    Next

End Sub

I am trying to combine the Header with Subheaders
See below pix-
Thanks in advance!!

A: Sub insertHeader()

Dim rng1 As Range
Dim ws As Worksheet
Dim c1 As Range

Set ws = Worksheets("Sheet1")
Set rng1 = ws.Range("A1:AV1")

For Each c1 In rng1
    If c1.Value <> "" Then
        c1.Offset(1, 0) = c1.Value & "_" & c1.Offset(1, 0)
        c1.Offset(1, 1) = c1.Value & "_" & c1.Offset(1, 1)
        c1.Offset(1, 2) = c1.Value & "_" & c1.Offset(1, 2)
        c1.Offset(1, 3) = c1.Value & "_" & c1.Offset(1, 3)
        c1.Offset(1, 4) = c1.Value & "_" & c1.Offset(1, 4)

    End If
Next

End Sub

A: Sub insertHeader()

    Dim rng1 As Range
    Dim ws As Worksheet
    Dim c1 As Range
    Dim rng2 As Range
    Dim currHeader

    Set ws = Worksheets("Sheet1")
    Set rng1 = ws.Range("A2:AV2")
    currHeader = ""

    For Each c1 In rng1
        If Len(c1.Offset(-1).Value)>0 Then
            currHeader = c1.Offset(-1).Value
        End If
        If c1.Value <> "" & currHeader <> "" Then
            c1.Value = currHeader  & "_" & c1.Value
        End If
    Next

End Sub


text:
Q: How do I used *ngIf to toggle child components of components featured in more than one location? I have components that need to be flexible for other areas of my site and so far am thinking using

*ngIf

to toggle the necessary child component linking to the route would be the easiest way to go about achieving it.
To be more precise, I have two sections, one I call the "Rebranding" section and the other the "Brand a New Business" section.  I have 1 point I want to make to them both in two different ways.  Which I'm encompassing in a "Fresh Start" component.
A "fresh start" for someone who's been in Business for 6 years is different from a "fresh start" for someone who's starting a new Business, therefor there's different key points I want to touch on.
The reason I want to keep them housed in one component is because in the long run I can see it being easier to manage each "point" I want to make for each crowd I want to communicate it to.  I figured that would be cleaner and easier than having that many components all scattered around and wired into the routing.
So far this is what I've been able to muster up for the area of my site I'm on now.
import { Component }                from '@angular/core';
import { Router }                   from '@angular/router';

@Component({
    selector: 'asset-packs',
    template: `
Asset Packs

               <asset-expand *ngIf="router.urlTree.contains(router.createUrlTree(['/expand']))"></asset-expand>
              `,
    directives:[
        Router
    ]
})

export class PointAssetsComponent {

    constructor(private router: Router){};
}

I have it all routed up in the module and didn't get any errors prior to trying this method.  I came across it on another answer on here that really didn't give much clarity in terms of what components I needed to import.  With that being said I already know this is incomplete, wasn't sure of where to add the constructor, I tried it both on top and bottom, not sure if I'm even using the router correctly.  without the *ngIf everything shows up perfectly fine.  I figured I'd start out with one nested component to make sure it shows up where I want it to and stays off on the other pages that use this component.  This in particular is for the "assets" component, which will be featured in 3 sections, but 2 of them will be the same, which means I'm also going to need to use an "or" statement or throw a "!" in there.

A: I'd use the "ActivatedRoute" for toggling components depending on route.
import { ActivatedRoute } from "@angular/router";
//
constructor(
    public activatedRoute: ActivatedRoute
)
{
    this.activatedRoute.url.subscribe(
                (data: any) => {
                    this.mycurrentUrl = "";
                    for (let i of data) {
                        this.mycurrentUrl = i.path;
                    }
                },
                error => console.debug("URL ERROR", error),
                () => console.log('Current URL:' + this.mycurrentUrl));
}
// Check current route
isExpandRoute() {
    if (this.mycurrentUrl == 'expand' )
        return true;
    } else {
        return false;
    }
}

A: Binding to the router this ways seems quite inefficient. Angular change detection will cause contains(...) to be called on every change detection turn.
I'd suggest using
@Component({
    selector: 'asset-packs',
    template: `
Asset Packs

               <asset-expand *ngIf="isExpandRoute"></asset-expand>
              `,
    directives:[
        Router
    ]
})
export class PointAssetsComponent {

    constructor(private router: Router){
      router.events
      .filter(event => event instanceof NavigationEnd)
      .subscribe((event:Event) => {
        this.isExpandRoute = router.urlTree.contains(router.createUrlTree(['/expand']));
      });
    }
}

I don't know if this fixes your actual problem though.
See also How to detect a route change in Angular 2?


text:
Q: Proof of the Ballot Theorem Random Walks
Ballot Theorem: For $b>0$ the number of paths (0,0) to (n,b) that do not revisit the x axis is $\frac{b}{n}\mathbb{P}_{0}(S_n=b)$.

MY ATTEMPT
Now the first step of this path is to the point (1,1) so we want to find $$\mathbb{P}_{1}(S_{n-1}=b)- \mathbb{P}^{0}_{1}(S_{n-1}=b)$$ DEFINE $\mathbb{P}^{0}_{1}$ AS PROBABILITY STARTING AT 1 TO HIT b IN N-1 MOVES  AND HITTING ZERO ON THE WAY
This by the reflective property is equivalent to $$\mathbb{P}_{1}(S_{n-1}=b)- \mathbb{P}_{-1}(S_{n-1}=b)$$ Now by using the formula $$\mathbb{P}_{a}(S_{n}=b)=\binom{n}{\frac{n+b-a}{2}}p^{\frac{n+b-a}{2}}q^{\frac{n-b+a}{2}}$$ But when I plug the numbers into the functions I am having a hard time rearragning it to give me the desired $\frac{b}{n}\mathbb{P}_{0}(S_n=b)$.
Is this proof reliant on all that algebra or is there a simply way of deriving the result?


text:
Q: heroku-like workflow on personal server I'm trying to set up a server with pure-git workflow similar to heroku. I don't need help setting up git, but for informative purposes, I'm using gitolite. I'd like to (somehow) write custom hooks in the operating system (Ubuntu) of this system so that, when it receives a push on a particular branch, it performs all the operators heroku does (starting Rack, Mongrel, Apache (for static serving pages in my case), etc.
Can someone point me towards a resource to do this or at least get started? A google search didn't really seem to help...

A: I just uncovered https://github.com/mislav/git-deploy, which is EXACTLY what I wanted. I'm going to leave the other answer as "correct" (since it was the best at the time), but I'm using git-deploy now :)

A: It sounds like you want to execute arbitrary functionality at a certain point in your Git workflow. Git hooks are the way to go.
If you look in any Git repo (inside the .git folder), you'll see a hooks folder. Inside it there are a number of example hook files with different names. Based on your explanation above, you want to edit the post-receive hook file, since that will be called immediately after a new ref has been updated in your remote repo (resulting from a push from a local one). For more info, read the official documentation on hooks or read this perhaps more approachable explanation.
You can put any shell commands you want in a hook file. Change the filename from post-receive.sample to simply post-receive, add the commands you need to start Rack, Mongrel, Apache, etc., then make the file executable with a quick chmod +x post-receive and you're all set.

A: I have a similar setup where the master branch is automatically deployed as staging using capistrano on git push. Production is manually deployed from the production branch.
The setup require that you use set :deploy_via, :remote_cache in deploy.rb to have a local cache copy on the server. This is to be able to run capistrano with the latest configuration if is has been changed since last deploy.
post-receive hook script:
#!/bin/bash
while read oldrev newrev ref
do
        if [ "$ref" = "refs/heads/master" ] ; then
                echo "Master branch pushed, deploying to staging"
                # seams to be set to "." for hooks, unset to make things more normal
                unset GIT_DIR
                # deploy path, where "current", "releases", "shared" etc are
                DEPLOYDIR="/home/user/deploy/staging"
                # default path for :deploy_via :remote_cache is shared/cached-copy
                cd "$DEPLOYDIR/shared/cached-copy"
                # update cache to pushed revision, will be done by capistrano too
                git fetch origin && git fetch --tags origin && git reset --hard "$newrev"
                # load rvm
                source ~/.rvm/scripts/rvm
                rvm use 1.9.2
                # make sure correct gems are installed
                # this will also create a .bundle directory
                bundle install --gemfile Gemfile --path "$DEPLOYDIR/shared/bundle" --deployment --without development test
                # run capistrano
                # if you use deploy:migrations instead of deploy you should probably add
                # after "deploy:migrations", "deploy:cleanup"
                # to your deploy.rb
                bundle exec cap staging deploy:migrations
        fi
done

A simpler setup without :remote_cache is also possible but it will run capistrano with the previous (currently deployed) configuration and seams to be a bit more fragile.
post-receive hook script:
#!/bin/bash
while read oldrev newrev ref
do
        if [ "$ref" = "refs/heads/master" ] ; then
                echo "Master branch pushed, deploying to staging"
                # seams to be set to "." for hooks, unset to make things more normal
                unset GIT_DIR
                source ~/.rvm/scripts/rvm
                rvm use 1.9.2
                cd /home/user/deploy/staging/current && bundle exec cap staging deploy:migrations
        fi
done

A: I recommend checking out GitHub:progrium/dokku, it's based on Docker technology and really easy to setup and use.
If you're also looking for cloud provider, I recommend DigitalOcean since they support Dokku out of the box! Checkout their community documentation for more information.
Your workflow will be very much similar to Heroku: (Full Tutorial)

*

*Setup Dokku Server (Your personal Heroku) and your public key

*Configure your domain to point *.DOMAIN.com to Dokku Server

*Add Git Remote to your repo: git remote add myheroku dokku@DOMAIN.com:your-app

*Push code to Dokku server: git push myheroku master

*Checkout http://your-app.DOMAIN.com
Also if you want to have different sub-domain or full-domain assign to your app, you can install Dokku Domain Plugin and simply do specify domain to your-app: dokku domains:set your-app NEWDOMAIN.com
It's worth mentioning new project called Flynn GitHub: flynn/flynn which comes with more features than Dokku. Read history behind Flynn and Dokku here...

A: Have you looked at Capistrano?  From wiki:

Capistrano is a utility and framework
  for executing commands in parallel on
  multiple remote machines, via SSH. It
  uses a simple Domain Specific Language
  borrowed in part from the tool rake.
  Rake is similar to make in the C world
  and allows you to define tasks, which
  may be applied to machines in certain
  roles. It also supports tunneling
  connections via some gateway machine
  to allow operations to be performed
  behind VPNs and firewalls.
Capistrano
  was originally designed to simplify
  and automate deployment of web
  applications to distributed
  environments, and originally came
  bundled with a set of tasks designed
  for deploying Rails applications. The
  deployment tasks are now (as of
  Capistrano 2.0) opt-in and require
  clients to explicitly put "load
  'deploy'" in their recipes.

It's not based on any sort of commit or post hooks, although I'm sure if you really needed that, then you would be able to find some example recipes to do something like that.
Update: Maybe git-deploy (based on Capistrano) is what you want:

A tool to install useful git hooks on your remote repository to enable push-based, Heroku-like deployment on your host.


text:
Q: Upload a folder to an S3 bucket using java aws sdk I'm trying to upload an entire folder to AWS S3 bucket. I'm successful at uploading individual files, but couldn't find a way to upload the entire folder.
AWS CLI has an option called sync, does and equivalent methods available in Java SDK?
Sample code for uploading individual objects is as below (only part)
final PutObjectRequest dashboardUploadRequest = PutObjectRequest.builder()
                        .bucket(aws.getApplihealthReportBucket())
                        .key(projectName + "/"+ executionConfig.getTestType() +"/" + aws.getS3Folder() + "/index.html").build();

S3Client s3 = S3Client.builder().credentialsProvider(credentialsProvider).build()
s3.putObject(dashboardUploadRequest, Paths.get(resultsDirectory + "/extent.html"));

A: There are no way to upload folder directly to s3. Only forearch and upload file by file.
Or using CLI
https://docs.aws.amazon.com/cli/latest/reference/s3/sync.html

A: The TransferManager API in Java SDK provides methods to upload a directory to S3.


text:
Q: How can I make html file dynamic with angularjs I have an html file and a JS file. The JS file contains some data that I want to present in the html file depending on a clicked link from another html file
html file:

                    {{product.name}}

                    {{product.price}}

                    {{product.description}}

js file
    var app = angular.module('app', [']);

    app.controller('prodCtrl', function ($scope) {
       $scope.courses = [
           {
            id: 1,
            name: 'prod 1',
            description: 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquid ea fugit
tempore error, tenetur adipisci hic voluptas sapiente distinctio,.',
            price: 100,
            image: 'public/photos/prod1.png'
        },
        {
            id: 2,
            name: 'prod 2',
            description: 'Lorem ipsum dolor sit amet consectetur adipisicing elit.',
            price: 30,
            image: 'public/photos/prod2.png'
        },
      ];
    });

in another html page I have the products listed as links and I want to present them in the html page up there depending on the link I clicked

A: You would pass the param in the route with ui-router
It sounds like you're asking for dynamic routing. There are a few questions about this on SO, but to point you in the right direction for what you're doing:
You have to declare your routes in the app config like so:
angular.module('myApp', [
  'ui.router'
])
.config(function($stateProvider) {
  $stateProvider
    .state({
      name: 'product',
      url: '/product/{id}', //{id} or :id will tell it to expect the param
      templateUrl: '/products/index.html',
      controller: 'ProdCtrl'
    });
});

Inside your index.html file, make sure you add:

  <ui-view></ui-view>

(or where you want the content to appear)
And finally, your controller:
.controller('ProdCtrl', function($scope, $stateParams) {
  //get id from the url and convert it to an int to match data type in courses id
  //may want to consider doing some validation
  $scope.productId = parseInt($stateParams.id);

  var courses = [
    {
      id: 1,
      name: 'prod 1',
      description: 'Lorem ipsum dolor sit amet consectetur adipisicing elit.',
      price: 100,
      image: 'public/photos/prod1.png'
    },
    {
      id: 2,
      name: 'prod 2',
      description: 'Lorem ipsum dolor sit amet consectetur adipisicing elit.',
      price: 30,
      image: 'public/photos/prod2.png'
    }
  ];

  //find the matching item by id and set it to scope
  $scope.product = courses.map(function(item) {
    if (item.id === $scope.productId) {
      return item;
    }
  });
});

You should now be able to go to /product/1 and see prod 1
Please note this is untested code, but should get you on the right track. I also renamed a couple things for clarity and be more aligned with common practices (e.g. myApp and ProdCtrl).
If you go through the ui-router documentation, you can also achieve this without using the id in the url and have it pass params in the background. This would mean you can only access that page via links in your app and not deep link them.


text:
Q: Nested table in table in table in table in div display block not inheriting height Why is wrapper #4 not inheriting the height of its parent table container?
The tables are nested in a display block wrapper, and each nested div is display table, and each table inherits until the innermost one. What is causing this and how can I workaround it?
The jsfiddle: http://jsfiddle.net/ubjZT/14/ (edit there was a typo in the old jsfiddle)
html markup:

css:
.wrapper
{
    display: block;
    background: black;
    height:100%;
    width: 100%;
}
body
{
    height: 500px;
}

.lastunit
{
   height: 100%;
    width: 100%;
   background: yellow;
   display: table;
}

.wrapper2
{
  position: relative;
  padding-top: 58.95117540687161%;
  padding-bottom: 0;
  padding-left: 0;
  padding-right: 0;
  width: 100%;
  height: 100%;
  display: table;
  background: red;
}

.wrapper3
{
 position: absolute;
 left: 0;
 right: 0;
 top: 0;
 bottom: 0;
 display: table;
 background: green;
 height: 100%;
 width: 100%;
}

.wrapper4
{
  width: 39.24050632911392%;
  margin-left: 5.4249547920434%;
  margin-right: 5.4249547920434%;
  margin-top: 6.69077757685353%;
  height: 88.650306748466%;
  display: table;
  background: purple;
}

UPDATED ANSWER FIDDLE: http://jsfiddle.net/ubjZT/20/

A: No need to set the wrappers to display: table here. Just set them to display: block (you could, in fact, not set the display property at all because div defaults to display: block)


text:
Q: Deriving from a base class whose instances reside in a fixed format (database, MMF)...how to be safe? (Note: I'm looking for really any suggestions on the right search terms to read up on this category of issue.  "Object-relational-mapping" occurred to me as a place where I could find some good prior art...but I haven't seen anything quite fitting this scenario just yet.)
I have a very generic class Node, which for the moment you can think of as being a bit like an element in a DOM tree.  This is not precisely what's going on--they're graph database objects in a memory mapped file.  But the analogy is fairly close for all practical purposes, so I'll stick to DOM terms for simplicity.
The "tag" embedded in the node implies a certain set of operations you should (ideally) be able to do with it.  Right now I'm using derived classes to do this.  So for instance, if you were trying to represent something like an HTML list:

Coffee

Tea

Milk

The underlying tree would be seven nodes:
+--UL                       // Node #1
   +--LI                    // Node #2
      +--String(Coffee)     // Node #3 (literal text)
   +--LI                    // Node #4
      +--String(Tea)        // Node #5 (literal text)
   +--LI                    // Node #6
      +--String(Milk)       // Node #7 (literal text)

Since getString() is already a primitive method on Nodes themselves, I'd probably only make class UnorderedListNode : public Node, class ListItemNode : public Node.
Continuing this hypothetical, let's imagine I wanted to help the programmer use less general functions when they know more about the Node "type"/tag they have in their hands.  Perhaps I want to assist them with structural idioms on the tree, like adding a string item to an unordered list, or extracting things as a string.  (This is just an analogy so don't take the routines too seriously.)
class UnorderedListNode : public Node {
private:
    // Any data members someone put here would be a mistake!

public:
    static boost::optional<UnorderedListNode&> maybeCastFromNode(Node& node) {
        if (node.tagString() == "ul") {
            return reinterpret_cast<UnorderedListNode&>(node);
        }
        return boost::none;
    }

    // a const helper method
    vector<string> getListAsStrings() const {
        vector<string> result;
        for (Node const* childNode : children()) {
            result.push_back(childNode->children()[0]->getText());
        }
        return result;
    }

    // helper method requiring mutable object
    void addStringToList(std::string listItemString) {
        unique_ptr<Node> liNode (new Node (Tag ("LI"));
        unique_ptr<Node> textNode (new Node (listItemString));
        liNode->addChild(std::move(textNode));
        addChild(std::move(liNode));
    }
};

Adding data members to these new derived classes is a bad idea.  The only way to really persist any information is to use the foundational routines of Node (for instance, the addChild call above, or getText) to interact with the tree.  Thus the real inheritance model--to the extent one exists--is outside of the C++ type system.  What makes a
 node "maybeCast" into an UnorderedListNode has nothing to do with vtables/etc.
C++ inheritance looks right sometimes, but feels wrong usually.  I feel like instead of inheritance I should have classes that exist independently of Node, and just collaborate with it somehow as "accessor helpers"...but I don't have a good grasp of what that would be like.

A: I am not sure I have understood completely what you intend to do but here are some suggestions you might find useful.
You are definitely on the right track with inheritance. All the UL nodes, LI nodes, ... etc. are Node-s. Perfect "is_a" relationship, you should derive these classes from the Node class.

let's imagine I wanted to help the programmer use less general functions when they know more about the Node "type"/tag they have in their hands

...and this is what virtual functions are for.
Now for the maybeCastFromNode method. That's downcasting. Why would you do that? Maybe for deserializing? If yes, then I'd recommend using dynamic_cast<UnorderedListNode *> . Although most likely you won't need RTTI at all if the inheritance tree and the virtual methods are well-designed.

C++ inheritance looks right sometimes, but feels wrong usually.

This might not always be C++'s fault :-)

A:
"C++ inheritance looks right sometimes, but feels wrong usually."

Indeed, and this statement is worrisome:

What makes a  node "maybeCast" into an UnorderedListNode has nothing to do with vtables/etc.

As is this code:
static boost::optional<UnorderedListNode&> maybeCastFromNode(Node& node) {
    if (tagString() == "ul") {
        return reinterpret_cast<UnorderedListNode&>(node);
    }
    return boost::none;
}

(1) type-punning
If the Node& being passed in was allocated through a mechanism that did not legally and properly construct an UnorderedListNode on the inheritance path, this is what is called type punning.  It's almost always a bad idea.  Even if the memory layout on most compilers appears to work when there are no virtual functions and derived classes add no data members, they are free to break it in most all circumstances.
(2) strict-alias
Next there is the compiler's assumption that pointers to objects of fundamentally different types do not "alias" each other.  This is the strict aliasing requirement.  Although it can be disabled via non-standard extensions, that should only be applied in legacy situations...it hinders optimization.
It's not completely clear--from an academic standpoint--whether these two hindrances have workarounds permitted by the spec under special circumstances.  Here's a question which investigates that, and is still an open discussion at time of writing:
Make interchangeable class types via pointer casting only, without having to allocate any new objects?
But to quote @MatthieuM.: "The closer you get to the edges of the specifications, the more likely you are to hit a compiler bug. So, as engineer, I advise to be pragmatic and avoid playing mind games with your compiler; whether you are right or wrong is irrelevant: when you get a crash in production code, you lose, not the compiler writers."
This is probably more the right track:

I feel like instead of inheritance I should have classes that exist independently of Node, and just collaborate with it somehow as "accessor helpers"...but I don't have a good grasp of what that would be like.

Using Design Pattern terms, this matches something like a Proxy.  You would have a lightweight object that stores the pointer and is then passed around by value.  In practice, it can be tricky to handle issues like what to do about the const-ness of the incoming pointers being wrapped!
Here's a sample of how it might be done relatively simply for this case.  First, a definition for the Accessor base class:
template<class AccessorType> class Wrapper;

class Accessor {
private:
    mutable Node * nodePtrDoNotUseDirectly;
template<class AccessorType> friend class Wrapper;
    void setNodePtr(Node * newNodePtr) {
        nodePtrDoNotUseDirectly = newNodePtr;
    }
    void setNodePtr(Node const * newNodePtr) const {
        nodePtrDoNotUseDirectly = const_cast<Node *>(newNodePtr);
    }
    Node & getNode() { return *nodePtrDoNotUseDirectly; }
    Node const & getNode() const { return *nodePtrDoNotUseDirectly; }

protected:
    Accessor() {}

public:
    // These functions should match Node's public interface
    // Library maintainer must maintain these, but oh well
    inline void addChild(unique_ptr<Node>&& child)) {
        getNode().addChild(std::move(child));
    }
    inline string getText() const { return getNode().getText(); }
    // ...
};

Then, a partial template specialization for handling the case of wrapping a "const Accessor", which is how to signal that it will be receiving a const Node &:
template<class AccessorType>
class Wrapper<AccessorType const> {
protected:
    AccessorType accessorDoNotUseDirectly;
private:
    inline AccessorType const & getAccessor() const {
        return accessorDoNotUseDirectly;
    }

public:
    Wrapper () = delete;
    Wrapper (Node const & node) { getAccessor().setNodePtr(&node); }
    AccessorType const * operator-> const () { return &getAccessor(); }
    virtual ~Wrapper () { }
};

The Wrapper for the "mutable Accessor" case inherits from its own partial template specialization.  This way the inheritance provides for the proper coercions and assignments...prohibiting the assignment of a const to a non-const, but working the other way around:
template<class AccessorType>
class Wrapper : public Wrapper<AccessorType const> {
private:
    inline AccessorType & getAccessor() {
        return Wrapper<AccessorType const>::accessorDoNotUseDirectly;
    }

public:
    Wrapper () = delete;
    Wrapper (Node & node) : Wrapper<AccessorType const> (node) { }
    AccessorType * operator-> () { return &Wrapper::getAccessor(); }
    virtual ~Wrapper() { }
};

A compiling implementation with test code and with comments documenting the weird parts is in a Gist here.

Sources: @MatthieuM., @PaulGroke


text:
Q: How to add media play/pause button into push notification bar? I successfully created an apple push notification. I am receiving audio URL via push notification. I want to add media play/pause button into notification bar (custom notification bar), which functionality is that upon getting audio notification the user is able to play/pause receiving audio without opening an app.
Is it possible in iOS? I've searched through many web documents, but found nothing. So, can anyone help me out with this concept?


text:
Q: Interactive Display of reflectivity data for PPI in matplotlib As a part of our project, we need to display radar reflectivity data in Plan Position Indicator(PPI) image along with latitude and longitude.  I am using plot_ppi_map function to Plot a PPI volume sweep on geographic map.  A sample output of my program is given below
Sample output of the Program
I am able to get latitude and longitude values in the bottom left corner of status bar, but not able to display values of radar reflectivites. Generated radar reflectivity values from following code
display = pyart.graph.RadarMapDisplay(radar)

rfdata = display._get_data(field = 'reflectivity', sweep = 0,mask_tuple = None,filter_transitions = True,gatefilter=None)

Tried using Example mentioned and tried working with ax.format_coord() with reflectivity data derived from display._get_data and got reflectivity data of size (361,1000). But getting Index error as mentioned below(screenshot also enclosed)
IndexError: index 176327 is out of bounds for axis 0 with size 361
Error message
I am using the following code snippet to plot reflectivity data on a map.
Projection that I am using in this is AzimuthalEquidistant
    class Formatter(object):
        def __init__(self, im):
            self.im = im
        def __call__(self, x, y):
            z = self.im.get_array()[int(y), int(x)]
            return 'x={:.01f}, y={:.01f}, z={:.01f}'.format(x, y, z)

    projection = ccrs.AzimuthalEquidistant(central_latitude=radar.latitude['data'][0],central_longitude=radar.longitude['data'][0])

    display.plot_ppi_map('reflectivity', 0, vmin=-31.5, vmax=95.5,
                             min_lon=min_longitude, max_lon=max_longitude, min_lat=min_latitude, max_lat=max_latitude,
                             lon_lines=np.arange(77, 85, 1), resolution='110m',shapefile = shapefile_path,ax=ax,
                             shapefile_kwargs = {'linewidth':1, 'edgecolor':'black', 'facecolor':"#00000000"},
                             cmap = dwrmpt,norm=norm, embelish = False,
                             lat_lines=np.arange(12, 20, 1), projection=projection,
                             fig=fig, lat_0=radar.latitude['data'][0],
                             lon_0=radar.longitude['data'][0])
im = ax.imshow(rfdata, interpolation='none')
ax.format_coord = Formatter(im)
plt.show()

I am expected to display reflectivity data whenever data is available.
I need to display reflectivity values along with latitude and longitude. Please advise.


text:
Q: Conditions to paginate for belongsToMany CakePHP 3 I have the tables Semesters, Disciplines and a jointTable Semesters_Disciplines. I want to create a action index in DisciplinesController with a semester_id as parameter, which list with paginate just the disciplines what belongs to the semester with the id passed in the parameter. I tried this:
public function index($semester_id)
{
    $options = ['semester_id' => $semester_id];
    $this->paginate = ['conditions' => $options];

    $this->set('disciplines', $this->paginate($this->Disciplines));
    $this->set('_serialize', ['disciplines']);
}

A: You'll have to use a query that uses matching or joins to be able to filter on non 1:1/n-1 associations.
You can do so by either passing a query directly to the paginate() method
// ...
$this->set('disciplines', $this->paginate(
    $this->Disciplines
        ->find()
        ->matching('Semesters', function(\Cake\ORM\Query $q) use ($semester_id) {
            return $q->where([
                'Semesters.id' => $semester_id
            ]);
        })
        ->group(['Disciplines.id'])
));
// ...

or by using a custom finder.
// ...
$this->paginate = [
    'finder' => [
        'semesters' => [
            'semester_id' => $semester_id
        ]
    ]
];
$this->set('disciplines', $this->paginate($this->Disciplines));
// ...

// DisciplinesTable
public function findSemesters(\Cake\ORM\Query $query, array $options)
{
    $query
        ->matching('Semesters', function(\Cake\ORM\Query $q) use ($options) {
            return $q->where([
                'Semesters.id' => $options['semester_id']
            ]);
        })
        ->group(['Disciplines.id']);
    return $query;
}

See also

*

*Cookbook > Pagination > Using Controller::paginate()

*Cookbook > Retrieving Data and Result Sets > Custom Finder Methods

*Cookbook > QueryBuilder > Filtering by Associated Data

*Cookbook > QueryBuilder > Adding Joins


text:
Q: Right Column bottom on all mobile devices I'm just starting on bootstrap and trying to understand how the grid works exactly
HTML:

 A

 B

CSS:
.leftcontainer{
  float:left;
}

.rightcontainer{
  float:right;
}

I don't want scroll bar at the bottom on the mobile devices. My output is of this format on mobile
A

                    B

Instead I want
A

B

but A   B on desktop
Any help is much appreciated. Thanks!

A:

 A

 B

and remove your CSS. You don't need to add the floats to any of this.
Also, please read up on the grid system in the Bootstrap documentation. It has whatever you need. http://getbootstrap.com/css/#grid