text:
Q: Python - Selenium get Element by attribute and the full attribute value Hi how can I get an element by attribute and the attribute value in Python Selenium?
For example I have class="class1 class2 class3".
Now I want to get the element with the attribute class what ca.rries the classes "class1 class2 class3".
Is this possible?
If I use xpath, I always need to add the element type, input, option,...
I try to avoid the element type since it varies sometimes.

A: While constructing locators considering css-selectors or xpath you have to use the different attributes and the attribute-values to identify the WebElement uniquely within the DOM Tree.
The generic way is:

*

*Using css_selector:
button.classname[attributeA='attributeA_value'][attributeB='attributeB_value']

*Using xpath and attributes:
//button[@attributeA='attributeA_value'][@attributeB='attributeB_value']

As an example, for an element like:
<button type="button" aria-hidden="true" class="close alert alert-close" data-notify="dismiss">Close</button>

You can identify the Close element using either of it's the attributes and the corresponding attribute-values using either of the Locator Strategies:

*

*Using css_selector:
button.close.alert.alert-close[data-notify='dismiss']
classes-> ^   ^^    ^^^        data-notify ^^^^ attribute

*Using xpath and attributes:
//button[@class='close alert alert-close' and @data-notify='dismiss']
 class attributes  ^    ^^     ^^^             data-notify ^^^^ attribute

*Using xpath and innerText:
//button[text()='Close']
       innerText ^

A: The CSS selectors would be formatted like this:
'[attribute]'
'[attribute="value"]'
For example, the selector for the input field on google.com would be:
'input[name="q"]'

A: to answer this part

If I use xpath, I always need to add the element type, input,
option,... I try to avoid the element type since it varies sometimes.

you can use //* and then attribute type and attribute value.
//*[@class='class1 class2 class3']

//* represent any or all nodes


text:
Q: performance on Android 4.x I am facing some performance issue (UI loading is slow) on android 4.x versions but my application is working perfectly well on android 2.x device.
Even a layout of few buttons and edit text are loading very slow
Is there any specific settings or twiking we have to made to make it work.
Please share your experience as I am struggling it with very badly.

A: you could include android:hardwareAccelerated="true" inside the  in your manifest.
But it sounds to me you have bigger problems deeper in the actual code.

A: I have already used it but no difference
there is nothing much in the .java as well as in layout file.
It is just a login page and connection to server happedn only with user clicks on login button.
this is the only code i have in my layout file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:background="@drawable/bg" >

    <!-- stitches for top, bottom, right, left -->

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:adjustViewBounds="true"
        android:scaleType="matrix"
        android:src="@drawable/stitch_top_full" />

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:adjustViewBounds="true"
        android:scaleType="matrix"
        android:src="@drawable/stitch_bottom_full" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:adjustViewBounds="true"
        android:scaleType="matrix"
        android:src="@drawable/stitch_left_full" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentRight="true"
        android:layout_marginRight="5dp"
        android:adjustViewBounds="true"
        android:scaleType="matrix"
        android:src="@drawable/stitch_right_full" />

    <RelativeLayout
        android:id="@+id/login_body"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/login_img_radial_bg" >

        <ImageView
            android:id="@+id/login_logo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="70dp"
            android:src="@drawable/login_img_logo" />

        <EditText
            android:id="@+id/login_membership_number"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/login_logo"
            android:layout_marginLeft="30dp"
            android:layout_marginRight="30dp"
            android:layout_marginTop="30dp"
            android:background="@drawable/textbox_layout_border"
            android:ellipsize="end"
            android:hint="@string/hint_cp_membership_number"
            android:maxLength="15"
            android:maxLines="1"
            android:paddingLeft="10dp"
            android:singleLine="true" />
        <!-- android:background="@drawable/login_textbox_bg" -->

        <EditText
            android:id="@+id/login_membership_password"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/login_membership_number"
            android:layout_marginLeft="30dp"
            android:layout_marginRight="30dp"
            android:layout_marginTop="15dp"
            android:background="@drawable/textbox_layout_border"
            android:hint="@string/hint_cp_membership_password"
            android:inputType="textPassword"
            android:maxLength="15"
            android:paddingLeft="10dp"
            android:singleLine="true" />

        <LinearLayout
            android:id="@+id/login_row"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/login_membership_password"
            android:weightSum="1" >

            <LinearLayout
                android:id="@+id/login_stayloggedin_bg"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="30dp"
                android:layout_marginRight="5dp"
                android:layout_marginTop="10dp"
                android:layout_weight="0.60"
                android:background="@drawable/login_img_remeber_bg"
                android:orientation="horizontal" >

                <!-- android:background="@drawable/login_stay_loggedin_bg" -->

                <ToggleButton
                    android:id="@+id/login_stay_login_btn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:layout_marginLeft="5dp"
                    android:background="@drawable/login_stay_loggin_btn_drawable"
                    android:button="@null"
                    android:textOff=""
                    android:textOn="" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="fill_parent"
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:layout_marginLeft="5dp"
                    android:ellipsize="end"
                    android:gravity="center_vertical|center_horizontal"
                    android:maxLines="2"
                    android:paddingRight="5dp"
                    android:text="@string/stay_login_label"
                    android:textColor="@color/white" />
            </LinearLayout>

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginRight="30dp"
                android:layout_marginTop="10dp"
                android:layout_weight="0.40"
                android:background="@drawable/login_img_button_bg" >

                <Button
                    android:id="@+id/login_bttn"
                    style="@style/textView_style"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:background="@drawable/login_button"
                    android:text="@string/btn_title_login" />

            </RelativeLayout>
        </LinearLayout>
        <!-- </RelativeLayout> -->

        <TextView
            android:id="@+id/login_copyright"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/login_row"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="10dp"
            android:singleLine="true"
            android:textColor="@color/white"
            android:typeface="normal" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/login_slider_open"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@drawable/login_img_slider_open"
        android:visibility="visible" >

        <TextView
            style="@style/textView_style"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:paddingRight="15dp"
            android:text="@string/not_a_member_label" />

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="60dp"
            android:background="@drawable/common_img_largebuttonbg1" >

            <Button
                android:id="@+id/login_signup_bttn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:background="@drawable/login_img_btn_signup"
                android:text="@string/btn_title_sign_up"
                android:textColor="@android:color/black"
                android:textStyle="bold" />
        </RelativeLayout>

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/login_slider_close"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@drawable/login_img_slider_closed" >

        <TextView
            style="@style/textView_style"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:paddingRight="15dp"
            android:text="@string/not_a_member_label" />
    </RelativeLayout>

</RelativeLayout>

A: I have managed to solve the problem, our issue is resolved now.
I would like to share my experience so that it might help others too.
What we were doing:
we were using text shadow for text in the textview and this was creating issue in android 4.x device, but working perfectly in android 2.x devices.
what we did:
we just remove the shadow elements from the textview and now it is working perfectly fine.
so this is our findings on android 4.x version.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding a static route for gmail? I have my PC (windows7) on two networks - WiFi Hotspot and LAN at the same time.
I would like to add a route on my PC such that requests to gmail go to the Wifi Hotspot and everything else to LAN proxy (everything goes to LAN proxy now).
How do I achieve this?


text:
Q: Angular CLI, can't create a new project because of an invalid configuration file was found This error appear when I try to create a new angular project with the command ng new app-new
I have this error on the following picture :

So I tried to uninstall and install again angular, and research this file but it's not in the directory.
Do you know what can cause this error please ?

A: This is not an "error" with the Angular CLI, but a config file at a level it probably shouldn't be. /home/shirley/.angular.json is listed in the error, and the error suggests that you delete it. If you don't need that file for anything else you're working on, delete the file. If you do need the file, Angular CLI won't work at this level.
ls -a /home/shirley/ <-- file is in here
rm /home/shirley/.angular.json <-- remove it


text:
Q: cron ignoring environment variables? This should be simple, but it doesn't seem to be working.  I have a very simple script run by cron:
export MAILTO=foo@foo.com
MAILTO=foo@foo.com
echo "MAILTO is set to $MAILTO"

Cron, however, seems to not be picking up the MAILTO variable - the cron e-mails look, in part, like this:
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/home/deploy>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=deploy>
Date: Thu, 20 Sep 2012 13:05:01 -0700

MAILTO is set to foo@foo.com

What am I missing?  Why isn't cron picking up the environment variables set in the script?

A: A process in Unix can change its own environment variables and can define its children's environment variables when those children are created. A process cannot change its parent's environment variables, those of its children after those children are created, or those of any other process.
It appears as though you're trying to have a cron job change cron's environment variables, which is impossible.

A: I'm guessing you're not logged in as the same user the cron is running under. Hence, creating the discrepancy.

A: Set MAILTO environment variable in the crontab file. cron just ignore environment variables for security reason. If MAILTO is not specified, then the output will be mailed to the owner of the process that produced the output.


