text:
Q: Scraping cascade selects' text with selenium/c# This is my first post on stackoverflow, even though i've been lurking in the shadows for past 10 years. :D
So, I have a task to scrape data off of a site which contains 3 cascade select lists / dropdowns, call it what ever you like. As I've played around selenium, I thought of giving a try with it. BUT I keep getting this :
"OpenQA.Selenium.StaleElementReferenceException"

I get the gist of it:
1) I declare a first list "Makes" of IWebElements which load up with all elements from first dropdown. => **works fine**
2) Then I iterate through the list using foreach, something like
foreach (var make in makes)
{
   make.click() // step 3
   ... // step 4
}
3.As seen above I click on the first element so it can fetch data for another dropdown
4.I point to another list "Models" and repeat the process for iterating the second list and console.writeline it's content.

So it gives me first element from the first list "makes", all of members from the second list "Models", as it is supposed to. But as soon as it proceeds to another member of the first list (first foreach), it says that Make is stale "OpenQA.Selenium.StaleElementReferenceException"

Cheers!


text:
Q: Sharing resources in Azure Resource Manager Template I have multiple Azure WebApps that share the same connection strings (and app settings). I would like to refactor the below so that the config connectionstring resource is only defined once and referenced from each WebApp. Is this possible? If so, how?
// some sections clipped for brevity
{
  "apiVersion": "2015-08-01",
  "name": "[variables('apiPortalName')]",
  "type": "Microsoft.Web/sites",
  "dependsOn": [
    "[concat('Microsoft.Web/serverFarms/', variables('hostingPlanName'))]"
  ],
  "resources": [
    {
      "apiVersion": "2015-08-01",
      "type": "config",
      "name": "connectionstrings",
      "dependsOn": [
        "[concat('Microsoft.Web/Sites/', variables('apiPortalName'))]"
      ],
      "properties": {
        "Default": {
          "value": "[concat('Data Source=tcp:', reference(concat('Microsoft.Sql/servers/', variables('sqlServerName'))).fullyQualifiedDomainName, ',1433;Initial Catalog=', variables('settingsDatabaseName'), ';User Id=', parameters('databaseAdminLogin'), '@', variables('sqlServerName'), ';Password=', parameters('databaseAdminPassword'), ';')]",
          "type": "SQLAzure"
        }
      }
    }
  ]
},
{
  "apiVersion": "2015-08-01",
  "name": "[variables('userPortalName')]",
  "type": "Microsoft.Web/sites",
  "dependsOn": [
    "[concat('Microsoft.Web/serverFarms/', variables('hostingPlanName'))]"
  ],
  "resources": [
    {
      "apiVersion": "2015-08-01",
      "type": "config",
      "name": "connectionstrings",
      "dependsOn": [
        "[concat('Microsoft.Web/Sites/', variables('userPortalName'))]"
      ],
      "properties": {
        "Default": {
          "value": "[concat('Data Source=tcp:', reference(concat('Microsoft.Sql/servers/', variables('sqlServerName'))).fullyQualifiedDomainName, ',1433;Initial Catalog=', variables('settingsDatabaseName'), ';User Id=', parameters('databaseAdminLogin'), '@', variables('sqlServerName'), ';Password=', parameters('databaseAdminPassword'), ';')]",
          "type": "SQLAzure"
        }
      }
    }
  ]
}

A: If your web sites are similar enough, you can create multiple sites that use a copy loop.  e.g.
  "variables": {
    "webSiteNameArray": ["apiPortalName", "userPortalName"]
  },

  "resources": [
    {
      "apiVersion": "2015-08-01",
      "name": "[variables('webSiteNameArray')[copyIndex()]]",
          "type": "Microsoft.Web/sites",
          "copy": {
            "name": "webSiteLoop",
            "count": 2
          },
      "dependsOn": [
        "[concat('Microsoft.Web/serverFarms/', variables('hostingPlanName'))]"
      ],
      "resources": [
        {
          "apiVersion": "2015-08-01",
          "type": "config",
          "name": "connectionstrings",
          "dependsOn": [
            "[concat('Microsoft.Web/Sites/', variables('webSiteNameArray')[copyIndex()])]"
          ],
          "properties": {
            "Default": {
              "value": "[concat('Data Source=tcp:', reference(concat('Microsoft.Sql/servers/', variables('sqlServerName'))).fullyQualifiedDomainName, ',1433;Initial Catalog=', variables('settingsDatabaseName'), ';User Id=', parameters('databaseAdminLogin'), '@', variables('sqlServerName'), ';Password=', parameters('databaseAdminPassword'), ';')]",
          "type": "SQLAzure"
            }
          }
        }
      ]
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't install numpy on Mountain Lion I'm completely new to Python, I'm trying to install NLTK based on http://nltk.org/install.html
I've got everything installed except for numpy (it says numpy is optional but when I try to import nltk, it says there's an error because it couldn't find the numpy module)
after I run sudo pip install -U numpy
I'm running on a Mac with Mountain Lion, python v2.7.3
I get the following error (I only included the end of log):

File "/private/tmp/pip-build/numpy/numpy/core/setup.py", line 696, in get_mathlib_info
raise RuntimeError("Broken toolchain: cannot link a simple C program")
RuntimeError: Broken toolchain: cannot link a simple C program

Command python setup.py egg_info failed with error code 1 in /tmp/pip-build/numpy

Has anyone seen this happen?

A: If you open a command prompt and type gcc does it run without error? If not, you may need to install XCode (available on the appstore) and then the command line tools (it looks similar to this post) so that you can complete the install for numpy.

A: Recently I had been seeing this along with:

clang: error: unknown argument: '-mno-fused-madd'
  [-Wunused-command-line-argument-hard-error-in-future]

See here to fix:
clang error: unknown argument: '-mno-fused-madd' (python package installation failure)

A: Looks to me like this question has already been answered here: Problems with pip install numpy - RuntimeError: Broken toolchain: cannot link a simple C program
Setting ARCHFLAGS enabled me to install numpy (running Mavericks with Command Line tools 5.1.1):
ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install --upgrade numpy


text:
Q: How to create a basic UDP listener with Spring Boot Being new to both Spring and UDP, I have spent a lot of time on researching this subject without finding a good answer. I need to build a listener that potentially can handle large amounts of messages and forward them to Kafka.

A: Ended up with a solution that uses java.net datagram classes in a Spring ApplicationRunner component implementation.


text:
Q: How to create a custom JTable? I am making a chat application in Java. They can add friends and chat with them.
Here is my add friend JFrame idea:

I tried to google search Multi jpanel in one jscrollpane but I found nothing. I ended up with custom JTable. I want to create a custom JTable which have JLabels in different position in each slot. Users can just select a slot in JTable, then they can use the JButton below to chat with them.
Is it possible to do this in Java. Is yes, please share your idea. Thanks.

A: Here is a proposal. But it contains some flaws yet

*

*Size propagation is fiexed (may be better client or server based sizing)

*No event delegation to underlying Component

*Performance, because heavyweight panel instances are created frequently inside paint loop

But here is how it can be done. The code is separated into parts.
A value class
Just a simple class to represent the date inside your panels for each cell.
class Value {
    public final String text;
    public final boolean flag;
    public Value(String text, boolean flag) {
        this.text = text;
        this.flag = flag;
    }
}

My individual panel class
The representation can be modelled within a gui editor like google's window builder. This panel makes use of the value and displays it accordingly.
public class MyPanel extends JPanel {
    public MyPanel(Value v) {
        JLabel lblNewLabel = new JLabel(v.text);
        add(lblNewLabel);
        JCheckBox chckbxSomeValue = new JCheckBox("some value");
        chckbxSomeValue.setSelected(v.flag);
        add(chckbxSomeValue);
    }
}

A table cell renderer class
Just returns some panel instance showing up the desired values.
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

class MyPanelCellRenderer implements TableCellRenderer {
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
        return new MyPanel((Value)value); // maybe performance problem
    }
}

A custom table model
import javax.swing.table.DefaultTableModel;

class MyTableModel extends DefaultTableModel {
    public MyTableModel() {
        super(new Object[][] {
                        new Object[] { 1, new Value("asdf", true) },
                        new Object[] { 2, new Value("qwer", false) } },
                        new String[] {"Id", "MyPanel" });
    }

    Class[] columnTypes = new Class[] { Integer.class, Value.class };

    MyTableModel(Object[][] data, Object[] columnNames) {
        super(data, columnNames);
    }

    public Class getColumnClass(int columnIndex) {
        return columnTypes[columnIndex];
    }
}

A frame class
import java.awt.BorderLayout;

public class MyFrame {
    JFrame frame;
    private JTable table;

    public MyFrame() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        table = new JTable();
        table.setModel(new MyTableModel());
        table.setFillsViewportHeight(true);
        table.getColumnModel()
            .getColumn(1)
            .setCellRenderer(new MyPanelCellRenderer());
        table.setRowHeight(40); // static sizing

        JScrollPane scrollPane = new JScrollPane();
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
        scrollPane.setViewportView(table);
    }
}

Main Function
import java.awt.EventQueue;

public class MyApp {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MyFrame window = new MyFrame();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

The final result

The panel MyPanel is created using eclipse and google's window builder

A: This is a completely different approach using neither a table nor a list. It uses panels as items arranged as a list inside of another panel. This solution doesn't requires any further modification to delegate any events to the underlying controls. The events are processed natively. The idea comes from this post. I have separated the logic into two parts for now.

JPanelList class
This class is a JPanel and maintains a list of such. ATM they can be added using the methods addPanel and addPanels.
public class JPanelList extends JPanel {
    private static final long serialVersionUID = 1L;
    private JPanel mainList;
    private List<JPanel> panels = new ArrayList<JPanel>();
    public JPanelList() { this(new ArrayList<JPanel>()); }
    public JPanelList(List<JPanel> panels) {
        setLayout(new BorderLayout());
        mainList = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.weightx = 1;
        gbc.weighty = 1;
        mainList.add(new JPanel(), gbc);
        add(new JScrollPane(mainList));
        addPanels(panels);
    }
    public void addPanels(List<JPanel> panels) {
        for (JPanel panel : panels)
            addPanel(panel);
    }
    public void addPanel(JPanel panel) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.weightx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        mainList.add(panel, gbc, 0);
        panels.add(panel);
        validate();
        repaint();
    }
}