text:
Q: how to solve size mismatch for this model? data_transforms = {
'train': transforms.Compose([
    transforms.RandomResizedCrop(224),
    transforms.RandomHorizontalFlip(),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'val': transforms.Compose([
    transforms.Resize(224),
    transforms.CenterCrop(256),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),

batchsize=4
class Net(nn.Module):
def __init__(self):
    super(Net, self).__init__()
    self.conv1 = nn.Conv2d(3, 64, kernel_size=5, padding=1)
    self.pool = nn.MaxPool2d(2, 2)
    self.conv2 = nn.Conv2d(64, 128, kernel_size=5, padding=1)
    self.fc1 = nn.Linear(256*6*6, 4096)
    self.fc2 = nn.Linear(4096, 4096)
    self.fc3 = nn.Linear(4096, 2)

def forward(self, x):
    x = self.pool(F.relu(self.conv1(x)))
    x = self.pool(F.relu(self.conv2(x)))
    x = x.reshape(x.size(0), -1)
    print(x.shape)
    x = F.relu(self.fc1(x))
    x = F.relu(self.fc2(x))
    x = self.fc3(x)
    return x

RuntimeError: size mismatch, m1: [4 x 373248], m2: [9216 x 4096] at C:/w/1/s/tmp_conda_3.8_075429/conda/conda-bld/pytorch_1579852542185/work/aten/src\THC/generic/THCTensorMathBlas.cu:290

A: With the provided debug information we can only tell that there is a size mismatch in one of the layers.
Looking at the error, it seems the error is in the first linear layer. You should change its size to 373248 instead of 256*6*6.
This should also be clear from the output of the print statement print(x.shape).


text:
Q: Apache/php running on Windows require & include not working I have a problem getting include or require to work with apache running on windows. The index.php in the root folder works fine but the index.php file in the marketing folder can find the file.
config/config.php
inc/header.php
index.php
/marketing/index.php

I have
<?php require_once '/config/config.php'; ?>

In header.php & in /marketing/index.php i have
<?php require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/header.php'); ?>

I haven't had this problem before so i'm really scratching my head as to why this is.


text:
Q: Telerik mMVC master detail grid view for two unrelated models I need to display/present two different models in a master-detail grid.
One model(collection) is bound to master grid.It has a link in one of the column and is enabled/disabled based on condition. Simple.
What I need to do is upon clicking the link I should be able to populate the detail grid by calling another controller- action. I need the row information,to pass the row details/ model data to the controller-action to fetch the model for detail grid.How do I do this through Javascript/jQuery.
The detail model is not a collection.
Any other approach to achieve this?

A: http://demos.telerik.com/aspnet-mvc/razor/grid/detailsajax gives a great example on how to do this with AJAX.  I am assuming you are using the MVC Extensions by Telerik?


text:
Q: 2D integrals in SciPy I am trying to integrate a multivariable function in SciPy over a 2D area.
What would be the equivalent of the following Mathematica code?
In[1]:= F[x_, y_] := Cos[x] + Cos[y]

In[2]:= Integrate[F[x, y], {x, -\[Pi], \[Pi]}, {y, -\[Pi], \[Pi]}]

Out[2]= 0

Looking at the SciPy documentation I could only find support for one-dimensional quadrature. Is there a way to do multidimensional integrals in SciPy?

A: If you want to do symbolic integration, have a look at sympy (code.google.com/p/sympy):
import sympy as s
x, y = s.symbols('x, y')
expr = s.cos(x) + s.sin(y)
expr.integrate((x, -s.pi, s.pi), (y, -s.pi, s.pi))

A: I think it would work something like this:
def func(x,y):
    return cos(x) + cos(y)

def func2(y, a, b):
    return integrate.quad(func, a, b, args=(y,))[0]

print integrate.quad(func2, -pi/2, pi/2, args=(-pi/2, pi/2))[0]

Wolfram|Alpha agrees
edit:  I just discovered dblquad which seems to do exactly what you want:
print integrate.dblquad(func, -pi/2, pi/2, lambda x:-pi/2, lambda x:pi/2)[0]


text:
Q: Execute an Oracle stored procedure from a SQL Server stored procedure I have a SQL Server stored proc that needs to send information to an Oracle stored proc.
How do I set this up? Should it be a linked server? And how do I write the code to pass and execute the stored proc?

A: a procedure "TestingProcedure" in Oracle server.
a linked Server "LinkedServer" in SQL Server.
call TestingProcedure in SQL server example:
EXECUTE ('begin TestingProcedure; end;') AT LinkedServer;

A: You could also use:
DECLARE @outputParameter int
EXEC ('BEGIN <procedureName>(?,?); END;', @inputParameter , @outputParameter OUTPUT) at <linkedServerName>

This allows capturing output parameters

A: This is the syntax that I would probably try from the start:
SELECT * FROM OPENQUERY(<linked server name>, '{CALL <oracle sp>}')

What I've seen (I have not tried this myself) is that you can also use OPENQUERY to call an Oracle function which can then call the stored procedure, or you can turn the stored procedure into a function. Your connection from SQL Server would then look something like this:
SELECT * FROM OPENQUERY(<linked server name>, 'SELECT <oracle function> FROM dual')

A: Turns out I ended up having to use Microsofts CLR and write my own little C# application in order to handle the variables being pushed between the servers. Here's what I did:

*

*C# Application starts on a scheduled task in windows

*Application executes the SQL Server stored procedure and gets the return values

*Application then executes the Oracle stored procedure with appropriate values


text:
Q: Linking to a tab or panel of a shiny app How do I manage to link from a given shiny part to parts that are located on other tabs/panels?
Update
The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for).
However, I'd be interested to also know about more generic ways of linking parts of a shiny app.
Example
I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked.
The value #tab-4527-2 came from investigating the HTML output of ui, but I just saw that those values change each time I restart the app.
library(shiny)

# UI ---------------------------------------------------------------------

ui <- fluidPage(
  tabsetPanel(
    tabPanel(
      "A",
      p(),
      actionLink("link_to_tabpanel_b", "Link to panel B")
    ),
    tabPanel(
      "B",
      h3("Some information"),
      tags$li("Item 1"),
      tags$li("Item 2")
    )
  )
)

# Server ------------------------------------------------------------------

server <- function(input, output, session) {
  observeEvent(input$link_to_tabpanel_b, {
    tags$a(href = "#tab-4527-2")
  })
}

shinyApp(ui, server)

A: We have just released a routing library, which makes linking in Shiny easy. Here's how it looks like in a nutshell.
make_router(
   route("<your_app_url>/main",  main_page_shiny_ui),
   route("<your_app_url>/other", other_page_shiny_ui)
)

More information can be found in this blog post.

A: You can give your tabsetPanel an id and use updateTabsetPanel with your observeEvent
library(shiny)

# UI ---------------------------------------------------------------------

ui <- fluidPage(
  tabsetPanel(id = "demo",
    tabPanel(
      "A",
      p(),
      actionLink("link_to_tabpanel_b", "Link to panel B")
    ),
    tabPanel(
      "B",
      h3("Some information"),
      tags$li("Item 1"),
      tags$li("Item 2")
    )
  )
)

# Server ------------------------------------------------------------------

server <- function(input, output, session) {
  observeEvent(input$link_to_tabpanel_b, {
    updateTabsetPanel(session, "demo", "B")
  })
}

shinyApp(ui, server)

A: I was struggling with the same issue and really wanted to link to a different tab via the URL. Thanks to the simple example of thesadie and by using an observe to parse inputs from the url, for me the following worked (and made it possible to switch the tab by adding /?tab=B to the URL, e.g. http://localhost:1234/?tab=B):
library(shiny)

# UI ---------------------------------------------------------------------

ui <- fluidPage(
  tabsetPanel(id = "demo",
              tabPanel(
                "A",
                p(),
                actionLink("link_to_tabpanel_b", "Link to panel B")
              ),
              tabPanel(
                "B",
                h3("Some information"),
                tags$li("Item 1"),
                tags$li("Item 2")
              )
  )
)

# Server ------------------------------------------------------------------

server <- function(input, output, session) {
  # Allow url parsing
  observe({
    query <- parseQueryString(session$clientData$url_search)
    if (!is.null(query)) {
      for (name in names(query)) {
        if (name == "tab") {
          # Change tab
          try(updateTabsetPanel(session, "demo", selected = query[[name]]))
        } else {
          # Update inputs - this part is not really necessary if you just want to change the tabs,
          # but I also needed to update other inputs from the url
          try(updateTextInput(session, name, value = query[[name]]), silent = TRUE)
        }
      }
    }
  })

  observeEvent(input$link_to_tabpanel_b, {
    updateTabsetPanel(session, "demo", "B")
  })
}

shinyApp(ui, server)

A: The following solution is based on the inputs I got from the comments.
Note that updateTabsetPanel() belongs to shiny while updateTabItems() is a function of the shinydashboard package. They seem to work interchangeably.
library(shiny)
library(shinydashboard)

# UI ---------------------------------------------------------------------

ui <- fluidPage(
  tabsetPanel(
    id = "panels",
    tabPanel(
      "A",
      p(),
      actionLink("link_to_tabpanel_b", "Link to panel B")
    ),
    tabPanel(
      "B",
      h3("Some information"),
      tags$li("Item 1"),
      tags$li("Item 2"),
      actionLink("link_to_tabpanel_a", "Link to panel A")
    )
  )
)

# Server ------------------------------------------------------------------

server <- function(input, output, session) {
#   observeEvent(input$link_to_tabpanel_b, {
#     tags$a(href = "#tab-4527-2")
#   })
  observeEvent(input$link_to_tabpanel_b, {
    newvalue <- "B"
    updateTabItems(session, "panels", newvalue)
  })
  observeEvent(input$link_to_tabpanel_a, {
    newvalue <- "A"
    updateTabsetPanel(session, "panels", newvalue)
  })
}

shinyApp(ui, server)

A: According to the code and logic from Rappster. It is possible to set any kind of links. Link to TabsetPanel can be used by updataTabsetPanel. Link to Navbar can use updateNavbarPage(session, inputId, selected = NULL). These can be found by ?updateTabsetPanel as following.
updateTabsetPanel(session, inputId, selected = NULL)

updateNavbarPage(session, inputId, selected = NULL)

updateNavlistPanel(session, inputId, selected = NULL)

Please notice selected is the new id that you can define for tabsetPanel, Navbar, or NavlistPanel.


text:
Q: C# EF6 Groupjoin on stored procedure I try to do a GroupJoin on a stored procedure with entity framework 6.
This group join is working on Entity but on stored procedure I get an exception with this message :

"An error occurred while preparing the command definition. See the inner exception for details." and inner exception "The nested query does not have the appropriate keys.".

My stored procedure key is a Nullable int but I specified that Entity Framework need to use key.Value.
I don't understand where is the problem.
var test = contextEF.MyStoredProcedur(varInt)
.GroupJoin(contextEF.LinkedEntity, p => p.EntityId.Value, s => s.EntityId, (p, s) => new { p = p, s = s.ToList() }).ToList();

var test2 = contextEF.MyEntity
.GroupJoin(contextEF.LinkedEntity, p => p.EntityId.Value, s => s.EntityId, (p, s) => new { p = p, s = s.ToList() }).ToList();

test is not working. test2 is working


text:
Q: Getting core dumped? #include <stdio.h>
#include <cs50.h>
#include <stdbool.h>

typedef struct shop {

         string custName;

         string custAdd;

         string custNum;

         string custClothPrice;

struct shop* next;

}

shop;

int main (void)

{
struct shop* head;

   head = NULL;

struct shop* pointer=NULL;

printf("**********WELCOME TO AZIZIYAH CREATIONS**********\n\n");

char cont = 'y';

printf("Please enter customer details\n");

printf("Please Enter NAME   : ");

  head->custName = GetString();

printf("Please Enter Address: ");

  head->custAdd = GetString();

printf("Please Enter Cell No: ");

  head->custNum = GetString();
printf("Please Enter Price  : ");

  head->custClothPrice = GetString();

return 0;

printf("Would you liked to add more customer(s)?: Y/N:");

  cont = GetChar();

  head->next = pointer;

if (cont == 'Y' || cont == 'y')

 {

    pointer = malloc(sizeof(shop));

    pointer->next = NULL;

    }
while (cont == 'y' || cont == 'Y' )

{

printf("Please enter customer details\n");

printf("Please Enter NAME   : ");

    pointer->custName = GetString();

printf("Please Enter Address: ");

    pointer->custAdd = GetString();

printf("Please Enter Cell No: ");

    pointer->custNum = GetString();

printf("Please Enter Price  : ");

    pointer->custClothPrice = GetString();

printf("Would you liked to add more customer(s)?: Y/N:");

    cont = GetChar();
if (cont == 'Y' || cont == 'y')

{

    pointer->next = malloc(sizeof(shop));
    pointer = pointer ->next;

        }

    }

printf("\n\nDETAILS OF CUSTOMER ARE AS FOLLOWS:-\n");

struct shop* traverse;

    traverse = head;

    if (traverse->next == NULL)

printf("WAS FOUND NULL\n");

while (traverse->next != NULL)

{

printf("%s\n", traverse->custName);

printf("%s\n", traverse->custAdd);

printf("%s\n", traverse->custNum);

printf("%s\n", traverse->custClothPrice);

   traverse = traverse->next;
    }

    printf("**********THANK YOU FOR VISITING**********\n");

}

Had made an application it producing an error of Segmentation fault (core dumped) after First Input
OutPut
**********WELCOME TO AZIZIYAH CREATIONS**********
Please enter customer details
Please Enter NAME   : asd
Segmentation fault (core dumped)
kindly help please

A: The assignment to head->custName causes your crash: You need to allocate memory for head before you can write something to where it points to. If you don't do that, your program crashes. You can allocate memory for head with malloc() like this:
head = malloc(sizeof *head);
if (head == NULL) {
    /* error handling code here */
}

Remember to insert appropriate error handling code.


text:
Q: why CaptiveNetwork Reference is used I have to detect wifi networks available and need to connect using  my iPhone Application.
I found this about CaptiveNetwork Reference here
Is this API used to detect and connect with wifi?
If this is correct can you advise of other links or other API's that might also accomplish this?

A: No it will not allow your app to scan/detect network, it allows your app to handle the login for networks.
Meaning that if an user join a netwrok which requires a login (not via WPA or WEP) a loginsheet is presented.  If you set your app to handle the SSID kind of the networks you app wil be used to authenticate the user.

By calling the CNSetSupportedSSIDs function, an application can
  register a list of wireless network SSIDs with Captive Network
  Support, thereby assuming responsibility for authenticating with those
  networks. Typically when a user joins a captive network, Captive
  Network Support provides a web sheet that allows the user to
  authenticate with the network. If an application has registered the
  SSID of the captive network, however, the web sheet is suppressed, and
  the user can complete authentication in the appropriate application.


text:
Q: Does this JSON object contain a variable? I'm working with an API (DocumentCloud) using jQuery/JSON. I'm trying to retrieve a specific page of text, which the API almost provides.
The returned JSON contains an object called resources.page which offers the following:
text: "http://www.documentcloud.org/documents/293026/pages/ohio-higher-education-capital-funding-p{page}.txt"

The confusing part is the end: p{page}.txt
Is it possible to specify a page in place of {page} and return the content? (If I use "5" instead of {page} and put it into the browser, I see the text I'm looking for.)

A: Sure, you can use string.replace
    var text = "http://www.documentcloud.org/documents/293026/pages/ohio-higher-education-capital-funding-p{page}.txt",
    urlString = '';

urlString = text.replace('{page}', '5');

$.ajax({
    url: urlString,
    dataType: 'jsonp',
    success : function (response) {
        alert(response);
    }
});

Test it here: http://jsfiddle.net/dy22q/
..fredrik


text:
Q: How do I perform a drag and delete item functionality in a RecyclerView I was able to implement drag and drop items in a list and reorder them. What I need to do is implement a delete functionality where one can select and hold an item and drag it to a trash icon. Once it overlaps the trash icon, the latter will change its color from grey to red. Once the user releases the item, a confirmation modal will appear.

From the demo, you can see that dragging the first three items in the list toward the trash icon did not turn the trash icon red but launched the modal. The fourth item did change the trash icon's color, but it was immediately removed from the list without confirmation.
The drag and drop is implemented using ItemTouchHelperCallback:
public class EditItemTouchHelperCallback extends ItemTouchHelper.Callback {

    private final RVAdapter mAdapter;
    private RecyclerView.ViewHolder curHolder;

    private int curPos;
    private boolean deletedSomething;
    private CreatePhotostoryActivity cpa;

    public EditItemTouchHelperCallback(RVAdapter adapter) {
        mAdapter = adapter;
        cpa = new CreatePhotostoryActivity();
    }

    @Override
    public boolean isLongPressDragEnabled() {
        return true;
    }

    @Override
    public boolean isItemViewSwipeEnabled() {
        return false;
    }

    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.START | ItemTouchHelper.END;
        int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
        return makeMovementFlags(dragFlags, swipeFlags);
    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
                          RecyclerView.ViewHolder target) {
        curPos = target.getAdapterPosition();
        if(!deletedSomething){
            mAdapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
        }
        return true;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        mAdapter.onItemDismiss(viewHolder.getAdapterPosition());
    }

    @Override
    public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        CreatePhotostoryActivity.trashNavbar.setVisibility(View.GONE);
        CreatePhotostoryActivity.navbar.setVisibility(View.VISIBLE);
    }

    @Override
    public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {

        boolean isOver = false;
        deletedSomething = false;

        CreatePhotostoryActivity.trashNavbar.setVisibility(View.VISIBLE);
        CreatePhotostoryActivity.trashNavbar.bringToFront();
        CreatePhotostoryActivity.navbar.setVisibility(View.GONE);

        if(ItemTouchHelper.ACTION_STATE_DRAG == actionState) {
            if (isViewOverlapping(viewHolder.itemView, CreatePhotostoryActivity.trashNavbar)) {
                CreatePhotostoryActivity.trashIcon.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.red500));
                //delete moment
                mAdapter.onItemDismiss(viewHolder.getAdapterPosition());
            } else {
                CreatePhotostoryActivity.trashIcon.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.grey700));
            }

            curHolder=viewHolder;
            curPos = curHolder.getAdapterPosition();
            Log.v("Selected","a viewholder "+ curPos);
        }

        if (isViewOverlapping(curHolder.itemView, CreatePhotostoryActivity.trashNavbar)) {
            isOver = true;
        }

        if(isOver) {
            deletedSomething = true;
            mAdapter.showConfirmationDialogDeleteMoment(curPos);
            Log.v("Dropped","a viewholder "+curHolder);
        }
    }

    private boolean isViewOverlapping(View firstView, View secondView) {
        int[] firstPosition = new int[2];
        int[] secondPosition = new int[2];

        firstView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        firstView.getLocationOnScreen(firstPosition);
        secondView.getLocationOnScreen(secondPosition);
        int r = firstView.getMeasuredHeight() + firstPosition[1];
        int l = secondPosition[1];
        return r >= l && (r != 0 && l != 0);
    }

}

As you can see it's onSelectedChanged that sets the color of the trash icon and calls the method to launch the confirmation modal. I'm not really sure if I placed the methods in the correct position. In my adapter, I use the following method to delete the item from the list:
@Override
public void onItemDismiss(int position) {
    moments.remove(position);
    notifyItemRemoved(position);
}

The method to launch the confirmation modal calls the above method. It is also located in my adapter:
public void showConfirmationDialogDeleteMoment(final int position) {
    AlertDialog.Builder builder =  new AlertDialog.Builder(createPhotoStoryLayout.getContext(), R.style.AlertDialog);
    builder.setTitle("DO YOU WANT TO DELETE THIS MOMENT?")
            .setPositiveButton("DELETE", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    onItemDismiss(position);
                }
            })
            .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    //do nothing
                }
            })
            .setIcon(0);
    AlertDialog alert = builder.create();
    alert.show();
    alert.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,
            (int) (170 * Resources.getSystem().getDisplayMetrics().density));
    AlertUtils.displayDialog(createPhotoStoryLayout.getContext(), alert, R.drawable.red_500_pill, R.drawable.grey_700_pill, R.color.red500, R.color.grey700);

}

Basically, what I want is something similar to the Android OS, where a user drags the app to the Uninstall icon, changes the icon's color to red, and deletes the app once it's released.