JListFrame test class with main function
public class JPanelListFrame {
    private JFrame frame;
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JPanelListFrame window = new JPanelListFrame();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public JPanelListFrame() {
        frame = new JFrame();
        frame.setBounds(100, 100, 210, 192);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JPanelList panelList = new JPanelList();
        frame.getContentPane().add(panelList, BorderLayout.CENTER);
        JButton btnAddMypanel = new JButton("Add MyPanel");
        btnAddMypanel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // just add a MyPanel with a Value containing a
                // "asdf" and a random boolean
                panelList.addPanel(new MyPanel(new Value("asdf",
                        (int) (2 * Math.random()) % 2 == 0)));
            }
        });
        panelList.add(btnAddMypanel, BorderLayout.SOUTH);
    }
}

One drawback with this solution is that the selection mechanics are lost. When selecting elements is a key requirement maybe a JList might be more appropriate. Another thing is that the items are not rendered as they would be rendered inside a JList or JTable e.g. using fancy borders. This can be solved by somehow adding a border decorator before adding the panels into the mainList of the JPanelList.


text:
Q: Apache Spark : How to deal with hierachical data I'm quite new to spark. I would like to know if spark can handle a hierachy of data like a tree. (without using graphx)
let's say I have a tree represented in a flat file

*

*Key  Value

*A1   P1

*A1   P2

*P1   S1

*P1   S2

*P1   S3

*P2   S4

*S1   C1

*S1   C2

Is there a way to force Spark to reduce in the following order:

*

*S1 (C1+C2)

*P1 (S1+S2+S3) and P2 (S4)

*and then once P1 and P2 are reduced

*A1 (P1+P2)

If I use a "reduceByKey" the order is random.
Thanks for any hint

A: You can write the code yourself to do this, but AFAIK you cannot do this via the API. The approach to do it, will vary depending on the use-case and the characteristics of graph(e.g. huge number of edges, intense computations, large nodes/data)
One approach to do this, assuming that the number of nodes is low is to process the graph level by level. In order to do that, you will need to extract the graph hierarchy information to a Broadcast variable and the apply a set of Unions and Filters until you've computed the top level nodes.
As @zero323 said, this might be a bit tricky if you are new to Spark, but in my use-cases it worked perfectly aggregating +80000 nodes with 100s GBs of underlying data.
The way to think about it is that each call to Spark aggregates one graph level. Hence, if the depth of your graph is high or you have billions of nodes this approach will not work.


text:
Q: "Called object type NSString is not a function or function pointer" error? - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.cellIdentifier = [self.brain returnCellIdentifier:indexPath];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier];

    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:self.cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    cell.textLabel.text = [self.brain enchantmentCellText:indexPath];

    return cell;
}

I have no idea why I am getting this error.  The error seems to come from the line that my cursor is on.  How can I fix this error:
Semantic issue
Called object type 'NSString *' is not a function or function pointer

A: I had this exact same error and discovered it was caused because I had created an array manually by typing out all of it's elements, and had forgotten a comma in between two of them.

A: I'm not entirely sure why you have that error, but if you don't have a need for the cell identifier to be different (which it doesn't appear you do) you may want to change that line your cursor is on to the more standard:
static NSString *CellIdentifier = @"Cell";

which would change your other lines to something closer to:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                  reuseIdentifier:CellIdentifier];
}

The error itself may come from the method of your "brain" object that your calling.  If you post that we may be able to tell.
~ Good Luck


text:
Q: substring in R with stringr I have a string that looks like this :
my_sting="AC=1;AN=249706;AF=4.00471e-06;rf_tp_probability=8.55653e-01;"

it is based on a column in my data :

  REF ALT    QUAL FILTER  INFO
1   C   A 3817.77   PASS  AN=2;AF=4.00471e06;rf_tp_probability=8.55653
2   C   G 3817.77   PASS  AN=3;AF=5;rf_tp_probability=8.55653

i wish to select only the part that start with AF= and ends with the number AF is equal to .
for example here: AF=4.00471e-06
I tried this :
print(str_extract_all(my_sting, "AF=.+;"))
[[1]]
[1] "AF=4.00471e-06;rf_tp_probability=8.55653e-01;"

but it returned everything until the end. instead of returning AF=4.00471e-06
is there any way to fix this ? thank you

A: You can write the pattern using a negated character class [^;]+ as:
library(stringr)
my_sting="AC=1;AN=249706;AF=4.00471e-06;rf_tp_probability=8.55653e-01;"
print(str_extract_all(my_sting, "AF=[^;]+"))

Output
[[1]]
[1] "AF=4.00471e-06"

A: Another option. Use  "followed by ;" (i.e., (?=;))
my_sting="AC=1;AN=249706;AF=4.00471e-06;rf_tp_probability=8.55653e-01;"

str_extract(my_sting, "AF=.*?(?=;)")
#> [1] "AF=4.00471e-06"


text:
Q: Nothing inserted in database? I have the following code, it executes without any error and even reports that 1 row was affected. However, nothing is saved. Why not?
i can retrieve from the database though.. but cannot write
Dim SQLConn As New SqlConnection() 'The SQL Connection
SQLConn.ConnectionString = connstring 'Set the Connection String
SQLConn.Open()
Dim SQLCmd As New SqlCommand() 'The SQL Command
Dim SQLStr As String = "INSERT into region_table VALUES(10,23,4,'test')"
SQLCmd.CommandText = SQLStr
sqlCmd.ExecuteNonQuery()
SQLConn.Close()

SOLUTION::
Open right click on database connection in server explorer, Select Properties And use that Connection String! Hopes this solves anyone else's problem too :D

A: You are not assigning the connection to the command:
After this line:
SQLCmd.CommandText = SQLStr

add this one:
SQLCmd.Connection = SQLConn

You should also use using statements to ensure everything is cleaned up correctly:
    Using SQLConn As New SqlConnection() 'The SQL Connection
        SQLConn.ConnectionString = connstring 'Set the Connection String
        SQLConn.Open()
        Using SQLCmd As New SqlCommand() 'The SQL Command
            Dim SQLStr As String = "INSERT into region_table VALUES(10,23,4,'test')"
            SQLCmd.CommandText = SQLStr
            SQLCmd.Connection = SQLConn
            SQLCmd.ExecuteNonQuery()
            SQLConn.Close()
        End Using
    End Using

A: Have you tried checking the database path in the connection string? XD


text:
Q: Cannot see my AppWidget, that I'm trying to add to existing application I'm studying how to write own android applications. I wrote one by myself, and now I'm trying to implement an AppWidget for it.
I'm using this page as a guideline for my work.
I decided to implement an AppWidget, that will not have any logic at first, just a layout.
The project builds and run without errors, but, when I'm trying to add my widget to launcher, I don't see it in the list of available widgets.
I only can see my application in the list of applications, that have widgets, but, when trying to filter widgets by application, I see nothing.
I've searched for a solution, but didn't find any. Just found a problem with appwidgets in android 4.0.4, that is solved by rebooting a device or stating the main application if the widget has any.
The code of my widget you can see lower.
What is wrong in it? Is the problem in empty class?

I made the following changes in manifest:
<receiver android:name="ru.pinedevelop.wind.NormalWidget"
 android:label="@string/app_name"
 android:icon="@drawable/ic_launcher">
  <intent-filter>
   <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
  </intent-filter>
  <meta-data android:name="android.appwidget.provider"
   android:resource="@xml/normal_widget" />
</receiver>

Then added the following desctiption to xml/normal_widget.xml:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="schemas.android.com/apk/res/android"
                android:minWidth="146dip"
                android:minHeight="72dip"
                android:updatePeriodMillis="86400000"
                android:resizeMode="none"
                android:initialLayout="@layout/normal_widget_main" />

Later I added the following layout for my widget:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_gravity="center"
          android:background="@drawable/appwidget_dark_bg">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:layout_gravity="center">
    <TextView android:id="@+id/widget_spot_name"
              android:layout_height="wrap_content"
              android:layout_width="wrap_content"
              android:layout_gravity="center_vertical|left"
              android:textColor="@android:color/white"/>
    <TextView android:id="@+id/widget_spot_update_time"
              android:layout_height="wrap_content"
              android:layout_width="wrap_content"
              android:layout_gravity="center_vertical|left"
              android:textColor="@android:color/white"/>