A: For developers that still looking for a solution; just an idea, you can try below code. A part of my ItemTouchHelper.Callback implementation. I tried and its working fine in my case.
    interface Callback{
        fun isInDeleteArea(dX: Float, dY: Float): Boolean
    }

    private var removeItem = false

    lateinit var callback: Callback

    override fun onChildDraw(
        c: Canvas,
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder,
        dX: Float,
        dY: Float,
        actionState: Int,
        isCurrentlyActive: Boolean
    ) {
        if (isCurrentlyActive.not() && callback.isInDeleteArea(dX, dY)) {
            removeItem = true
            viewHolder.itemView.isGone = true
            return
        }

        viewHolder.itemView.translationY = dY
        viewHolder.itemView.translationX = dX
    }

    override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {

    }

    override fun getAnimationDuration(
        recyclerView: RecyclerView,
        animationType: Int,
        animateDx: Float,
        animateDy: Float
    ): Long {
        if (removeItem) return 0
        return super.getAnimationDuration(recyclerView, animationType, animateDx, animateDy)
    }

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {}

    override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
        removeItem = false
        super.onSelectedChanged(viewHolder, actionState)
    }


text:
Q: angular-auth-oidc-client logout not working I am using angular-auth-oidc-client lib for authenticating my app with keycloak as the identity server.i am able to login into the app however the logout functionality is not working. I've read the docs and am using the same call for logout but it doesn't seem to work. Please help. Thanks in advance.
Here is my config:
{
    "sts_server": "http://localhost/auth/realms/test",
    "redirect_url": "http://localhost:4200/app/",
    "client_id": "test_client",
    "response_type": "code",
    "scope": "openid profile email",
    "post_logout_redirect_uri": "http://localhost:4200/app/#/homepage/",
    "startup_route": "/homepage/welcome",
    "start_checksession": "true",
    "silent_renew": "true",
    "silent_renew_url": "assets",
    "max_id_token_iat_offset_allowed_in_seconds": "10",
    "logLevel": "info",
    "forbidden_route": "/unauthorized",
    "unauthorized_route": "/unauthorized"
}

My logout method:
  logOut() {
        this.oidcSecurityService.logoffLocal();
        this.oidcSecurityService.logoffAndRevokeTokens();
        this.oidcSecurityService.logoff();
// none of the three mentioned above work.

      }

A: You have to subscribe to this methods.
 this.sercurityService.logoff().subscribe((result) => {
      // any
    });

A: No solution, but more info:

It looks like the call to /logout is cancelled. However, if I paste that into the browser, it does log me out, so the url and functionality seem ok.


text:
Q: Karma-coverage cannot be found I am trying to add karma coverage to my application however I keep getting the message "Cannot load coverage, it is not registered!"
However I have used "npm install karma-coverage --save-dev" to ensure that karma is installed locally in my node_modules folder, which it is.
My abbreviated file structure is:
app/
    node_modules/
        karma/
        karma_coverage/ // Coverage is in fact installed, with the other karma modules, as far as I understand this means the plugin should be automatically found and added to the project.
    public/ // Application files go here.
    tests/
        controllers/ // contains controller tests
        coverage/ // Contains coverage results (I might not need this, I'm not sure yet).
        services/ // contains service tests
        karma.config.js

package.json
  "devDependencies": {
      "jasmine-core": "^2.3.4",
      "karma": "^0.13.10",
      "karma-chrome-launcher": "^0.2.0",
      "karma-coverage": "^0.5.2", // I swear it's installed...
      "karma-firefox-launcher": "^0.1.6",
      "karma-ie-launcher": "^0.2.0",
      "karma-jasmine": "^0.3.6",
      "karma-ng-html2js-preprocessor": "~0.1",
      "karma-requirejs": "^0.2.2",
      "karma-safari-launcher": "^0.1.1"
    }

karma.config.js:
// Karma configuration

module.exports = function(config) {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '../public/',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine'],

        // list of files / patterns to load in the browser
        files: [
          'js/lib/angular/angular.js',
          'js/*.js',
          'js/lib/*.js',
          'js/lib/angular/angular-ui-states.js',
          'modules/*/*Ctrl.js',
          '../tests/angular-mocks.js',
          '../tests/**/*.js'
        ],

        // list of files to exclude
        exclude: [
          'js/passport.js'
        ],

        // test results reporter to use
        // possible values: 'dots', 'progress', 'coverage'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress', 'coverage'],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-               preprocessor
        preprocessors: {
          'modules/**/*.js': ['coverage'],
          'js/servicess.js': ['coverage']
        },

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome', 'IE', 'Safari', 'Firefox'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false
    })
}

It doesn't make sense that karma isn't automatically loading coverage like the rest of the modules, but I decided to manually add coverage into the plugins to see if that resolved the problem.
I added the following code to the karma.config.js file between frameworks and files.
// pluguns to use
    plugins: [
        'karma',
        'karma-jasmine',
        'karma-coverage'
    ],

This change gives me a slightly different error, "Cannot find plugin karma-coverage, did you forget to install it?" but ultimately it's saying the same thing, it can't find the coverage plugin.
What am I missing here?

A: I'm not sure why this worked but I got it working.
First I deleted my global karma install
> npm uninstall -g karma

Next I installed karma-cli globally
> npm install -g karma-cli

And boom it worked fine.


text:
Q: Use chains in Laravel jobs I try to sheduling jobs with chains in Laravel 8. This variant work fine
$schedule->job((new  $mainclassname ($parser) )->chain($jobs))->dailyAt('8:33');

But if i try to use Bus
 $schedule->job(Bus::chain($jobs))->dailyAt('8:33');

I get error
Call to undefined method Illuminate\Foundation\Bus\PendingChain::__invoke() {"exception":"[object] (Error(code: 0): Call to undefined method Illuminate\Foundation\Bus\PendingChain::__invoke() at /var/www/cruiz.laravel/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:36)


text:
Q: VS Compiler warning 4239 caused by default argument I have this declaration of a method and faced to a VS2015 compiler warning C4239:

warning C4239: nonstandard extension used: 'default argument': conversion from 'std::shared_ptr' to 'std::shared_ptr &'

note: A non-const reference may only be bound to an lvalue

void checkMe(shared_ptr<string>& param = shared_ptr<string>());
This MSDN article says it is a /W4 warning. Fun fact: /W3 is set.
To be honest, I'm not a pro regarding default arguments, but in the implementation is no real use of having an empty instance of the shared_ptr without usage afterwards. But I'd rather understand the issue than adjusting  the functionality.
How and why then can I get rid of the warning? Or is there any legal way of doing this?
Thanks


text:
Q: "bnr not recognised as internal command" while developing ionic2-cordova app This is the error i am getting when i am trying to build android. Can anyone help?
'bnr' is not recognized as an internal or external command, operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! ionic2-taxi-app@0.1.0 dev: `bnr dev`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ionic2-taxi-app@0.1.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\VARANASI\AppData\Roaming\npm-cache\_logs\2017-07-    01T13_14_22_953Z-debug.log

A: In the project I'm currently working on, that error sometime occurs. Usually when some command execution fails, but I don't know exactly the cause. Anyway, it seems executing npm install again solves the problem.


text:
Q: separating data frames instead of dropping in pandas In python when using pandas, the similar rows can be dropped using drop_duplicates. Is there any way to separate the dataframe into two dataframes and not actually "drop" rows?

A: If you want to split the dataframe by duplicates, maybe you could use the boolean array returned by.duplicated():
>>> df = pd.DataFrame({"A": [1,1,2,3,2,4]})
>>> df
   A
0  1
1  1
2  2
3  3
4  2
5  4

[6 rows x 1 columns]
>>> df_a, df_b= df[~df.duplicated()], df[df.duplicated()]
>>> df_a
   A
0  1
2  2
3  3
5  4

[4 rows x 1 columns]
>>> df_b
   A
1  1
4  2

[2 rows x 1 columns]


text:
Q: Window event not removing inside class

class Panel {
  domElement = document.createElement("dialog");
  dragMouseStartX = 0;
  dragMouseStartY = 0;
  dragElementStartX = 0;
  dragElementStartY = 0;

  mousemove(event) {
    const style = this.domElement.style;
    const x = this.dragElementStartX + (event.clientX - this.dragMouseStartX);
    const y = this.dragElementStartY + (event.clientY - this.dragMouseStartY);
    style.left = x + "px";
    style.top = y + "px";
  }
  mouseup(event) {
    window.removeEventListener("mousemove", this.mousemove.bind(this));
    window.removeEventListener("mouseup", this.mouseup.bind(this));
  }
  mousedown(event) {
    window.addEventListener("mousemove", this.mousemove.bind(this));
    window.addEventListener("mouseup", this.mouseup.bind(this));
    const bounding = this.domElement.getBoundingClientRect();
    this.dragMouseStartX = event.clientX;
    this.dragMouseStartY = event.clientY;
    this.dragElementStartX = bounding.left;
    this.dragElementStartY = bounding.top;
  }
  constructor() {
    document.body.appendChild(this.domElement);
    this.domElement.addEventListener("mousedown", this.mousedown.bind(this));
    this.domElement.setAttribute("open", "true");
  }
}
const prop = new Panel();
*{
  box-sizing: border-box;
  margin: unset;
}
dialog{
  position: fixed;
}
<script src="resource/scripts/engine.js"></script>

I want to create a drag and drop program in Typescript, but I encountered the following problem.
My code doesn't stop dragging and dropping and I can't remove its class function from the window object inside the class!
What is the problem?


text:
Q: Need to open each login in the same browser window by reading mailids and passwords from a CSV file using Java in Selenium I'm trying to read a CSV file containing Mail ids and Passwords using java in Selenium .After reading it, I need to login to each of these mail ids in the same browser. I have written the entire code for this, but the issue is that it is opening each userlogins in different browser windows. My requirement is to open each userlogins in the same browser window. I'm using Firefox browser.
Below is my entire code:
    package NewCsvPkg;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
//import org.openqa.selenium.support.ui.ExpectedConditions;
//import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.WebDriverWait;

//csv reader imports
import java.io.FileReader;
import java.util.Iterator;
import java.util.List;
//import au.com.bytecode.opencsv.CSVReader;
import com.opencsv.CSVReader;
public class NewCsvClass {

  public static void main(String[] args) throws Exception  {

      //put this 4 lines inside while loop.

//         WebDriver driver = new FirefoxDriver();
//       String appUrl = "https://accounts.google.com";
//       driver.get(appUrl);
//       driver.manage().window().maximize();

     //csv reader aswathy -start
        CSVReader reader = new CSVReader(new FileReader("/home/user/Documents/UrmilaDocs/CSV PAck/testCSV.csv"));
        String [] nextLine;

        while ((nextLine = reader.readNext())!= null){

        String user_name = nextLine[0];
        String pass_word = nextLine[1];

        System.out.println("Username: " + user_name);
        System.out.println("Password: " + pass_word);

    //stackoverflow
        WebDriver driver = new FirefoxDriver();
         String appUrl = "https://accounts.google.com";
         driver.get(appUrl);
         driver.manage().window().maximize();

        WebElement username = driver.findElement(By.xpath(".//*[@id='Email']"));
        username.clear();
        username.sendKeys(user_name);
        driver.findElement(By.xpath(".//*[@id='next']")).click();

        Thread.sleep(5000);
             //try
             try{
            WebElement password = driver.findElement(By.xpath(".//*[@id='Passwd']"));
              password.clear();
              password.sendKeys( pass_word);
              driver.findElement(By.xpath(".//*[@id='signIn']")).click();
        Thread.sleep(8000);

        //click on 'Google Apps' icon
        driver.findElement(By.xpath(".//*[@id='gbwa']/div[1]/a")).click();
        Thread.sleep(10000);

        //Click on 'Gmail' icon to navigate to inbox page
        driver.findElement(By.xpath(".//*[@id='gb23']/span[1]")).click();
        Thread.sleep(10000);
        System.out.println("Login Success");

        //Click on user name first letter circle icon
        driver.findElement(By.xpath(".//*[@id='gb']/div[1]/div[1]/div[2]/div[4]/div[1]/a/span")).click();
        Thread.sleep(5000);

        //click on 'Signout' button
        driver.findElement(By.xpath(".//*[@id='gb_71']")).click();
        Thread.sleep(10000);
        System.out.println("Logout Success");

        /*click on 'Signin with a different account ' option (since, after signing out from
//      the first user, he page is navigated to password entry page, which is supposed to navigate to
//      username/mailid entry page  */
        driver.findElement(By.xpath(".//*[@id='account-chooser-link']")).click();
        Thread.sleep(10000);
//      /* In 'Choose an Account page', Click on 'Add Account' button */
        driver.findElement(By.xpath(".//*[@id='account-chooser-add-account']")).click();
        Thread.sleep(10000);
//
    }catch(Exception e)
             {
                 System.out.println("Login failed!");
             }// catch closed
//           //closing driver & firefox
             //driver.close();
             //System.exit(0);
            //end
        }   //while end

//      //closing driver & firefox
        // driver.close();
//     //csv reader aswathy -end
        System.exit(0);       //closing firefox

  }

  }

A:     You should initialise driver before entering into loop, currently you are initialising driver in loop thus causing driver to open multiple windows, also close firefox only after completing loop else you may face problem in next iteration of loop.

    Change it like this:

     //Initialise driver here and then go to loop:
            WebDriver driver = new FirefoxDriver();
             String appUrl = "https://accounts.google.com";
             driver.get(appUrl);
             driver.manage().window().maximize();

     while ((nextLine = reader.readNext())!= null){

            String user_name = nextLine[0];
            String pass_word = nextLine[1];

            System.out.println("Username: " + user_name);
            System.out.println("Password: " + pass_word);

    }

   System.exit(0);


text:
Q: Notification not working with Android 4.0
Possible Duplicate:
OnMessage i want to open Google Play android

When I use the below code in Android 4.0 (ICS) it doesn't work:
     NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(R.drawable.ic_launcher, "Testomg", System.currentTimeMillis() + 5000);

    Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
    notificationIntent.setData(Uri.parse("market://details?id=com.karya.kot"));
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent intent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
    notification.setLatestEventInfo(getApplicationContext(), "Google Play", "Download app", intent);

    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(0, notification);

But it's works for lower versions of Android.
For Android ICS, I want to use Notification.Builder, but then what should I use for lower versions?

A: Below is full working code for me on any version of the android 2.2 and above
private static void generateNotification(Context context, String message) {
        int icon = R.drawable.ic_launcher;
        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(icon, message, when);

        String title = context.getString(R.string.app_name);

        Intent notificationIntent = new Intent(context, <nameofactivity>.class);
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent =
                PendingIntent.getActivity(context, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        // Play default notification sound
        notification.defaults |= Notification.DEFAULT_SOUND;

        // Vibrate if vibrate is enabled
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notificationManager.notify(0, notification);

    }


text:
Q: How to correctly call base class constructor Base class:
abstract class AbstractHandler {
    use FeedbackTrait;

    /** @var EntityManager */
    private $entityManager;
    /** @var SessionInterface */
    private $session;

    /**
     * Constructor.
     *
     * @param EntityManager    $entityManager
     * @param SessionInterface $session
     */
    public function __construct(
        EntityManager $entityManager,
        SessionInterface $session
    ) {
        $this->entityManager = $entityManager;
        $this->session = $session;
    }

    /**
     * @return EntityManager
     */
    protected function getEntityManager() {
        return $this->entityManager;
    }

    /**
     * @return FlashBagInterface
     */
    protected function getFeedback() {
        /** @var FlashBagInterface $feedback */
        $feedback = $this->session->getBag('boltforms');

        return $feedback;
    }
}

Then, in the member class I have its own constructor. But I can't get how to properly call the base class contructor.
class bigbrotherHandler extends AbstractHandler {
    //custom class vars

    public function __construct() {
        parent::__construct();
        //custom declarations
    }
}

PhpStorm says Required parameter $entityManager missing. But how do I mention this parameter here? If I go with parent::__construct($entityManager);, it says Undefined variable $entityManager. If I just copy the data from the braces in the base class constructor, it also gives all sorts of errors. How can I properly call my base class constructor in this case?

A: You have to call parent constructor with parameters as it has been declared in your abstract class.
class bigbrotherHandler extends AbstractHandler {
    public function __construct(EntityManager $entityManager,SessionInterface $session) {
         parent::__construct($entityManager, $session);
         //custom declarations
     }
 }

BTW think about making "FeedbackProvider" as a standalone service and injecting this service into another services via constructor or method injection (not via setter).


text:
Q: json_decode in php problem with "-" character in string I have a problem with parsing data in json exposed with strings that contain the character "-", for example "foo-opened". All strings containing the value "-" in the php file return value 0 or error.
FILE JSON:
{
  "overview": [
    {
      "foo": {
        "foo-opened": 0,
        "foo-total": 110,
        "foo-closed": 110
      }
    }
  ],
}

FILE PHP
<?php
header('Content-type: text/html; charset=UTF-8');
$url = "data.json";
$contents = file_get_contents($url);
$obj=json_decode($contents);
$FooTotal = $obj->overview[0]->foo->foo-opened;
$FooOpen = $obj->overview[0]->foo->foo-total;
$FooClosed = $obj->overview[0]->foo->foo-closed;
echo "

Foo total:" . $FooTotal . "

Foo open:" . $FooOpen . "

Foo closed:" . $FooClosed . "

";
 ?>

Thank you in advance for your help!

A: You need to access the prop via $obj->overview[0]->foo->{'foo-total'}


text:
Q: Grid Filter for Milestine and display color not working Can anybody help me get Milestone and Displaycolor work in My grid filter?
I am able to get Milestone and DisplayColor in filter box but they are not working. The filter is not applied to grid
Thanks
HSG
this.add({
                        xtype: 'rallygridboard',
                        context: context,
                        modelNames: modelNames,
                        toggleState: 'board',
                        stateful: false,
                        plugins: [
                            {
                                ptype: 'rallygridboardinlinefiltercontrol',
                                inlineFilterButtonConfig: {
                                    stateful: true,
                                    stateId: context.getScopedStateId('filters'),
                                    modelNames: modelNames,
                                    inlineFilterPanelConfig: {
                                        quickFilterPanelConfig: {
                                            defaultFields: ['ArtifactSearch'],
                                            addQuickFilterConfig: {
                                                whiteListFields: whiteListFields
                                            }
                                        },
                                        advancedFilterPanelConfig: {
                                            advancedFilterRowsConfig: {
                                                propertyFieldConfig: {
                                                    whiteListFields: whiteListFields
                                                }
                                            }
                                        }
                                    }
                                }
                            },
                            {
                                ptype: 'rallygridboardfieldpicker',
                                headerPosition: 'left',
                                modelNames: modelNames,
                                stateful: true,
                                stateId: context.getScopedStateId('columns-example')
                            },
                            {
                                ptype: 'rallygridboardactionsmenu',
                                menuItems: [
                                    {
                                        text: 'Print...',
                                        handler: function () {
                                            this.down('rallygridboard').getGridOrBoard().openPrintPage({ title: 'Program Board' });
                                        },
                                        scope: this
                                    }
                                    //
                                ],
                                buttonConfig: {
                                    iconCls: 'icon-export'
                                }
                            }
                        ],
                        cardBoardConfig: {
                            plugins: [
                                { ptype: 'rallyfixedheadercardboard' },
                                { ptype: 'rallycardboardprinting' }
                            ],
                            readOnly: true,
                            rowConfig: {
                                field: 'Project'
                            },
                            columns: columns,
                            attribute: 'Iteration'
                        },
                        storeConfig: {
                            fetch: ['Iteration', 'Name', 'StartDate', 'EndDate']
                        }
                    });


text:
Q: Adding/set variable to Array from another method Ok, so I'm more of a dunce than a beginner so bear with me.
What I'm trying to accomplished is to try to set/add variable within an array.
The question I am doing is to create a package and call another method called addAccommodation(); and use that method to add the required info and adding it to TravelPackage travelpackage.
I'm posting section of the issue here. The arraylist is called travelPackages and the one I want to add variables into is TravelPackage travelpackage.
(addAccommodation(); is the method soppose to lead another section, and travelpackage.setAccID is the issue I'm trying to solve)
public void addPackages() {
    Scanner input = new Scanner(System.in);
    System.out.println("Input Customer ID: ");
    int customerID = input.nextInt();
    input.nextLine();
    System.out.print("Input Duration in Days: ");
    int duration = input.nextInt();
    input.nextLine();

    System.out.print("Date in format yyyy-mm-dd? ");
    String date = input.nextLine();
      LocalDate startDate = null;
      try{
       startDate = LocalDate.parse(date);
     }
      catch(Exception e){}

    TravelPackage travelpackage = new TravelPackage(customerID, duration, startDate);
    travelPackages.add(travelpackage);
    addAccommodation();

}

public void addAccommodation(){
    Scanner input = new Scanner(System.in);
     boolean match = false;
      while(true) {
        System.out.print("Input Accommodation Type(Hotel, Lodge, Ski Club, Apartment, Village): ");
        String type = input.nextLine();
         for (Accommodation a: accommodations) {
          if (a.getType().equalsIgnoreCase(type) && a.getAvailability()) {
            // Update accommodation status  in ArrayList
            a.setAvailability(false);
            travelpackage.setAccID(a.getAccID());
            // Set match flag to break loop
             match = true;
            // Stop searching for matching bike
             break;
           }
         }
         if(match){
          System.out.println("Did not find a match.");
          break;
         }
      }
}

It keep saying cannot find symbol. Is there something I'm missing here? (Sorry if I can't provide proper info, I am quite dumb)


text:
Q: Running excel line graph I have a set of data points in a spreadsheet with another set of line graphs plotting that data over time.  New data in entered every month and each month I have to manually update the charts to display the new data.
I would like a solution to get the chart to automatically pick up the new data once entered.
I know this can be done because for some (minority) of my sheets, this happens automatically so long as my input range extends to columns beyond what has been populated.
However when I try to do this in other charts, this skews the graph such that the section to the right is empty/blank (as the values have not yet been entered)
I have tried to assess the differences in the graphs (both line charts, data entered is the same format etc) but have not been able to identify any differences.
[Data is entered for a number of parameters over time. Time is plotted in columns from left to right and can not easily be changed due to the number of other data series in the range.
Speadsheets are created in Excel 1997-2003 and 2007 though I cannot associate a link to updating charts to either version]

A: The difference probably isn't in the graphs, but in the raw data.
Convert your row data to tables (insert tab - table), then select again the source data of the charts, so instead of cell references (e.g. A1:E50) you'll see the name of the table (e.g. Table1).
This way whenever you enter new data your chart will be updated automatically.


text:
Q: How to Count a value in a column if another column with the same row equals to something?

*John

*james

*john

I want to count a number in the number column if the same row corresponds a spesific name.
For example i want to count how many 202 number that corresponds john.

A: You can use Click here COUNTIFS formula. Assuming in column A numbers available and in coulmn B names available then your formula will be
=COUNTIFS(B:B,B1,A:A,A1)

Hope this is what you need :)

A: You can use a PivotTable to do this.
First make sure your data has column headers (Numberand Name in your example). Select your data, including headers, and choose Insert -> PivotTable. Accept the default settings in the dialog. In the table editor, drag Name to "Columns" and Number to "Rows". Then drag Name into "Values".
Your end result should look like the screenshot below. The number in each cell is the number of times that each combination of name and number occurs.


text:
Q: Can't rearrange Mission Control spaces I can't rearrange full screen spaces in mission control.  When I drag one to move it, it never seems to stick back onto the mission control bar.  If I drop the space on the bar the animation shows it going back to the dock and it disappears from the mission control bar.  I can drag the space from the bar to the desktop.
It tends to leave behind a semi transparent image of the full screen view (similar to the one that can be dragged around in mission control) and this persists even after mission control is closed.  The only way to get rid of it is to restart my machine.
What's going on and how can I fix it?

A: Just to reconfirm that I understand it correct, the issue is:
On trying to move full-screen apps between two spaces by going into spaces (press F3 button or 3-finger swipe above), it (full-screen app) just slips to one the desktops and doesn't get accommodated like desktops (space is created automatically by the GUI for insertion and you can drop the desktop there).
Have found the following:

*

*Generally restarting the Mac solves this issue for some time (few days) but then it returns again.

*Once the full screen app drops into one of the desktops, pick it and insert it where you want in the top spaces panel.

This is not exactly a solution but a workaround or change of habit if you don't want to restart your mac for something so trivial.
Hope this helps in reducing the inconvenience.


text:
Q: How can I check how much disk space is being used by Kafka My disk space is running out, after syncing 2 millions message in one of my Kafka topic. I even deleted the topic but still the space is somehow seems consumed. Any help of link would be appreciated.

A: Use the below command to know how much disk space consumed by each topic
du -sh /tmp/kafka-logs/*

A: Another way to determine the size of the topic to send metrics, such as graphite. Then the size can be found as follows:
kafka.log.Log.<topic_name>-<partition_number>-Size.value

A: *

*To delete messages from the topic you shall first set retention time to e.g. 1000ms. This will purge all messages in 1 sec. (see the answer: The correct config key is retention.ms)

*Delete the topic

*General think through the retention time for all topics, as default is 7 days, what might be quite much, when you operate with high frequecies.

A: From server.properties
#A comma separated list of directories under which to store log files
log.dirs=/tmp/kafka-logs
du will work but make sure to check all log directories. In fact, any normal unix command that you like to check disk space will work.
Deleting topic does not guarantee deletion. It will put it in "to be deleted" state. If you have any producer/consumer still attached to the topic, it will not be removed. Try the following:

*

*Make sure all brokers that have topic replicas are running

*Make sure you allow topic deletion
delete.topic.enable = true

*Check if topic was deleted
bin/kafka-topics.sh --list --zookeeper zookeeper_host:2181


text:
Q: Remove non-ASCII non-printable characters from a String I get user input including non-ASCII characters and non-printable characters, such as
\xc2d
\xa0
\xe7
\xc3\ufffdd
\xc3\ufffdd
\xc2\xa0
\xc3\xa7
\xa0\xa0

for example:
email : abc@gmail.com\xa0\xa0
street : 123 Main St.\xc2\xa0

desired output:
  email : abc@gmail.com
  street : 123 Main St.

What is the best way to removing them using Java?
I tried the following, but doesn't seem to work
public static void main(String args[]) throws UnsupportedEncodingException {
        String s = "abc@gmail\\xe9.com";
        String email = "abc@gmail.com\\xa0\\xa0";

        System.out.println(s.replaceAll("\\P{Print}", ""));
        System.out.println(email.replaceAll("\\P{Print}", ""));
    }

Output
abc@gmail\xe9.com
abc@gmail.com\xa0\xa0

A: Your requirements are not clear. All characters in a Java String are Unicode characters, so if you remove them, you'll be left with an empty string. I assume what you mean is that you want to remove any non-ASCII, non-printable characters.
String clean = str.replaceAll("\\P{Print}", "");

Here, \p{Print} represents a POSIX character class for printable ASCII characters, while \P{Print} is the complement of that class. With this expression, all characters that are not printable ASCII are replaced with the empty string. (The extra backslash is because \ starts an escape sequence in string literals.)

Apparently, all the input characters are actually ASCII characters that represent a printable encoding of non-printable or non-ASCII characters. Mongo shouldn't have any trouble with these strings, because they contain only plain printable ASCII characters.
This all sounds a little fishy to me. What I believe is happening is that the data really do contain non-printable and non-ASCII characters, and another component (like a logging framework) is replacing these with a printable representation. In your simple tests, you are failing to translate the printable representation back to the original string, so you mistakenly believe the first regular expression is not working.
That's my guess, but if I've misread the situation and you really do need to strip out literal \xHH escapes, you can do it with the following regular expression.
String clean = str.replaceAll("\\\\x\\p{XDigit}{2}", "");

The API documentation for the Pattern class does a good job of listing all of the syntax supported by Java's regex library. For more elaboration on what all of the syntax means, I have found the Regular-Expressions.info site very helpful.

A: You can try this code:
public String cleanInvalidCharacters(String in) {
    StringBuilder out = new StringBuilder();
    char current;
    if (in == null || ("".equals(in))) {
        return "";
    }
    for (int i = 0; i < in.length(); i++) {
        current = in.charAt(i);
        if ((current == 0x9)
                || (current == 0xA)
                || (current == 0xD)
                || ((current >= 0x20) && (current <= 0xD7FF))
                || ((current >= 0xE000) && (current <= 0xFFFD))
                || ((current >= 0x10000) && (current <= 0x10FFFF))) {
            out.append(current);
        }

    }
    return out.toString().replaceAll("\\s", " ");
}

It works for me to remove invalid characters from String.

A: You can use java.text.normalizer

A: With Google Guava's CharMatcher, you can remove any non-printable characters and then retain all ASCII characters (dropping any accents) like this:
String printable = CharMatcher.INVISIBLE.removeFrom(input);
String clean = CharMatcher.ASCII.retainFrom(printable);

Not sure if that's what you really want, but it removes anything expressed as escape sequences in your question's sample data.

A: I know it's maybe late but for future reference:
String clean = str.replaceAll("\\P{Print}", "");

Removes all non printable characters, but that includes \n (line feed), \t(tab) and \r(carriage return), and sometimes you want to keep those characters.
For that problem use inverted logic:
String clean = str.replaceAll("[^\\n\\r\\t\\p{Print}]", "");

A: Input => "This \u7279text \u7279is what I need"
Output => "This text is what I need"
If you are trying to remove Unicode characters from a string like above this code will work
Pattern unicodeCharsPattern = Pattern.compile("\\\\u(\\p{XDigit}{4})");
Matcher unicodeMatcher = unicodeChars.matcher(data);
String cleanData = null;
if (unicodeMatcher.find()) {
    cleanData = unicodeMatcher.replaceAll("");
}


text:
Q: Push Notifications on iOS and Android for website I'm struggling with a scenario where I have a website that is accessed by Android and iOS(written in HTML/Javascript) where the customer is asking for push notifications for both platforms.
Is there anyone here with an idea on how to solve that for both platforms? I was thinking of packaging the website as an application using Cordova. I haven't tried it before so I am looking into that now. If there is any better suggestion then I would really appreciate to hear that.


text:
Q: Gd Library Flip image and saving it I am using PHP GD library to flip an image and then save that flipped image. However I am able to flip image successfully but I don't know how to save it with another name in a folder. My code is
$filename = '324234234234.jpg';
header('Content-type: image/jpeg');
$im = imagecreatefromjpeg($filename);
imageflip($im, IMG_FLIP_VERTICAL);
imagejpeg($im);

A: You need to pass a second parameter to imagejpeg($im) call with the path to the file you want to store.
imagejpeg($im, 'path/to/new/file.jpg');

http://php.net/manual/en/function.imagejpeg.php

A: Look at the documentation for imagejpeg where it explains the second parameter relates to $filename:

bool imagejpeg ( resource $image [, string $filename [, int $quality ]] )
The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.

So just add the new filename as a second parameter like this; assuming the name of the new name is new_filename.jpg. Also comment out or completely remove the header line so you are not outputting the image to the browser, but rather saving it to a file so the header isn't needed:
$filename = '324234234234.jpg';
// header('Content-type: image/jpeg');
$im = imagecreatefromjpeg($filename);
imageflip($im, IMG_FLIP_VERTICAL);
imagejpeg($im, 'new_filename.jpg');

Also note that while imageflip is nice to use it is only available in PHP 5.5 & higher; it won't be available in PHP 5.4 or lower:

(PHP 5 >= 5.5.0)
image flip — Flips an image using a given mode

So if you want to use it in PHP 5.4 or lower, you need to create the logic to flip it on your own in the code or use a function like this. It only flips horizontally so you would have to adjust it to flip vertically, but posting here so you have something to explore & work with if needed:
/**
 * Flip (mirror) an image left to right.
 *
 * @param image  resource
 * @param x      int
 * @param y      int
 * @param width  int
 * @param height int
 * @return bool
 * @require PHP 3.0.7 (function_exists), GD1
 */
function imageflip(&$image, $x = 0, $y = 0, $width = null, $height = null)
{
    if ($width  < 1) $width  = imagesx($image);
    if ($height < 1) $height = imagesy($image);
    // Truecolor provides better results, if possible.
    if (function_exists('imageistruecolor') && imageistruecolor($image))
    {
        $tmp = imagecreatetruecolor(1, $height);
    }
    else
    {
        $tmp = imagecreate(1, $height);
    }
    $x2 = $x + $width - 1;
    for ($i = (int) floor(($width - 1) / 2); $i >= 0; $i--)
    {
        // Backup right stripe.
        imagecopy($tmp,   $image, 0,        0,  $x2 - $i, $y, 1, $height);
        // Copy left stripe to the right.
        imagecopy($image, $image, $x2 - $i, $y, $x + $i,  $y, 1, $height);
        // Copy backuped right stripe to the left.
        imagecopy($image, $tmp,   $x + $i,  $y, 0,        0,  1, $height);
    }
    imagedestroy($tmp);
    return true;
}


text:
Q: Flatten JSON-response I have issues with flattening this JSON due to the ending of it which I actually don't need so I could potentially remove it (before or after flattern the JSON). I would like to do this in Python and have tried json_normalized and Panda for export to CSV.
What's special, the last three items, TotalNumberOfMunicipalities, TotalCitizens, Aggregations, lies outside the part I would like to export to CSV after flattern.
JSON:
{
    "Municipalities": [
        {
            "Name": "Stockholm",
            "NumberOfCitizens": 974073,
            "Id": "5203d2be-7cda-4caf-9fb5",
            "Attributes": [],
            "Location": {
                "Lat": 59.33,
                "Lon": 18.06
            },
            "PoliticalGovernance": 1
        },
        {
            "Name": "Uppsala",
            "NumerOfCitizens": 230767,
            "Id": "d155e5f5-b94a-4d0e-ba80",
            "Attributes": [],
            "Location": {
                "Lat": 59.86,
                "Lon": 17.64
            },
            "PoliticalGovernance": 3
        }
    ],
    "TotalNumberOfMunicipalities": 33,
    "TotalCitizens": 4000000,
    "Aggregations": {}
}

How I would like the output to be

A: Use pd.json_normalize:
df = pd.json_normalize(d, 'Municipalities')
print (df)
        Name  NumberOfCitizens                       Id Attributes  \
0  Stockholm            974073  5203d2be-7cda-4caf-9fb5         []
1    Uppsala            230767  d155e5f5-b94a-4d0e-ba80         []

   PoliticalGovernance  Location.Lat  Location.Lon
0                    1         59.33         18.06
1                    3         59.86         17.64


text:
Q: Good GUI and UI-Designer Extension with Drag and Drop for VS2012 I'm programmed a algorithm. Now I'm looking for a good and simple designer, where I can integrate my sourcecode. My Source is written in C/C++ including WinAPI for Bluetooth-Devices.
I tried C++/CLR .NET with winforms but it's not so well. Someone tolds me that I should use MFC in VS 2012 but it's not a elegant way.
QT5Creator is also not possible: I think my code is not compatible with it.
Do you have any experience with any extensions for VS2012?
Thanks


text:
Q: button "Post" in SLComposeViewController I am developing a share extension for my application and wanted to know if it was possible to change the text of the button "Post" in SLComposeViewController.
I tried in all ways but I just can not figure out if it can do
Thanks a lot in advance
Luca

A: This is impossible to change the text of Post and cancel button in SLComposeViewController.
Apple doesn't provide any api for this.
So you can't.


text:
Q: Union of events as the Complement of their complements intersection Just need some quick clarification on this:
Let A and B be independent i..e $P(A \cap B) = P(A)P(B)$
$P(A \cup B) = P(A) + P(B) -  P(A)P(B)$
$=  1 - (1 - P(A))(1-P(B))$
$=  1 - (P(A^c))(P(B^c))$
$= P(A^c \cap B^c)^c = P(A \cup B)$
Have I done this correctly?
And I assume the intuition is that the probability of A and or B happening, which is like A and B both being coloured in, in our Ven Diagram, is equal to the probability, of 1 - Both of them not happening, which is 1 - all the space serrounhding A and B. I.e. the Complement of Both A and B complement.
Thanks!


text:
Q: How to change React parent component size based on child component size without rendering child component? I've created a React component which takes any component and renders it as a Pop-up. A parent component receives the component to be rendered (popped up). The rendered component is here the child component which using react-sizeme to get its size and pass back to parent component. The parent component must take the dimensions of child component, so adjusts' its height and width. This is the code:

class Popup extends React.Component<IPopupProps,IComponent>{
    constructor(props:IPopupProps){
        super(props);
        this.state={
            childComponent:this.props.children,
            style:{
                height:0,
                width:0
            }
        }
    }

    // This function runs two times, before and after rendering child component
    // & so have an improper visualization as the size is changed twice here

    public OnSize = (size:any) =>{
        const width = size.width +20;
        const height =size.height+20;
        this.setState({
            style:{height,
                width             }
        })
    }

    public render(){
        return(

                            ×

                    <this.state.childComponent onSize={this.OnSize}/>

        )
    }
}

The initial width and height is set to 0. So it doesn't renders properly. So is there any way so that to hide the child component or avoid its rendering before parent component gets the size?
EDIT: We can't get the size until the child component is rendered. So is there any trick to get this done. Just a component needs to be popped-up properly.
EDIT 2: Here's the PropsBuilder.tsx which calls the Popup.tsx and sends the component to display as children

class PopupBuilder extends React.Component<IPopupBuilderProps, IPopup>{
    constructor(props:IPopupBuilderProps){
        super(props);
        this.state = {
            showPopup:false
        }
    }

    public togglePopup = () =>{
        this.setState({
            showPopup:!this.state.showPopup
        })
    }

    public render (){
        return(
            <React.Fragment>

                    <button onClick={this.togglePopup}>{this.props.trigger}</button>

                    <React.Fragment>
                        {this.state.showPopup?<Popup onExit={this.togglePopup} >{this.props.component}</Popup>:null}
                    </React.Fragment>

            </React.Fragment>

        )
    }
}

export default PopupBuilder;

A: Actually, this looks like more general DOM/JavaScript question.
Consider such case:
const span = document.createElement('span');
span.innerText = 'hello';
span.getBoundingClientRect() // -> { width: 0, height: 0, top: 0, … }

This is an indicator that you don't know the dimensions of the element until it is in DOM (Rendered in react);
document.body.appendChild(span);
span.getBoundingClientRect(); // -> {width: 50, height: 16,  …}

My recommendation to you in this case are:

*

*Child component should accept a property (function) from Parent one

*Use React "ref" feature to find actual dimensions of Child element

*Call the function in 'componentDidMount' (use componentDidUpdate if child can change dynamically), passing it child component dimensions.

If you don't have access to child component. You may wrap it like this:
// Popup.tsx

class Popup .... {
 ...
   render() {
     <Measurer>{this.props.children}</Measurer>
   }
}

and implement the logic of fetching dimensions in it. Measurer is a direct child of Popup and their communication can be controlled by you.


text:
Q: Error: Gradle: execution failed for task ':app:preDexDebug' I had a self created jar from another projected imported as a library into my other project. When I changed code in that project and exported a new jar to replaced the old one I cannot run my app anymore. I only get the following error:

I have tried removing and adding and adding as dependency, adding as library. Nothing seems to work. I have also done clean build and a rebuild.

A: We've seen this problem in the past when our project was compiling with a version of Java different from the one used to compile the library. The magic number is just used to identify class files so that is not the problem here. The issue is the java version (0034.0000 == Java 8).
The easiest thing to do is target Java 6, which may require removing newer syntax from your code. In our case, both the project and library were ours so we were able to add the following to force the version of Java that we needed:
Android Libraries
for android libraries, add this code to the "android" extension object:
android {
    ...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_6
        targetCompatibility JavaVersion.VERSION_1_6
    }
    ...
}