</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:layout_gravity="center">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:orientation="vertical"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:layout_gravity="center">
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                      android:orientation="horizontal"
                      android:layout_width="fill_parent"
                      android:layout_height="wrap_content"
                      android:layout_gravity="center">
            <TextView android:id="@+id/widget_max_label"
                      android:layout_height="wrap_content"
                      android:layout_width="wrap_content"
                      android:text="@string/widget_label_max"
                      android:layout_gravity="center_vertical|left"
                      android:textColor="@android:color/white"/>
            <TextView android:id="@+id/widget_max_value"
                      android:layout_height="wrap_content"
                      android:layout_width="wrap_content"
                      android:layout_gravity="center_vertical|left"
                      android:textColor="@android:color/white"/>
        </LinearLayout>
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                      android:orientation="horizontal"
                      android:layout_width="fill_parent"
                      android:layout_height="wrap_content"
                      android:layout_gravity="center">
            <TextView android:id="@+id/widget_avg_label"
                      android:layout_height="wrap_content"
                      android:layout_width="wrap_content"
                      android:text="@string/widget_label_avg"
                      android:layout_gravity="center_vertical|left"
                      android:textColor="@android:color/white"/>
            <TextView android:id="@+id/widget_avg_value"
                      android:layout_height="wrap_content"
                      android:layout_width="wrap_content"
                      android:layout_gravity="center_vertical|left"
                      android:textColor="@android:color/white"/>
        </LinearLayout>
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                      android:orientation="horizontal"
                      android:layout_width="fill_parent"
                      android:layout_height="wrap_content"
                      android:layout_gravity="center">
            <TextView android:id="@+id/widget_min_label"
                      android:layout_height="wrap_content"
                      android:layout_width="wrap_content"
                      android:text="@string/widget_label_min"
                      android:layout_gravity="center_vertical|left"
                      android:textColor="@android:color/white"/>
            <TextView android:id="@+id/widget_min_value"
                      android:layout_height="wrap_content"
                      android:layout_width="wrap_content"
                      android:layout_gravity="center_vertical|left"
                      android:textColor="@android:color/white"/>
        </LinearLayout>
    </LinearLayout>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:orientation="vertical"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:layout_gravity="center">

        <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/widget_arrow"
                android:src="@drawable/arrow50"
                android:background="#ffffff"
                android:cropToPadding="false"
                android:contentDescription="@string/widget_arrow_descr"/>
    </LinearLayout>
</LinearLayout>
</LinearLayout>

And created a dummy class for it:
package ru.pinedevelop.wind;
import android.appwidget.AppWidgetProvider;
public class NormalWidget extends AppWidgetProvider {
}

A: I found out that a problem was in widget declaration.
I just edited a line, adding "http://":
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"...


text:
Q: My Array only goes up to 3 values and my second Array repeats whatever the user entered into the 2nd array I have changed up my code to be vectors. Now I am trying to find the Union, Intersection, and A-B. My code for both Union and Intersection now is working. I can not figure out how to do my difference. I figured I could take A and if it == to B then not insert it but it still puts them in none the less.
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
#include <algorithm>

using namespace std;

void Union();
void Intersection();
void Difference();

int main()
{
    Union();
    Intersection();
    Difference();

    return 0;
}

void SetVectors()
{

}

void Union()
{
        int temp = 0;
vector<int> U{};
vector<int> A{3, 4, 9, 12, 13, 15, 16, 17};

vector<int> B{1, 3, 5, 7, 9};

for(int i = 0; i < A.size(); i++)
{
    for (int j = 0; j < B.size(); j++)
    {

        if (A[i] != B[j])
        {
            int temp = A[i];
            U.push_back(temp);
            temp = B[j];
            U.push_back(temp);
        }

              //Used To Sort The Vector So There Is No Duplicates And Its In Order!
              sort( U.begin(), U.end() );
              U.erase( unique( U.begin(), U.end() ), U.end() );
    }

}
cout << "Union: ";
for(int z = 0; z < U.size(); z++)
{
    cout << U[z] << " ";
}
}

void Intersection()
{
        int temp = 0;
vector<int> U{};
vector<int> A{3, 4, 9, 12, 13, 15};
//Used To Sort The Vector So There Is No Duplicates And Its In Order!
sort( A.begin(), A.end() );
A.erase( unique( A.begin(), A.end() ), A.end() );

vector<int> B{1, 3, 5, 7, 9};
//Used To Sort The Vector So There Is No Duplicates And Its In Order!
sort( B.begin(), B.end() );
B.erase( unique( B.begin(), B.end() ), B.end() );

for(int i = 0; i < A.size(); i++)
{
    for (int j = 0; j < B.size(); j++)
    {

        if (A[i] == B[j])
        {
            int temp = A[i];
            U.push_back(temp);
            temp = B[j];
            U.push_back(temp);
        }

              //Used To Sort The Vector So There Is No Duplicates And Its In Order!
              sort( U.begin(), U.end() );
              U.erase( unique( U.begin(), U.end() ), U.end() );
    }

}
cout << "Intersection: ";
for(int z = 0; z < U.size(); z++)
{
    cout << U[z] << " ";
}
}

void Difference()
{
    int temp = 0;
    vector<int> D{};
    vector<int> A{3, 4, 9, 12, 13, 15};

    vector<int> B{1, 3, 5, 7, 9};

    for(int i = 0; i < A.size(); i++)
    {
        for (int j = 0; j < B.size(); j++)
        {

            if (A[i] == B[j])
            {
                cout << A[i];
            }
            else
            {
                int temp = A[i];
                D.push_back(temp);
            }

                  //Used To Sort The Vector So There Is No Duplicates And Its In Order!
                  sort( D.begin(), D.end() );
                  D.erase( unique( D.begin(), D.end() ), D.end() );
        }

    }
    cout << "Difference: ";
    for(int z = 0; z < D.size(); z++)
    {
        cout << D[z] << " ";
    }
}

A: The best help we can provide is to say "Don't do it that way..." Continuing from the comment int A [MaxSizeA]; is declared while MaxSizeA is zero attempting to declare an non-standard Variable Length Array (VLA) with zero elements. That won't work. For starters VLAs are not part of C++, and are only provided as non-standard compiler extensions by some compilers.
Bewilderingly, you #include <vector>, which is great -- that is what you want to use to store an unknown number of objects - but, you fail to make use of std::vector in your code.
Before looking at how you can use std::vector to accomplish what you are trying to do, take a quick look at Why is "using namespace std;" considered bad practice?. Learning good habits early is a lot easier than breaking bad ones later.
std::vector
std::vector allows you to add as many objects to your collection as you like and the memory management is handled automatically. In your case you can ask for MaxSizeA and MaxSizeB and then loop until the user has provided that many valid elements for each. Take A for example, you could do:
#include <limits>
...
    std::vector<int> A{}, B{};
    size_t MaxSizeA, MaxSizeB;
    int val;

    std::cout << "How Many Values Do You Wish To Enter For A: ";
    if (!(std::cin >> MaxSizeA)) {
        std::cerr << "error: invalid integer input.\n";
        return 1;
    }

    while (A.size() < MaxSizeA) {
        std::cout << "Enter Values For A[" << A.size() << "]: ";
        if (std::cin >> val)
            A.push_back(val);
        else {
            std::cerr << "  error: invalid integer input.\n";
            std::cin.clear();
            std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }

Where you declare your vectors and variables local to main(), there is no reason to use global variables here (and in fact they should be avoided unless absolutely necessary). You prompt for MaxSizeA and then validate the stream-state after your call to std::cin to ensure you have a valid integer value in MaxSizeA. Then you simply loop until A.size() == MaxSizeA ensuring your user provided MaxSizeA valid integer inputs. You handle a failed input by resetting the stream state and then clearing to the end of input with std::cin.ignore(). No counter is needed, you can simple use A.size() and B.size() to determine the current number of elements stored in each vector.
(you can also check std::cin.eof() and std::cin.bad() to catch a user manually generating EOF or catch an unrecoverable stream error -- that is left to you.)
You can use a Range-based for loop (since C++11) to output the contents of each vector, e.g.
    std::cout << "\narray A:\n";
    for (auto& v : A)
        std::cout << v << '\n';

Putting it altogether into an example similar to what your are attempting you would have:
#include <iostream>
#include <vector>
#include <limits>

int main() {

    std::vector<int> A{}, B{};
    size_t MaxSizeA, MaxSizeB;
    int val;

    std::cout << "How Many Values Do You Wish To Enter For A: ";
    if (!(std::cin >> MaxSizeA)) {
        std::cerr << "error: invalid integer input.\n";
        return 1;
    }

    while (A.size() < MaxSizeA) {
        std::cout << "Enter Values For A[" << A.size() << "]: ";
        if (std::cin >> val)
            A.push_back(val);
        else {
            std::cerr << "  error: invalid integer input.\n";
            std::cin.clear();
            std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }

    std::cout << "\nHow Many Values Do You Wish To Enter For B: ";
    if (!(std::cin >> MaxSizeB)) {
        std::cerr << "error: invalid integer input.\n";
        return 1;
    }

    while (B.size() < MaxSizeB) {
        std::cout << "Enter Values For B[" << B.size() << "]: ";
        if (std::cin >> val)
            B.push_back(val);
        else {
            std::cerr << "  error: invalid integer input.\n";
            std::cin.clear();
            std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }

    std::cout << "\narray A:\n";
    for (auto& v : A)
        std::cout << v << '\n';

    std::cout << "\narray B:\n";
    for (auto& v : B)
        std::cout << v << '\n';

}

Example Use/Output
Running the program and intentionally providing bad input to exercise the error handling you could do:
$ ./bin/arrayVLAtoVector
How Many Values Do You Wish To Enter For A: 4
Enter Values For A[0]: 10
Enter Values For A[1]: 20
Enter Values For A[2]: thirty
  error: invalid integer input.
Enter Values For A[2]: 30
Enter Values For A[3]: 40

How Many Values Do You Wish To Enter For B: 3
Enter Values For B[0]: 1
Enter Values For B[1]: 2
Enter Values For B[2]: buckle my shoe
  error: invalid integer input.
Enter Values For B[2]: 3

array A:
10
20
30
40

array B:
1
2
3

Look things over and let me know if you have further questions.


text:
Q: Firebase Uploader AsyncTask doinBackground() error android I am using chat application. Upto Android 28sdk its worked fine but after i refract to androidx am facing this problem please check my code below and error screenshot.
Error Code Image 1
Error Code Image 2

private void compressAndUpload(final Context context, final String child, final File file) {
        compressionTask = new AsyncTask<File, Void, String>() {
            @Override
            protected String doInBackground(File... files) {
                String filePathCompressed = null;
                Uri originalFileUri = Uri.fromFile(files[0]);
                File tempFile = new File(context.getCacheDir(), originalFileUri.getLastPathSegment());
                //tempFile = File.createTempFile(originalFileUri.getLastPathSegment(), null, context.getCacheDir());
                if (child.equals("images")) {
                    filePathCompressed = SiliCompressor.with(context).compress(originalFileUri.toString(), tempFile);
                } else {
                    try {
                        filePathCompressed = SiliCompressor.with(context).compressVideo(files[0].getPath(), context.getCacheDir().getPath());
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                }
                if (filePathCompressed == null)
                    filePathCompressed = "";
                return filePathCompressed;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                File compressed = new File(s);
                fileUri = Uri.fromFile(compressed.length() > 0 ? compressed : file);
                FirebaseStorage storage = FirebaseStorage.getInstance();
                if (uploadRef == null)
                    uploadRef = storage.getReference().child(child).child(fileUri.getLastPathSegment());

                if (replace) {
                    upload();
                } else {
                    checkIfExists();
                }
            }
        };

        compressionTask.execute(file);
    }


text:
Q: Filtering an array by date in Javascript I have an data structured like that:
8: {
      name: 8,
      type: "group",
      home_team: 15,
      away_team: 16,
      home_result: ' ',
      away_result: ' ',
      date: "2018-06-16T21:00:00+02:00",
      stadium: 4,
      channels: [],
      finished: false,
      group: "d"
    },
    23: {
      name: 23,
      type: "group",
      home_team: 13,
      away_team: 15,
      home_result: ' ',
      away_result: ' ',
      date: "2018-06-21T21:00:00+03:00",
      stadium: 6,
      channels: [],
      finished: false,
      group: "d"
    },

And want to create a function that returns the matches of the day.
So, how can I do a function called getMatchesOfDay(), that, with the current data, returns only the matches in the specific day?

A: Are you looking for something like this?

let x = {
    8: {
        name: 8,
        type: "group",
        home_team: 15,
        away_team: 16,
        home_result: ' ',
        away_result: ' ',
        date: "2018-06-16T21:00:00+02:00",
        stadium: 4,
        channels: [],
        finished: false,
        group: "d"
    },
    23: {
        name: 23,
        type: "group",
        home_team: 13,
        away_team: 15,
        home_result: ' ',
        away_result: ' ',
        date: "2018-06-21T21:00:00+03:00",
        stadium: 6,
        channels: [],
        finished: false,
        group: "d"
    }
}

const getMatches= function(date){
    Object.keys(x).forEach((obj) => {
    if (x[obj].date == myDate) {
        console.log(x[obj])
    }
})
}

let myDate = "2018-06-21T21:00:00+03:00";
getMatches(myDate)


text:
Q: Python tkinter and turtle errors after program stops sorry to bother anyone but when I run my code (my first attempt at a real game)  everything works fine, but then after I close it some errors print and I can't find anyone else with my problem.  My files is called Space Invaders.py, I am using Pycharm (these errors also occur with the IDLE).  This is my code:
import turtle
import math

print("------------Space Invaders - Python------------")
print("-------------GAME NOT YET COMPLETED------------")
print("This console is simply a status readout.")

wn = turtle.Screen()
wn.bgcolor("black")
wn.title("Space Invaders")

borderPen = turtle.Turtle()
borderPen.speed(0)
borderPen.color("white")
borderPen.penup()
borderPen.setposition(-400, -400)
borderPen.pendown()
borderPen.pensize(3)
for i in range(4):
    borderPen.fd(800)
    borderPen.lt(90)
borderPen.hideturtle()

player = turtle.Turtle()
player.setheading(90)
player.shape("triangle")
player.color("blue")
player.penup()
player.speed(0)
player.setposition(0, -350)

enemy = turtle.Turtle()
enemy.color("red")
enemy.shape("circle")
enemy.penup()
enemy.speed(0)
enemy.setposition(-300, 250)

movementStepE = 2
movementStepEY = -15
movementStepP = 5

def move_left():
    x = player.xcor()
    new_x = x - movementStepP
    if new_x < -380:
        new_x = -380
    player.setx(new_x)

def move_right():
    x = player.xcor()
    new_x = x + movementStepP
    if new_x > 380:
        new_x = 380
    player.setx(new_x)

def distancepyth(x1, x2, y1, y2):
    pyth = math.sqrt((x1 - x2) ** 2) + (y1 - y2 ** 2)
    return(pyth)

turtle.listen()
turtle.onkeypress(move_left, "Left")

turtle.onkeypress(move_right, "Right")

new_y = 250  # 250
while True:

    x = enemy.xcor()
    y = enemy.ycor()
    new_x = x + movementStepE
    if new_x > 380:
        movementStepE = movementStepE * -1
        new_y = y + movementStepEY
        new_x = 380
    elif new_x < -380:
        movementStepE = movementStepE * -1
        new_y = y + movementStepEY
        new_x = -380
    enemy.setposition(new_x, new_y)

turtle.done()

print("-------PROGRAM TERMINATED INTENTIONALLY-------")

and these are the errors:
Traceback (most recent call last):
  File "C:/Users/Noname Antilabelson/PycharmProjects/Space Invaders Game/Code/Space Invaders.py", line 97, in <module>
    enemy.setposition(new_x, new_y)
  File "C:\Users\Noname Antilabelson\AppData\Local\Programs\Python\Python37\lib\turtle.py", line 1776, in goto
    self._goto(Vec2D(x, y))
  File "C:\Users\Noname Antilabelson\AppData\Local\Programs\Python\Python37\lib\turtle.py", line 3158, in _goto
    screen._pointlist(self.currentLineItem),
  File "C:\Users\Noname Antilabelson\AppData\Local\Programs\Python\Python37\lib\turtle.py", line 755, in _pointlist
    cl = self.cv.coords(item)
  File "<string>", line 1, in coords
  File "C:\Users\Noname Antilabelson\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 2469, in coords
    self.tk.call((self._w, 'coords') + args))]
_tkinter.TclError: invalid command name ".!canvas"

Sorry if I've done anything stupid, your help would be greatly appreciated!
Regards
 - Jacob Sutton

A: As you noted in your comment, the while True: is your problem as it has no place in an event driven environment like turtle.  Closing a window is an event that's firing asynchronous to your main loop.  To make it synchronous, we can use an ontimer() event.  I've made that change to your code below as well as thrown in other turtle idioms and code cleanup:
from turtle import Screen, Turtle

print("------------Space Invaders - Python------------")
print("-------------GAME NOT YET COMPLETED------------")
print("This console is simply a status readout.")

def move_left():
    new_x = player.xcor() - movementStepP

    if new_x < -380:
        new_x = -380

    player.setx(new_x)

def move_right():
    new_x = player.xcor() + movementStepP

    if new_x > 380:
        new_x = 380

    player.setx(new_x)

def move_enemy():
    global new_y, movementStepE

    new_x = enemy.xcor() + movementStepE

    if new_x > 380:
        movementStepE *= -1
        new_y += movementStepEY
        new_x = 380
    elif new_x < -380:
        movementStepE *= -1
        new_y += movementStepEY
        new_x = -380

    enemy.setposition(new_x, new_y)

    screen.ontimer(move_enemy, 50)

movementStepE = 2
movementStepEY = -15
movementStepP = 5

screen = Screen()
screen.bgcolor("black")
screen.title("Space Invaders")

borderPen = Turtle(visible=False)
borderPen.speed("fastest")
borderPen.color("white")
borderPen.pensize(3)

borderPen.penup()
borderPen.setposition(-400, -400)
borderPen.pendown()

for _ in range(4):
    borderPen.forward(800)
    borderPen.left(90)

player = Turtle("triangle")
player.speed("fastest")
player.setheading(90)
player.color("blue")
player.penup()
player.setposition(0, -350)

enemy = Turtle("circle")
enemy.speed("fastest")
enemy.color("red")
enemy.penup()
enemy.setposition(-300, 250)

screen.onkeypress(move_left, "Left")
screen.onkeypress(move_right, "Right")
screen.listen()

new_y = 250

move_enemy()

screen.mainloop()

print("-------PROGRAM TERMINATED INTENTIONALLY-------")

With this change, the console shows:
> python3 test.py
------------Space Invaders - Python------------
-------------GAME NOT YET COMPLETED------------
This console is simply a status readout.
-------PROGRAM TERMINATED INTENTIONALLY-------
>

Even when you close the window while the enemy is in motion.


text:
Q: Image getting currupt when uploading by ftp in php I am working on a self taught local project and trying to upload a file to a server.
but when I upload the image file it gets corrupted.
this is my upload.php
<?php
$ds          = DIRECTORY_SEPARATOR;  //1

$storeFolder = 'uploads';   //2

if (!empty($_FILES)) {

$tempFile = $_FILES['file']['tmp_name'];          //3

$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;  //4

$targetFile =  $targetPath. $_FILES['file']['name'];  //5

move_uploaded_file($tempFile,$targetFile); //6

$ftp_server="myServer";
$ftp_user_name="userName";
$ftp_user_pass="Password";

$file = $targetFile;//tobe uploaded
$remote_file = $_FILES['file']['name'];

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
echo "successfully uploaded $file\n";
exit;
} else {
echo "There was a problem while uploading $file\n";
exit;
}
// close the connection
ftp_close($conn_id);

}
?>

It currently uploads to the local folder Uploads also to the server but corruptted any help on this will be great.

A: Have you tried using FTP Binary? an image is a binary file not an ASCII file.


text:
Q: fpdf size of text before print Hello I'm using the FPDF and I need help.
I need to print news at the bottom of an invoice, the problem is, I need to know first the size of the news (text) (because people can choose which news will apear in the invoice) and then put the news onto the invoice, but close to the bottom/footer...
My idea is to get the size of the text and save in $theSizeOfNew, then use:
//move pointer to the bottom of the page
$this->SetY(-$theSizeOfNew);

and then print the news.
How can I get the size of the news before print?

A: I'm not sure what you mean by "a new".
As far as I can understand, your problem is to calculate the size of the string which has to go to the bottom of the page. Right?
There's a method GetStringWidth(string s) which gives you the width of the String. This can help you to calculate, if it will be wider than the width of the page and you can find out, how many lines the string will have to take and how often you have to subtract the line height from the y value (bottom of page).
Finally, use MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]]) to add the string.
The manual pages on http://www.fpdf.org/ will give you more information about the methods.
P.S.: I think, the tags "get" and "news" are misleading.