Java Libraries
for java libraries, add this code at the "top level":
apply plugin: 'java'

version '1.8.1'
group   'com.yourcompany.package'

sourceCompatibility = JavaVersion.VERSION_1_6   //these two lines
targetCompatibility = JavaVersion.VERSION_1_6   //are the only ones that matter

NOTE: the last two lines are the only ones that matter, I added the others just to show where those lines belong, in respect to the rest of your gradle build file.

A: For us, this was caused by the Android SDK build-tools version. Got the problem on v23.x, but not v22.x. You need to uninstall v23 for cordova to pick v22.
Possibly a symptom rather than a cause, but this may unstick someone in the same situation.

A: Although your problem seems fixed, I ended up here with a similar error (while building the samples from developer.android.com). In case it's helpful to others, I was able to solve it by setting JAVA_HOME to the appropriate value. In my case it was:
export JAVA_HOME=/usr/lib/jvm/java-6-openjdk-amd64

A: adding:
sourceCompatibility = JavaVersion.VERSION_X_X
targetCompatibility = JavaVersion.VERSION_X_X

in the Android project gradle file and the Java library gradle file worked for me.
Sorry I would have +1'd it but don't have a high enough reputation


text:
Q: Can't download excel file from C# I'm working on adding Export functionality to an existing site. I've created an Excel file, and I'm able to output it to my local directory, but when I try pushing the file to the user using Response, nothing happens. I've viewed several differnet articles and Stack questions, and none seem to be different from what I have, or work when I apply them.
Here is the code I currently have:
public void Export () {
     //Create instance of the database
     ExportContext eDB = new ExportContext();

     var query = (from x in eDB.EMPLOYEES
                      select x);

     IEnumerable<EMPLOYEES> employees = query.ToList();

     //Set filename to Table + date/time
     string fileName = "EMPLOYEES" + DateTime.Now.ToShortTimeString() + ".xlsx";

     //Create excel package
     ExcelPackage excel = new ExcelPackage();
     var worksheet = excel.Workbook.Worksheets.Add("Employees");
     worksheet.Cells[1, 1].LoadFromCollection(employees, true);

     using (var memoryStream = new MemoryStream()) {
        //Output the file to the user via download
        Response.Buffer = false;
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
        excel.SaveAs(memoryStream);
        memoryStream.WriteTo(Response.OutputStream);
        Response.Flush();
        Response.Close();
        Response.End();
     }
  }