text:
Q: Docker Add command doesn't work in nested destination directory I'm trying to build a simple image that includes a file (jdbc driver for Teamcity) in the image that I will then upload.  When I set the destination to /data/ or /data/teamcity_server/ it works but, if I include the full path of where the file needs to be, it doesn't.  I'm stumped.
Dockerfile:
FROM jetbrains/teamcity-server
ADD  https://jdbc.postgresql.org/download/postgresql-9.4.1212.jar /data/teamcity_server/datadir/lib/jdbc/

I tried the copy command using a file on disk in the context of the folder i'm building from with the same result.  Surely it's something simple I've missed, but i'm about frustrated at this point.

A: What about?
FROM jetbrains/teamcity-server
RUN cd /data/teamcity_server/datadir/lib/jdbc/ \
   && wget https://jdbc.postgresql.org/download/postgresql-9.4.1212.jar


text:
Q: Have I made a mistake on the master and a branch? I'm a novice on git/github and I suspect I might have made a mistake with a branch without realising it until now. A few months ago I managed to get everything up and running with git and everything still seems to work fine.
Now, for the first time I want to create a branche and when reading the docs, I noticed that my config might already have a branche that I never intended to create. I think that I only need a master branche right now and then for the new feature I want to test I will create a branche.
Could someone tell me if I'm currently working correctly with just a Master or do I also have a branche without knowing it?
When I run: git status
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working directory clean

When I run: git branch -r
  origin/master
  origin/—set-upstream-to=origin/master

When I run: git remote -v
origin  git@github.com:TheGabeMan/NestReporter.git (fetch)
origin  git@github.com:TheGabeMan/NestReporter.git (push)

When I run: git branch
* master
  —set-upstream-to=origin/master

So I'm wondering if "--set-upstream-to master origin/master" is an incorrect parameter I used which accidentaly converted to a name or is it the correct naming for the remote master?

A: Yes it looks like you have inadvertently create both a local and remote branch named "—set-upstream-to=origin/master".
To delete that branch locally, you should be able to run git branch -d "—set-upstream-to=origin/master"
To delete the remote branch, as long as you are using a relatively recent version of git, the most straightforward thing to do is git push origin --delete "—set-upstream-to=origin/master".

A: SOLVED: Tried a few more deletes and eventually solved it by running git fetch -p.
When I now run git branch -a, the result is:
* master
  remotes/origin/master

Looks good to me now :-)


text:
Q: Erro ao baixar branch no git Estava trabalhando numa branch na minha máquina pessoal, e quando fui baixá-la na máquina da empresa, usando o power shell do windows, recebi a seguinte mensagem:
PS projeto> git checkout -t origin/minha_branch
fatal: Cannot update paths and switch to branch 'minha_branch' at the same time.
Did you intend to checkout 'origin/minha_branch' which can not be resolved as commit?

A: Quando você deu clone em um projeto e está trocando de branch, você pode só utilizar git checkout <branch> sem precisar do -t, porque o git vai automaticamente buscar as referências e gerenciar o tracking.
Se isso continuar acontecendo, veja se seus remotes estão corretos com o git remote -v e tente utilizar o git fetch <seuRemote> e git remote update <seuremote> para atualizar as referências, depois use o mesmo comando novamente.
https://stackoverflow.com/questions/945654/git-checkout-updating-paths-is-incompatible-with-switching-branches
http://dianaarnos.com/pt/git-resolvendo-erro-cannot-update-paths/


text:
Q: Are cache & buffers subject to the overcommit_ratio? While generally I would consider ending up in swap a failure, I do want my systems to degrade gracefully. On the boxes doing heavy IO, I want to preserve a reasonable amount of memory for buffers and cache. Several of these don't get on well with the heuristic overcommit limit (due to switching between user demand and batch processing) so I'm using a fixed ratio for the overcommit.
Is the memory used for buffers and cache included when calculating the memory usage relative to the overcommit ratio? Or should I reduce the ratio to preserve memory for these?


text:
Q: RestFul webService and Database Transactions Lately i'm struggling with Rest architecture :p and i usualy raise a lot of problems with it.
Let's say that i have a resource named "user", and that user can have a list of cars.
Im trying to insert that user and his list of cars in the database at once. I know i have to do this with the POST HTTP verb. But how would i achieve this? Should i send only one URL with the user identification and the list of cars somehow encoded or should i use the "user" resource to insert the user, and then for each car, call a POST URL in a resource named "car"?
The second approach has a problem. This process must be implemented with a Database Transaction. If something goes wrong when inserting a car, i want the user to not be regitered in the database.
I know restFul architectures must be stateless, so how can i implement such a transaction using the database functionalities? I know i can implement myself some kind of transaction, but i wanted it to be more automaticaly.
Thanks in advance.

A: There are a number of ways you can do it depending on the languages you're using in the front and backend and how you plan to send this data. I would solve the problem like so, assuming you're using PHP and MySQL:

*

*Get the data ready, so something like user=123&cars[]=1&cars[]=2&cars[]=3 (I'm using the var cars[] as this will send an array to PHP and you can achieve this by naming your input fields as cars[])

*Post this to your backend

*Your backend will then process the user and add them to the database if they're not there.

*I would then have a table that illustrated the relationship between the user and the cars, something along the lines of:
CREATE TABLE box_to_category (
  user_id int(11) NOT NULL,
  car_id int(11) NOT NULL
);

*In this table I'd clear all cars associated with that user and then add the new cars as POSTed to the backend (the user_id will be associated to a user in a users table and the car_id will be associated to a car in the cars table)
It's a simple set up.


text:
Q: php - feof error The file that I'm trying to read is a pgp-encrypted file.  This is part of the process to decrypt it and I'm actually attempting to read the contents into a string so that I can then decrypt it. I'm not sure if that's the core problem here or not, but I'm getting an error:
Warning: feof(): supplied argument is not a valid stream resource

Here's the file code:
if($handle = opendir($dir)) {
  while( false !== ($file = readdir($handle))) {
    if($file != "." && $file != "..") {
      $fhandle = fopen($file, "r");
      $encrypted = '';
      $filename = explode('.',$file);
      while(!feof($fhandle)) {
        $encrypted .= fread($fhandle, filesize($file));
      }
      fclose($fhandle);
      $decrypted = $filename[0].'.txt';
      shell_exec("echo $passphrase | $gpg --passphrase-fd 0 -o $decrypted -d $encrypted");
    }
  }
}

A: Learn to debug your code.
supplied argument is not a valid stream resource means passed variable contains unexpected value. So, we can make a logical conclusion, that a function returning this variable had fail.
So. we have to check fopen($file, "r"); what makes it fail? may be we can check if a file exists? And so on.
This is called debugging and you cannot program without it.
Though it seems very strange.
Because fopen should throw an error as well.

A: You should check the fopen call to make sure you're file has actually been opened. Check it's return value.
As for fixing it you're working directory is likely different than $dir. You probably need
fopen("$dir/$file","r");

unless you change to the directory first.
edit clarified that the code sample was a possible solution to the problem, not code to check the return value.

A: You need to check your return values.  The error indicates that $fhandle doesn't contain a valid file handle - it probably contains false, which fopen returns on failure.
See http://ca.php.net/manual/en/function.fopen.php


text:
Q: Confused About Meteor this.next() Error onBeforeAction I have the following code for a Router map:
this.route('confirmTag', {
    path: '/confirm-tag',
    template: 'confirmTag',
    controller: 'SignUpController',
    onBeforeAction: function () {
        if (Meteor.user()) {
            if (typeof user.profile.tag === 'undefined') {
                Router.go('confirm');
            } else {
                Router.go('checkEmail');
            }
            this.next();
        } else {
            Router.go('signUp');
        }
        this.next();
    }
});

Yet, I keep getting this error in console:
Exception in callback of async function:
.onBeforeAction@http://localhost:3000/lib/router.js?783dc96a24a92cfd09fbf0ca371d762661a830bb:87:9

Line 87 in the example code is:
if (typeof user.profile.tag === 'undefined') {

What or how should "this.next();" be placed in the above code?
Thanks in advance.

A: I don't see user defined anywhere.  What about ...
this.route('confirmTag', {
    path: '/confirm-tag',
    template: 'confirmTag',
    controller: 'SignUpController',
    onBeforeAction: function () {
        if (Meteor.user()) {
            var user = Meteor.user();
            if (typeof user.profile.tag === 'undefined') {
                Router.go('confirm');
            } else {
                Router.go('checkEmail');
            }
            this.next();
        } else {
            Router.go('signUp');
        }
        this.next();
    }
});


text:
Q: Log4Net exception while writing exception to MySQL database When logging an exception, it is correctly shown in the command line. However, it does not write to the database. The other parameters are logged correctly.
In my app.config, the exception is configured as follows:
<commandText value="INSERT INTO logs (time, log_level, logger, message, exception, thread) VALUES (?time, ?log_level, ?logger, ?message, ?exception, ?thread)" />

Parameter:
<parameter>
    <parameterName value="exception" />
    <dbType value="String" />
    <size value="2000" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%exception" />
    </layout>
</parameter>

I am testing with:
try
{
    throw new DivideByZeroException();
}
catch (Exception e)
{
    log.Error("", e);
}

I enabled Log4Net debugging and got the following output:
log4net: Hierarchy Threshold []
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
log4net:ERROR [CustomAdoNetAppender] ErrorCode: GenericFailure. Exception while writing to database
12:25:37,902 [Game.Program] {exceptions} () ERROR:  System.DivideByZeroException: Attempted to divide by zero.
   at Game.Program.Init() in --:line 98

log4net:ERROR [CustomAdoNetAppender] ErrorCode: GenericFailure. Exception while writing to database
System.FormatException: Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at System.String.System.IConvertible.ToInt32(IFormatProvider provider)
   at System.Convert.ToInt32(Object value)
   at MySql.Data.Types.MySqlInt32.MySql.Data.Types.IMySqlValue.WriteValue(MySqlPacket packet, Boolean binary, Object val, Int32 length)
   at MySql.Data.MySqlClient.MySqlParameter.Serialize(MySqlPacket packet, Boolean binary, MySqlConnectionStringBuilder settings)
   at MySql.Data.MySqlClient.Statement.SerialiSystem.FormatException: Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at System.String.System.IConvertible.ToInt32(IFormatProvider provider)
   at System.Convert.ToInt32(Object value)
   at MySql.Data.Types.MySqlInt32.MySql.Data.Types.IMySqlValue.WriteValue(MySqlPacket packet, Boolean binary, Object val, Int32 length)
   at MySql.Data.MySqlClient.MySqlParameter.Serialize(MySqlPacket packet, Boolean binary, MySqlConnectionStringBuilder settings)
   at MySql.Data.MySqlClient.Statement.SerializeParameter(MySqlParameterCollection parameters, MySqlPacket packet, String parmName, Int32 parameterIndex)
   at MySql.Data.MySqlClient.Statement.InternalBindParameters(String sql, MySqlParameterCollection parameters, MySqlPacket packet)
   at MySql.Data.MySqlClient.Statement.BindParameters()
   at MySql.Data.MySqlClient.Statement.Execute()
   at MySql.Data.MySqlClient.PreparableStatement.Execute()
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
   at log4net.Appender.AdoNetAppender.SendBuffer(IDbTransaction dbTran, LoggingEvent[] events)
   at log4net.Appender.AdoNetAppender.SendBuffer(LoggingEvent[] events)
zeParameter(MySqlParameterCollection parameters, MySqlPacket packet, String parmName, Int32 parameterIndex)
   at MySql.Data.MySqlClient.Statement.InternalBindParameters(String sql, MySqlParameterCollection parameters, MySqlPacket packet)
   at MySql.Data.MySqlClient.Statement.BindParameters()
   at MySql.Data.MySqlClient.Statement.Execute()
   at MySql.Data.MySqlClient.PreparableStatement.Execute()
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
   at log4net.Appender.AdoNetAppender.SendBuffer(IDbTransaction dbTran, LoggingEvent[] events)
   at log4net.Appender.AdoNetAppender.SendBuffer(LoggingEvent[] events)

A: I found the error.
Apparently, I added some global variables which were not initialized yet when calling my test exception function. I initialized these variables to empty strings and zeroes and it worked.


text:
Q: how to specify open id realm in openid4java 0.9.5 my url @ development : http://192.168.0.1:8888/com.company.MyEntryPoint/MyEntrypoint.html
my url @ live env : http://www.example.com/com.company.MyEntryPoint/MyEntrypoint.html
I need users to authenticate using open id,
this is how i want my realm to be:
*.company.MyEntryPoint
I wrote a simple code to specify realm:
AuthRequest authReq =
    manager.authenticate(
        discovered,
        returnToUrl,
        "*.company.MyEntryPoint"
    );

it does not work.
Exception:
org.openid4java.message.MessageException: 0x301: Realm verification failed (2) for: *.company.MyEntryPoint
    at org.openid4java.message.AuthRequest.validate(AuthRequest.java:354)
    at org.openid4java.message.AuthRequest.createAuthRequest(AuthRequest.java:101)
    at org.openid4java.consumer.ConsumerManager.authenticate(ConsumerManager.java:1073)

Of all the combinations I tried, curiously, the following worked:
AuthRequest authReq =
    manager.authenticate(
        discovered,
        returnToUrl,
        "http://localhost:8888/com.capgent.MyEntryPoint"
    );

This does not solves my issue but rather complicates it :)
According to google and open id spec it should have worked
complete code snippet:
List discoveries = manager.discover(clientUrl);
DiscoveryInformation discovered = manager.associate(discoveries);
AuthRequest authReq = manager.authenticate(discovered, returnToUrl,"*.company.MyEntryPoint");
FetchRequest fetch = FetchRequest.createFetchRequest();
fetch.addAttribute("email", "http://schema.openid.net/contact/email", true);
fetch.addAttribute("country", "http://axschema.org/contact/country/home", true);
fetch.addAttribute("firstname", "http://axschema.org/namePerson/first", true);
fetch.addAttribute("lastname", "http://axschema.org/namePerson/last", true);
fetch.addAttribute("language", "http://axschema.org/pref/language", true);
authReq.addExtension(fetch);
String returnStr;
if (!discovered.isVersion2())
{
    returnStr = authReq.getDestinationUrl(true);
}
else
{
    returnStr = authReq.getDestinationUrl(false);
}

What am I doing wrong over here ?

A: returnStr = authReq.getDestinationUrl(false); => returnStr = authReq.getDestinationUrl(true);


text:
Q: I called a Function recursively using shellscript,but the function doesnt accept the arguments while calling function recusively,infinite loop runs I am trying to print the sub-file and sub directories of a Specific file. The case is, I will be giving the location of the root-folder directly.First it should print the files and directories of the root-folder,in-case of files , it should only print the name of the file and return  .In-case of folders, it should print the folder name and traverse through that sub- folder and print the files and folders present in it . So the case is, if it is file then print the name of file and leave else if it is a folder present ,recursively traverse through the folder and print the contents inside and if you find sub-folder in this folder, again recursively traverse it till you find no folder present. I need to execute in shell-script language
I had writen the sample code for this in java. This is the code logic. I am trying the same logic in shellscript but whenever I call the function recursively,it runs a infinite loop in shell script
Java code :
 import java.io.File;
 import java.nio.file.Files;
 public class Recursion
 {
   public static void fileRecursive(File root)
   {
     System.out.println(root.getName());
     if(root.isFile())
     {
      return;
     }
     else
     {
      File[] files = root.listFiles();
      for(File file : files)
      {
       fileRecursive(file);
      }
     }
   }
 public static void main(String args[])
 {
  File directoryPath = new File("/home/keshav/Main");
  System.out.println("Root Folder : "+directoryPath.getName());
  fileRecursive(directoryPath);
}

}
 Shell-Script Code:

 FileTraverse()
 {
   path=$dirname
   if [ -f "$path" ];
    then
       return;
   else
   for dir in `ls $dirname`;
    do
    FileTraverse $dir
    done
   fi
  }

 echo "Enter Root directory name"
 read dirname
 FileTraverse $dirname

A: Analyzing your program, we can see:

*

*You assign a value to the variable dirname only once (outside the function in the read statement), but never assign a new value for it. Every invocation of the function (including the recorsive ones) use the same value for this variable.

*You call your function by passing a parameter, but you never actually use this parameter.
Solution: Inside the function do a
path=$1

as a first statement and in the function body, replace each occurance of dirname by path.


text:
Q: How to make sure all the replicas of a consumer read the same message in a kinesis queue I have few consumers which updates their local cache on reading a message from the kinesis queue. But this leads to inconsistency as message is only processed by only one among all the replicas and any information retrieved from other replicas gives us invalid cache.
How can i make sure i clear the cache among all the replicas when the invalidation message appears in the queue.

A: The library that you're using assigns consumers to shards, so any message that you put on the stream will only go to one consumer.
The best solution would be to send your invalidation message out-of-band, using another Kinesis stream (or alternative such as SNS). This would add  complexity to your listener, as they'd now have to listen for two sources (and you couldn't use that library for the out-of-band messages).
If you want to send in-band cache invalidation messages, then you need to write the validation message multiple times, with different partition keys, so that it goes to all shards in the stream. The way that the partition key works is that it's MD5-hashed, and that hash is used to select a shard (see PutRecord doc).
Assuming that your application can handle multiple cache invalidation messages, I think that the best way to handle this is to write multiple messages with different partition keys (no need to get fancy, just use "A", "B", "C", and so on). Keep doing this until you've written a message to every shard (getting the shard ID for each record from the response to PutRecord).
You can call ListShards with a ShardFilter of AT_LATEST to get the shard IDs of the currently active shards.


text:
Q: Grails Spring Security Redirect after Session-Timeout I have an issue with the Session Timeout. In my grails application an user logs in after a session timeout, but then gets to the last edited page. I want to prevent that and send them to a specific URL. How can I achieve this, I cant find something in the spring security documentation.
Greetings.

A: Per the docs, it looks like you might be able to use a combination of:
successHandler.defaultTargetUrl="/whatever/url/you/want"
successHandler.alwaysUseDefault=true

A: By default spring security will forward the original request after successful login. You can prevent that by adding the following to Config.groovy:
grails.plugins.springsecurity.successHandler.alwaysUseDefault = true
grails.plugins.springsecurity.successHandler.alwaysUseDefaultTargetUrl = true
grails.plugins.springsecurity.successHandler.defaultTargetUrl = '/my/default/url'

The two properties sound like they should do the same, but in my case it only works when I have them both. Perhaps you can remove one of them and get it to work...
This will alter the behavior any time you log in, not just after a timeout. If you need a more dynamic solution, I guess you have to dig into the spring security source code...