Any help will be appreciated. Thanks.


text:
Q: android Image resize in listview I've got an ImageView in a relative layout both with following properties android:layout_width="wrap_content" android:layout_height="wrap_content"

I fill this layout in a ListItem within a mainactivity with the help of an Adapter. Then I try to resize in Adapter with the code below;
DisplayMetrics dm = new DisplayMetrics(); dm = ctx .getResources().getDisplayMetrics(); int width = dm.widthPixels; int height = width * 243 / 325;

          RelativeLayout.LayoutParams layoutParams = new

RelativeLayout.LayoutParams(width, height); thumbImage.setLayoutParams(layoutParams);

But the images get stuck in the listview item even smaller than their original size.
xml that contains imageview that is filled in Adapter is,
<?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="?android:attr/listPreferredItemHeight" android:padding="0dp">

<TextView
    android:id="@+id/tvKategori"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"

/>

<ImageView
    android:id="@+id/ivThumbnail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:adjustViewBounds="false" />

<TextView
    android:id="@+id/tvTitle"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
     />

</relativelayout>

And this is the mainactivity xml that has the listview and I fill lvGununVideolari listview and lvEnCokIzlenenler content.
<android.support.v4.widget.drawerlayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent">

<!-- Framelayout to display Fragments -->
<FrameLayout
    android:id="@+id/frame_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