text:
Q: ASP NET Core MVC - поместить все div в один ряд Создаю ASP NET Core MVC приложение, использую Bootstrap есть три элемента div, нужно вывести все элементы в цикле в один ряд

    @foreach (var game in Model.Games)
    {
        @await Html.PartialAsync("GameSummary", game)
    }

Вот код самого вью GameSummary

    ... тут картинки, текст и тд

Вроде все 3 элемента должны быть в одном ряду, но два div в одном ряду, а третий последний элемент попадает уже во второй ряд, в чем может быть проблема?


text:
Q: Receiving JSON from MVC Controller I have a ng-table in a jsp view that sends to my server the selected params  (filtering, sorting, page and pagesize) for every 'getData()' ajax request:
ngTableParams({
    page: 1,            // show first page
    count: 10,          // count per page
    filter: {
        name: 'Mike',       // initial filter
        age: '18'
    },
    sorting: {
        name: 'asc'     // initial sorting
    }
}

I want to bind this parameters into java objects in the Spring MVC Controller in order to build dynamic queries in the server.
1: Reading other questions about the REST method for this proposes, I think that I should  use: GET better than POST
2: The ngTableParams javascript object for the ng-table has a method 'url' used in their Ajax examples:
ngTableparams.url = Object {page: "1", count: "10", filter[name]: "Mike", filter[age]: "24", sorting[name]: "asc"}

But i'd like to receive all the filter params in just one Array, ¿How can I parse this JSON requestParams easily?.
Controller:
    @RequestMapping(value = "/search", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> search(@RequestParam(required=true) List<String> filter,
                                @RequestParam int page,
                                Locale locale) {

    return search(filter, page, locale, null);
}

Thanks!

A: im not sure if i understand you correctly.
But to send a json object from your controller, to your angular you can just do :
public ActionResult(int paramId, int something) {
 return Json(search(filter, page, locale, null), JsonRequestBehavior.AllowGet);
}


text:
Q: CardView showing white centered layout I have used card view as a row item in my recycler view and every cardview has different background color.
I've done it successfully until i add corner radius in my cardview. Now it is displaying some white layout in the middle.
Here is the code for my cardView.
    <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_margin="5dp"
    android:id="@+id/cvNB"
    app:cardCornerRadius="10dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_margin="10dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:id="@+id/txtNBHead"
                android:layout_weight="0.9"
                android:textSize="24sp"
                android:fontFamily="@font/raleway_semibold"
                android:textColor="@color/colorPrimary"/>
            <ImageView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:id="@+id/NBOptions"
                android:src="@drawable/ic_menu_icon_white_24dp"
                android:layout_weight="0.1"/>
        </LinearLayout>
        <TextView
            android:id="@+id/txtNBStory1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="@font/raleway_thin"
            android:textSize="18sp"
            android:textColor="@color/colorPrimary"
            android:layout_margin="2dp"/>
        <TextView
            android:id="@+id/txtNBStory2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="@font/raleway_thin"
            android:textSize="18sp"
            android:textColor="@color/colorPrimary"
            android:layout_margin="2dp"/>
        <TextView
            android:id="@+id/txtNBStory3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="@font/raleway_thin"
            android:textSize="18sp"
            android:textColor="@color/colorPrimary"
            android:layout_margin="2dp"/>
    </LinearLayout>
</androidx.cardview.widget.CardView>

I am using it in recycler view with different background colors shown in below code
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
        holder.cvNB.getBackground().setAlpha(0);
    } else {
        holder.cvNB.setCardBackgroundColor(ContextCompat.getColor(context, colors[index]));
    }

here is what i am getting
Cardview displaying white section
I am really frustrated please help me out
Here is the code for recycler view layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/listMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:scrollbars="vertical"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="15dp"/>
    </ScrollView>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fabAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:src="@drawable/icon_add"
        app:backgroundTint="@color/colorProfileText"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<com.airbnb.lottie.LottieAnimationView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/listNBAnim"
    app:lottie_fileName="nb_loading_anim.json"
    app:lottie_loop="true"
    android:visibility="gone"
    app:lottie_autoPlay="true"/>
</RelativeLayout>


text:
Q: Archivos CSS sin Minificar en NUXT tengo una web realiazda con NUXT (framework de VUE) y al compilarla no comprime los archivos CSS dandome un codigo HTML muy largo.
https://www.tiroconarco.link/
Los archivos los genero con un yarn generate supongo que debo tener que poner algo en los archivos de configuración para que comprima los CSS.
¿Me podeis ayudar?
Gracias

A: Añadiendo este código en el fichero de configuración nuxt.config.js lo he podido solucionar
// nuxt.config.js

export default {
  build: {
    extractCSS: true
  }
}


text:
Q: how to implement image on wxpython? I want to use matplotlib's imread/imshow feature on wxpython.  What i want is not only image display but also plotting data on image. Is that possible on wxpython using WXAgg matplotlib?
I googled but couldn't find any example of it. Thanks  in advance.


text:
Q: Swift UITableView scrollToRow or setContentOffset doesn't scroll to appropriate position I have tried both
let rect = tableView.rectForRow(at: indexPath)
tableView.setContentOffset(CGPoint(x: 0, y: rect.origin.y+self.additionalContentOffset), animated: true)

and
tableView.scrollToRow(at: indexPath, at: scrollPosition, animated: true)

And in some cases it works ok in others it is a little jumpy and ends on a wrong position/row in table view.
What is the reason that scrollView/tableView is not scrolled to correctly?


text:
Q: Separate string into different strings at space C++ I'm taking in string inputs and I need to read in multiple words from one line and push them into a vector. I can't for the life of me figure out how to split the string whenever there's a space character. I know I need to use the getline() function, but I feel like I've tried everything and I'm stuck.
Here's my code so far. I'm aware that the if/else statement are both doing the same thing.
int main(){
    vector<string> vec;
    string str = "";
    string t = "";
    int i = 0;

    while(getline(cin, str){
        if(str != "STOP"){
            if(str[i] == ' '){
                vec.push_back(str);
            }else{
                vec.push_back(str);
            }
        }else{
            cout << vec.size() << endl;
        }
        i += 1;
    }
}

I can't really use any fancy code, just the basic functions

A: You can use getline() to take the input and then use stringstream for splitting the strings.  Like:
#include <sstream>
#include <vector>
#include <iostream>
using namespace std;

int main(){
    string arr;
    getline(cin, arr);

    stringstream ss(arr);
    string word;

    vector<string> v;

    while(ss >> word){
       // your desired strings are in `word` one by one, you can store these strings in a vector
       v.push_back(word);
    }
}

for continuously taking input and processing do this :
#include <sstream>
#include <vector>
#include <iostream>
using namespace std;

int main(){
    string arr;

    while(getline(cin, arr)){

        stringstream ss(arr);
        string word;

        vector<string> v;

        while(ss >> word){
           // your desired strings are in `word` one by one, you can store these strings in a vector
           //v.push_back(word);
           cout << word << " ";
        }
        cout << "\n";
    }
}


text:
Q: SOAP Client Error: "Error Fetching Http Headers" I am trying to use a SOAP Client-Server in my computer and it doesn't look like it is going to work, I am getting this error Error Fetching Http Headers when I try to run my SOAP Client.
I have been looking and the solution that I have encountred is to increase the default_socket_timeout from 60 to 120 seconds and it doesn't work for me, also I have seen another solution that is putting the vhost in my apache KeepAlive Off and that didn't work.
The WSDL is working fine because I try to use it in another computer and it work.
I am running PHP Version 5.3.5-1ubuntu7.4 in Linux Mint using Zend Framework, I hope some of you can help me fix this thank you.

A: I'm sorry but I don't know what you are using to set up your SOAP service.....
If you can give more information about your SOAP service (poss Zend_Soap given the Zend Framework tag) etc that would be great.
Also, as a quick alternative, you say you've looked at the WSDL on another computer, perhaps try the application in an alternative environment to ensure it's not an environment issue.
May be a simple issue with your client-server code.
UPDATE: Ok so I realised the example I mentioned yesterday wasn't fully implemented so I've hacked something together quickly that you can try to see if it works in your environment.
The code is a mix of something I found here (an example of Zend_Soap_Server) and something from another SO question here (an example of a basic SOAP service test).
I've tested it at my end using ZF 1.11 and the example I'm outlining uses the default Application path you get with a new ZF project (e.g models are in directory application/models so the model shown is headed up Application_Model_Classname).
If it works, you can tweak accordingly....if it doesn't work we can try something else.
Start by creating a new SOAP controller and set the class up like this:
<?php
class SoapController extends Zend_Controller_Action
{

    public function init()
    {
        ini_set("soap.wsdl_cache_enabled", "0");     //disable WSDL caching
        $this->_helper->layout()->disableLayout();   //disable the layout
        $this->_helper->viewRenderer->setNoRender(); //disable the view
    }

    public function indexAction ()
    {
        if (isset($_GET['wsdl'])) {
            //return the WSDL
            $this->handleWSDL();
        } else {
            //handle SOAP request
            $this->handleSOAP();
        }
    }

    private function handleWSDL ()
    {
        $strategy = new Zend_Soap_Wsdl_Strategy_AnyType();
        $autodiscover = new Zend_Soap_AutoDiscover();
        $autodiscover->setComplexTypeStrategy($strategy);
        $autodiscover->setClass('Application_Model_SoapService');
        $autodiscover->handle();
    }

    private function handleSOAP ()
    {
        $server = new Zend_Soap_Server(null,
        array('uri' => "http://YOURDOMAIN/soap?wsdl"));
        $server->setClass("Application_Model_SoapService");
        $server->handle();
    }

    public function testAction()
    {
        $client = new Zend_Soap_Client("http://YOURDOMAIN/soap?wsdl");
        try {
            echo $client->testMethod('test');
        } catch (Exception $e) {
            echo $e;
        }
    }

}

In the class above, the WSDL is automatically generated using Zend_Soap_Autodiscover with a SoapService.php file at application/models/SoapService.php used as the template.  Note the DocBock comments above each method in your target class are integral to this process.
Next create the SoapService.php file in the default models folder:
<?php
class Application_Model_SoapService
{
    /**
    * testMethod
    *
    * @param string $string
    * @return string $testSuccess
    */
    public function testMethod(string $string)
    {
        $testSuccess = 'Test successful, the message was: ' . $string;
        return $testSuccess;
    }

}

If all is working as it should be you can visit:
http://YOURDOMAIN/soap?wsdl

to see the WSDL and visit:
http://YOURDOMAIN/soap/test

to get a success message with the string you specified in the client request within the testAction() code in the SoapController class as part of the message.
Let me know if it's working or not and we can go from there.
I'll be able to have another look on Monday.


text:
Q: Firebase : How many subscribers to a topic? Is it possible to know how many Instance ID tokens have been subscribed to a topic with the Firebase API?

A: Currently no, you have to keep track of what topics an IID is subscribed to yourself.

A: Best idea is to consider implementing a simple counter/s in Firebase Realtime Database from your application whenever a user subscribes/unsubscribed from a topic you define. You can then query the variable/s however you wish.


text:
Q: Why erased code (OnClick event) is still running? This little html code (my first html) ask an integer between 1 and 20 and makes a multiplication table. The multiTable is put in an aspx.cs file together. I got a plus task to change mainheader color using javascriptcode (written in script area) by OnCLientClick event. To try whether the coloring javascript function works I temporary deleted OnCLick event connected to Page_Load event. As you can see in the code asp:Button (ID=ButtonCreateMultiplicationTable) hasn't got OnClick event. But it is still functioning. Examin the input and if it is correct makes the table. How it is possible? The Code is not exist. I used: Rebuild Solution, Clean Solution, Restarted VisualStudio, Disabled cache in Chrome Developer Tools. Thank you for any help.

<%= (DateTime.Now.Date).ToString("yyyy/MM/dd") + " " + HungarianWeekName((DateTime.Now.DayOfWeek).ToString()).ToString() %>

Szorzótábla

    &nbsp

Adjon meg egy számot 0 és 21 között

    &nbsp
        <asp:TextBox class="inputitem2" runat="server" ID="TextBox1"></asp:TextBox>
    &nbsp
        <asp:Button class="inputitem3" runat="server" Text="Készít" OnClientClick="return ChangeColor()" ID="ButtonCreateMultiplicationTable" />
    &nbsp

        <asp:Literal ID="DynamicTable" runat="server"></asp:Literal>

A: An asp:button will always perform a PostBack, whether or not there is an OnClick event.
You either need to return false from the ChangeColor function.
function ChangeColor() {
    //rest of your js code

    return false;
}

Or don't use an asp:button
<button class="inputitem3" type="button" onclick="ChangeColor()" id="ButtonCreateMultiplicationTable">
    Készít
</button>


text:
Q: python script error in docker detached mode, but executes correctly in docker attached mode I am using JayDeBeAPI and UCanAccess to extract data from MS Access .mdb files (as per this advice). My python script runs in docker debian container (FROM python:3.9-slim) and everything is OK if it runs in the "attached mode", but if I run the container in the "detached mode" and try to execute the script, I get this error:
jdbc.UcanaccessSQLException: UCAExc:::5.0.1 user lacks privilege or object not found: EXPORT in statement [SELECT * from export]"
...

How to make the script executing in the docker detached mode? What could be wrong?

A: What seemed to have fixed the problem was installing sudo in the docker image:
RUN apt-get install -y sudo

Strange, since I was executing docker exec as root already ... (?)


text:
Q: How does Blazor hijack the Browser-Back button? Blazor-Server apps use the SignalR circuit.
I can somewhat understand how there is JS that change events happening from the DOM, so instead of sending a new HTTP GET request the framework manipulates the DOM and displays the new blazor page.
But how is it even possible that the circuit is still active and working on page back button? This is a BROWSER FEATURE, not some html element, which can be changed, right? Would it not be a security issue if the browser back button behavior can be manipulated in different ways?
Not firing a new HTTP GET request on page back seems pretty hacky. Wouldn't that allow for malicious websites to do the same? Can websites access the last page visited with that??
How does the browser "know" that the last page should also use the same websocket circuit?
Is it then possible to tell the browser that it should establish a websocket on a past page, that didn't even have any before (would seem like a security risk)?
How does the back button differ from hitting "enter" in the address bar (which will always cut and establish a new circuit)?
Is the back button exactly the same as calling JS history.back() ?


text: Q: Is this function just zero? I asked a question like this a few minutes, but am about ready to strike the problem out as errata for the book. The problem defines a function $g(x)=f(x-a)g(b-x)$. The function has bound $|f|<1$, so I believe the equality, $g(x)=f(x-a)g(b-x)=g(x)=f(x-a)f(b-a-x)g(x)$ shows that $g(x)=0$. Since the author claims that this is a bump functions, positive on $(a, b)$, I think he meant $g(x)=f(x-a)f(b-x)$. Any opinions? The book is Differential Topology by Alan Pollock. Sec 1, Excersise 18 FYI.


text:
Q: iOS 9.1 beta 3-4 eating up my wifi downstream I just run into a strange issue. My iPhone 6 Plus 64GB (updated today to 9.1 beta 3) started eating my wifi downstream (not upstream) after I plugged it to my macbook for charging. I tried disabling any feature (I was aware of) that could download stuff in the background. Every app is updated on my device. There is also no indicator at the statusbar. Every app is terminated. When I unplug the device from charging and reenable the wifi connection the download process starts again.
Rebooting the device while unplugged does help but if I start charging the device it happens again.
Any suggestion what that could be, maybe I missed something here. The free space is gone from 6GB down to 3GB already.
Version: 9.1 (13B5130b)
UPDATE:
Version: 9.1 (13B136) behaves the same. I deleted almost all apps I don't use atm and searched trough every setting that could use background downloading. The device is downloading non stop (it should be 4-6GB already).

A: I would do three things to narrow down the culprit:

*

*Connect to Xcode and look at the console logs for the phone - activity might be logged

*Connect to Instruments and profile the network activity

*Connect to iTunes and make snapshots of the storage sizes (or use storage and usage on iOS) to see what bins are growing over time.

You can turn off iCloud to reduce many downloads, but it really depends on which apps you have installed, how they background data load and what data stores they are configured to pull. Since you are on the betas, you have many options to pick apart the data flow using diagnostic profiles provided by Apple and the developer tools similarly provided.


text:
Q: Error while creating aspnet.db for Form Based Authentication I want to install SharePoint 2013 FBA Pack for user password management. When I followed the instruction to prepare my system, I can not create a aspnet.db. I got the following error message:
Setup failed.
Exception:
Unable to connect to SQL Server database.

System.Web.HttpException (0x80004005): Unable to connect to SQL Server database. ---> System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) ---> System.ComponentModel.Win32Exception (0x80004005): The system cannot find the file specified
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover)
   at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
   at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
   at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString)
ClientConnectionId:00000000-0000-0000-0000-000000000000
   at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString)
   at System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install)
   at System.Web.Management.ConfirmPanel.Execute()


text:
Q: Reading data from two different array of json objects and keeping in third json array I have two arrays containing objects like the below:
json1[] = [{
    "time": "00:00:00",
    "speed": 15,
    "speedlimit": 10
}, {
    "time": "00:00:00",
    "speed": 15,
    "speedlimit": 10
}, {
    "time": "00:00:00",
    "speed": 15,
    "speedlimit": 10
}];

json2[] = [{
    "time": "00:00:00",
    "Brake": 15
}, {
    "time": "00:00:00",
    "Brake": 15
}, {
    "time": "00:00:00",
    "Brake": 15
}];

Using the above two objects I want to create a 3rd; json3[]. How can I do this?

A: Firstly, note that your variable names will cause you syntax errors as they cannot contain the [] characters.
Secondly, to achieve what you need you can simply use the concat() method:
var json3 = json1.concat(json2);

Example fiddle


text:
Q: Setting the frame of an UIView does not work I have a problem with the frame-property in iOS 7.
I wanna resize some UIViews in the viewDidLoad-method of my UIViewController, but if I do it like int screenHeight = [[UIScreen mainScreen] bounds].size.height;
[self.leftSideTableView setFrame: CGRectMake(0, 0, 320, screenHeight)];
the height is set as I want it till the end of the method, but in every other method it is as is has been before!
What's wrong with it or is it just a bug of the compiler or anything else?

A: Check to make sure that auto layout isn't activated in your storyboard file.
To turn it off, look at the inspector in interface builder. Click the icon that looks like a page all the way on the left. In the section "Interface Builder Document" uncheck "Use Auto Layout."
I find it's best to an entire view controller in IB with auto layout, or completely in code. Mixing the two can lead to weird behavior that is hard to debug.

A: One has to put view resizing into -viewDidLayoutSubviews:! (documentation)
Placing view frame changes into -viewWillAppear: or -viewDidLoad: will not work, because the views are not laying out yet!

A: *

*Check if you are using autolayout in your xib file. If you don't want to use autolayout, uncheck it in your xib file.

*Change your self.leftSideTableView frame in -viewWillAppear:.

A: There are several reasons why this might be happening. First of all, you need to make sure that your tableview isn't nil. If you're creating it programmatically, you need to be sure that you're calling alloc/init somewhere before you attempt to set the frame. If self.leftSideTableView is an IBOutlet, this can be caused by forgetting to actually link the outlet to the interface object.
Then, second and less likely, you are creating the table view programmatically and initializing it properly, but you forgot to add it as a subview of one of your on screen views.