/>

<!-- Listview to display slider menu -->
<ExpandableListView
    android:id="@+id/list_slidermenu"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:divider="@color/list_divider"
    android:dividerHeight="1dp"
    android:listSelector="@drawable/list_selector"
    android:background="@color/list_background"/>

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="0px"
android:paddingLeft="0px"
android:paddingRight="0px"
android:paddingTop="0px" >

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:paddingBottom="0px"
    android:paddingLeft="0px"
    android:paddingRight="0px"
    android:paddingTop="0px"
    android:weightSum="1.0" >

    <Button
        android:id="@+id/btnGununVideolari"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight=".5"
        android:text="Günün Videoları"
        android:textSize="12sp" />

    <Button
        android:id="@+id/btnEnCokIzlenenler"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight=".5"
        android:text="En Çok İzlenenler"
        android:textSize="12sp" />
</LinearLayout>

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <ListView
        android:id="@+id/lvGununVideolari"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="0px"
        android:paddingLeft="0px"
        android:paddingRight="0px"
        android:paddingTop="0px" >
    </ListView>

    <ListView
        android:id="@+id/lvEnCokIzlenenler"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:paddingBottom="0px"
        android:paddingLeft="0px"
        android:paddingRight="0px"
        android:paddingTop="0px" >

    </ListView>
</RelativeLayout>

</linearlayout> </android.support.v4.widget.drawerlayout>

A: You need to setup the way Image should be scaled, like:
<ImageView
    android:id="@+id/ivThumbnail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
android:scaleType="fitXY"
    android:adjustViewBounds="false" />

And there are other options available for scaleType.
But thats not all, also to do autoresize you need to setup particular size of ImageView like:
<ImageView
    android:id="@+id/ivThumbnail"
    android:layout_width="50dp"
    android:layout_height="50dp"
android:scaleType="fitXY"
    android:adjustViewBounds="false" />

however you do mostly the same in code via LayoutParams :)


text:
Q: PHP HTML Purifier and MathML Is there any simple way to allow all MathML tags with attributes in HTML Purifier?
I tried to put all the MathML tags from https://developer.mozilla.org/en-US/docs/Web/MathML/Element/semantics with attributes to HTML.Allowed but I don't know if this is the right way.

A: There's currently no native support for MathML in HTML Purifier. There's an old pull request you could potentially repurpose here, but as it's a few years old patching it in will almost surely require significant manual effort; see also some discussion here:

The primary consideration is security. When adding a very big new
extension like MathML, it is very tempting to cut corners, and not
truly understand every corner of the specification and build a parser
that truly understands what it reads, and isn't just checking
syntax blindly.

Alternatively you could use the customization guide to add them as new tags and attributes to HTML Purifier, but that's more work, not less.
Simply adding the tags to HTML.Allowed won't do much - HTML Purifier's strength is that it understands the context that tags appear in, where they're allowed to appear and what restrictions make sense on their attributes (e.g. an attribute like 'width' takes integers, but an attribute like 'style' takes CSS (that will be sanitised separately), and an attribute like 'onclick' is unsafe by definition). If HTML Purifier doesn't know anything about a particular tag, it won't allow it, even if you add it to the allowlist, because it won't know how to actually handle the tag.
In short:
No, there is unfortunately no simple way to allow MathML in HTML Purifier.


text:
Q: Mapping different https subdomains to different ECS containers on same application load balancer? I'm using the Docker ECS integration to deploy an app and a webservice it depends on. Both should be running over HTTPS, at different subdomains.
My problem is, both need to run over HTTPS but since the ECS docker thing only created one load balancer, it looks like I can only configure it to forward https traffic to one target group. Is there a way to get this to work?

A: Yes, when you add the HTTPS listener to the load balancer, set the default rule to forward to one of the target groups (probably the main web app). But then go back to the list of listeners and click "View/edit rules". You can then add a Host Header rule for each additional service. The host header just equals the domain name, including subdomain, e.g. service-A.example.com. That way one HTTPS listener can handle every subdomain on the same application load balancer. The documentation for this is here.
Note: If HTTP and HTTPS listeners aren't available, you may have accidentally created a network load balancer. This happens when at least one of your services exposes a port other than 80 or 443. To force it to be an application load balancer (which will let you forward HTTP and HTTPS traffic), your docker-compose config needs to look like this:
  test:
    image: mycompany/webapp
    ports:
      - target: 8080
        x-aws-protocol: http