text:
Q: C++ custom iterator over container based on items property I have a container of Employees with fields std::string name and bool is_manager. I want to iterate over container for regular and manager employees. The number of items in a container can be very large so I do not want to do a linear scan with checking is_manager property. Also the number of managers is very small i.e. 10 out of 100000, so doing a full scan over the container is ineffective. So I want to pre-cache the memory addresses of Employees with and without is_manager==true and have RegularEmployeeIterator and ManagerEmployeeIterator, I think this can be pre-cached and organized as a list/vector of pointers?
And I want to able to sort the container of Employees by name field and retain the ability to iterate over regulars and managers.
How to implement that in C++? Specifically, I have no idea how iterators are implemented in C++, how to define several of them for a single collection, based on property value, does my idea with caching the addresses works, etc.

A:
organized as a list/vector of pointers?

Whatever the problem, a list is not the data structure you need.
1. Unrealistic answer for a beginner, but you claim it's the problem you're solving

ok actually I have tens of millions entries

I mean, this is very clearly a learning exercise, and you insisting that your data is 10s of millions of entries large is... mediocrily helpful, because that's the point where if access times are important, you stop storing the composite object in one container:
std::vector<Employee> employees; //10⁷ employees

but would group the data according to the properties you're going to work on at the same time:
std::vector<bool> bossiness; //10⁷ bits – std::vector<bool> has an optimization!
std::vector<std::string> names; //10⁷ std::strings

and as a matter of fact, if you know your data doesn't change, you wouldn't even do that, because the names vector is a dereferencing nightmare that wastes a lot of memory on redundant information, if you could as well just go
std::vector<bool> bossiness; //10⁷ bits – std::vector<bool> has an optimization!
std::string all_names; // a **very** long string containing all names, one after the other
std::vector<size_t> name_begins;  // 10⁷ name beginnings; through all_names.substr(name_begins[i], name_begins[i+1]) you can access the i.th name

Now, to speed up looking for bosses, you just start by making a run-time encoded list of 64bit-regions in your bossiness vector where at least one bit is set. You could do elegant k-d trees if your problem becomes multidimensional, but at the sparsity you have, runtime encoding on machine word sizes will probably still beat the hell out of that.
But that's an optimization level you need when writing a database system or a 3D game with millions of vertices. You're learning C++. You're not writing these kinds of things, so:
2. Realistic answer that you didn't want when offered in the question

i.e. 10 out of 100000

so, let's really go with a problem size of 10⁵. I.e., a small problem.
You need to do your Employee vector, and add a bosses vector:
std::vector<Employee> employees;
std::vector<size_t> boss_indices;

Then you need to do your linear search once:
// if you know a safe and not too outlandish upper bound for the number of managers, reserve that memory once to avoid resizing the vector while filling it, as that's very expensive:
boss_indices.reserve(size_t(employees.size() * fraction_of_managers));

for(size_t idx = 0; idx < employees.size(); ++idx) {
  if(employees[idx].is_manager) {
    boss_indices.push_back(idx)
  }
}

congratulations, an easy to use vector indices. Indices into std::vector are just as good as pointers to elements (it's a simple pointer deref, both ways, and the additional offset is usually merged into the deref operation on any modern CPU I know), but survive the target vector being moved.

And I want to able to sort the container of Employees by name field and retain the ability to iterate over regulars and managers.

have a class
#include <algorithm>
struct SortableEmployee {
   const Employee* empl;
   bool operator <(const SortableEmployee& other) const {
      return std::lexicographical_compare(
          empl->name.cbegin(); empl->name.cend(),
          other.empl->name.cbegin(), other.empl->name.cend());
   }
   SortableEmployee(Employee* underlying) : empl(underlying){
   }
};

and put it in a std::set to get a sorted version that you can iterate through:
std::set<SortableEmployee> namebook;
for(const auto& individual : employees) {
    namebook.emplace(&individual);
}

You can then iterate through it linearly as well
for(const auto& sorted_empl : namebook) {
    std::cout << std::format("{}: is {}a manager\n",
        sorted_empl.empl->name,
        sorted_empl.empl->is_manager ? "" : "not ");
}


text:
Q: Is there a way to LOG RC Selenium test errors/failures into a database? Im using phpunit & phpundercontrol to run the RC Selenium on every build.

A: PHPUnit allows you to implement your own TestListener. Custom test listeners implement the abstract methods in the PHPUnit_Framework_TestListener interface. Specifically, your listener will implement:

*

*startTestSuite()

*endTestSuite()

*startTest()

*endTest()

*addError()

*addFailure()

*addSkippedTest()

*addIncompleteTest()

Once you've attached the TestListner these methods will be called each time the corresponding events occur in your test suite. These methods will be written to perform the INSERTs and UPDATEs on a test results database that you'll create.
Attaching the listener class to your suite is as easy as adding a  tag to the phpunit.xml configuration file. For example:
<phpunit>
  <testsuites>[...]</testsuites>
  <selenium>[...]</selenium>
  <listeners>
    <listener class="Database"
              file="/usr/loocal/share/pear/PHPUnit/Util/Log/Database.php">
  </listeners>
</phpunit>

That's all you need!
In fact, PHPUnit already comes with a working version of the listener I just described (PHPUnit_Util_Log_Database), as well as two different database schema definitions.
On many systems this class will live at /usr/loocal/share/pear/PHPUnit/Util/Log/Database.php, and the schemas at /usr/loocal/share/pear/PHPUnit/Util/Log/Database/MySQL.sql and /usr/loocal/share/pear/PHPUnit/Util/Log/Database/SQLite3.sql. You may have to do some tweaking depending on the DBMS you're using.

See these sections of the documentation (it wont let me post two links:
http://www.phpunit.de/manual/3.4/en/extending-phpunit.html#extending-phpunit.PHPUnit_Framework_TestListener
htp://www.phpunit.de/manual/3.4/en/api.html#api.testresult.tables.testlistener
(StackOverflow won't let me post two links, so you'll have to correct the HTTP in that second one)

A: I am working on the same problem.
Have asked a related question here a few days ago.
My attempt using Selenium IDE, Selenium RC and perl.
General strategy:
You can make newer releases of phpunit generate TAP output (options --tap, --log-tap).
(TAP is Test Anything Protocol - standardized output format)
Parse the logfile to obtain the suite metadata from the TAP parser object, insert into database using perl, e.g. "# Number of Passed": , "Failed", "Unexpectedly succeeded",

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to delete data from database that has been published to the cloud? I am generating dummy data in the database and then publishing to cloud.
As soon as it is published, I want to delete that entry from the database.
I understand that I need to send the 'mid' value in the publish method then call deleteFromDb() function. But mid is always 1, even though I return ret.mid=index. Index is the primary key retrieved from the database.
def on_publish(unused_client,unused_userdata,mid):
    print('on_publish')
    deleteFromDb(mid)

def main() :
    TableSchema="""
      create table if not exists heartbeat(
        id integer primary key autoincrement,
        Date_Time text,
        Heartbeat text
      );

      """

    while True:
        conn = sqlite3.connect(dbFile)
        print("Connected to db")
        conn.execute('pragma foreign_keys = on')
        conn.commit()
        curs = conn.cursor()

        print "Writing to db..."
        sqlite3.complete_statement(TableSchema)
        curs.executescript(TableSchema)
        conn.commit()

        rectime=strftime("%Y-%m-%d %H:%M:%S", gmtime())
        res="ON"
        curs.execute("insert into heartbeat (Date_Time, Heartbeat)
                    values (?,?)",[rectime,res])
        conn.commit()
        print "Inserted Heartbeat Data into Database."
        for row in curs.execute("select * from heartbeat"):
            index=row[0]
            continue
        conn.commit()
        encoded_row=''
        encoded_row=json.dumps(row) #Dumped in the form of str
        print encoded_row

        client = mqtt.Client(client_id=_CLIENT_ID)
        client.username_pw_set (username='unused', password=create_jwt(project_id, ssl_private_key_filepath, ssl_algorithm))
        client=mqtt.Client()

        client.on_connect = on_connect
        client.on_publish=on_publish
        client.on_message = on_message

        client.tls_set(ca_certs=root_cert_filepath)
        client.connect('mqtt.googleapis.com', 8883,60)

        client.loop_start()
        ret=client.publish(_MQTT_TOPIC,encoded_row,qos=1)
        time.sleep(0.5)
        ret.mid=index
        client.loop_stop()
        #print(ret.mid)

        curs.close()
        conn.close()

A: I am assuming you are using sqlite3 so you need to connect and execute a delete statement to delete and then commit() to make changes you saved. Try like this
import sqlite3

deleteFromDb(mid):
    con=sqlite3.connect("mydatabase.db") #your db name
    cursor=con.cursor()
    cursor.execute("DELETE FROM TABLE_NAME WHERE ID = %s" % mid)
    con.commit()
    con.close()


text:
Q: WPF: Creating image of dynamically created usercontrol I want to create the image of a dynamically created usercontrol  and show it in a window.
I am creating the usercontrol using the  Below code .
 MyViews.MyViewsUserControl myViewsCanvas = new MyViews.MyViewsUserControl(AllFoundationMyViewsViewModel,item.Id);
                        //myViewsCanvas.Height = 5;
                        //myViewsCanvas.Width = 5;
                        Size size = new Size(50, 50);
                        myViewsCanvas.Measure(size);
                        double width = myViewsCanvas.DesiredSize.Width;
                        double height = myViewsCanvas.DesiredSize.Height;
                        myViewsCanvas.Arrange(new Rect(new Point(), size));

Then i am creating the image of the myViewsCanvas and adding it to a view box of another usercontrol called _DashBoardUserControl using the below code.
 _DashBoardUserControl.Viewbox2.Child = CreateImage(myViewsCanvas);

Then i am adding the _DashBoardUserControl to a window.
UserControls.Controls.PopupWindow popup = new UserControls.Controls.PopupWindow();
        popup.PopupContent = _DashBoardUserControl;
        popup.ShowDialog();

The problem is, I can only see a portion of the Image. I guess that is because of the measure() and arrange() methods. Can anybody tell me about these methods or what size should i pass to these methods. Do i need to scale down the image? If yes how do i do that?

A: The easiest way I know of is this:
Viewbox v = new Viewbox();
v.Child = uielem;
uielem.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
v.Measure(uielem.DesiredSize);
v.Arrange(new Rect(new Point(), uielem.DesiredSize));
v.UpdateLayout();
r.Render(v);

where uielem is the element you want to render and r is the RenderTargetBitmap. (v.UpdateLayout might not be needed there, but I'm not sure anymore).


text:
Q: How can I tell which Silverlight Popup (or ChildWindow) is topmost? I am trying to hit test in Silverlight applications to find the elements under the mouse cursor.
Normally VisualTreeHelper.FindElementsInHostCoordinates works for this. If there is a Popup open I need to pass in the popup to the hit testing method. If there are multiple popups open, I need to determine the correct (topmost) popup to pass in.
Is there any reliable way to determine which Popup is topmost? I'm doing this in an assembly that may be loaded after the Popups have been opened, so I can't rely on tracking the order in which they are opened.
Thanks for any assistance.

A: It looks like the new VisualTreeHelper.GetOpenPopups call returns the open Popups in order from bottom to top (or least recently to most recently opened?). So that does what I need.
Posting this answer in case anyone else runs into the same issue.


text:
Q: Checking column for value. If true, check same row in another column and count if not blank I have a spreadsheet of employees. Column A is a list of Dept types (sales, HR, payroll, etc). Column B is the date their appraisal is completed, or blank if incomplete.
I would like a function that checks the Dept column for a particular Dept type (e.g. "Sales") and if equals "Sales" then checks the corresponding rows of the Appraisal column and counts how many dates. I would then replicate for all other Dept types. So for the "Sales" example, if there are four employees and two have an appraisal date, the result would be "2". Noting that I don't want it to count the dates in Column B relating to the other Dept types.
Column A -  Dept          .      .    .    .    -   HR -    Sales - HR -    Payroll -   Sales - Sales - Sales .
Column B -  Appraisal - 1/07/2015 - 8/07/2015 - 6/07/2015 - "Blank" -   "Blank" -   3/07/2015 - "Blank" -

A: Open the VBA Editor, then choose Module from the Insert menu. Paste the following into the resulting text field:
Function DEPTAPPCOUNT(Dept As String, Range As Range, CountRange As Range) As Integer
    Dim count As Integer
    For Each rCell In Range
        If rCell.Text = Dept Then
            If rCell.Offset(0, 1).Text <> "" Then count = count + 1
        End If
    Next
    DEPTAPPCOUNT = count
End Function

Press the Save button on the toolbar, then close the VBA Editor to return to your spreadsheet. You can now use the DEPTAPPCOUNT function just like Excel intrinsic functions. If your department column spans from A2 to A7 (and the appraisal dates are in B2 to B7 - the counted column must be immediately to the right of the department column for this function to work), enter =DEPTAPPCOUNT("Sales", A2:A7, B2:B7) to get the number of sales entries with non-blank appraisal dates. Adjust the first parameter (the Sales text) as desired to count in other departments.
If you're on Excel 2007 or newer, you'll need to save the worksheet in the XLSM (macro-enabled) format.
For those wondering why CountRange must be passed to the custom function even though it isn't used, it's needed to have Excel recalculate the count if the date column is changed. In other words, passing the extra range to the function creates a dependency in Excel's calculations.


text:
Q: How to interpret/do a correlation/regression analysis if underlying relation has to be asymptotic? I want to do a correlation/regression analysis of a dependent and an independet variable.
I've got the following problem:
I want to analyze how the number of produced goods affects the price.
At the beginning with a raising number of produced goods the price drops quite fast but then it flattens out.
From the theory of the problem I'd say that the realtion is asymptotic (see drawing).
Somehow I can't really find a way on how to do a correlation/regression analysis on asymptotic data though.
Shouldnt be this relation of variables be quite common?
Hope that someone could help me..
Thanks guys

A: One would need to do power law analysis. See the seminal paper, Power-law distributions in empirical data. There is an R package poweRlaw to help in this direction.
Edit: Nice suggestion from @whuber, due to frequency of posts in CV, exponential decay can also be used to model such data. However, intrinsically different than power laws, see discussion Difference between power law distribution and exponential decay


text:
Q: Calling some PyObject functions causes segfault - Boost python For a project, I need to interface some C++ modules in Python. To do so, I need a converter which converts a Python tuple to a cv::Size (openCV object). Here is my C++ function :
cv::Size tupleToSize(PyObject* obj)
{
    // Check if obj is a tuple :
    if (!PyTuple_CheckExact(obj))
        return cv::Size(-1,-1);

    // Element Extraction :
    PyObject* x = PyTuple_GetItem(obj,0);
    PyObject* y = PyTuple_GetItem(obj,1);

    // TODO : extract values from x and y
    // Trying to create two variables a et b that contains the values
    long a = PyLong_AsLong(x);
    long b = PyLong_AsLong(y);
    /* The first line causes a SegFault*/

    // New cv::Size with extracted values :
    cv::Size ret(a,b);
    return ret;
}

And here is the main that calls my function :
int main()
{

    // New cv:Size :
    Size s(10,20);
    // Conversion :
    PyObject* ss = SizeToTuple(s); // I have a SizeToTuple function that works fine.
    // Reconversion :
    Size sss = tupleToSize(ss); /* SEGFAULT */

    return 0;

}

So, I wonder if my PyObject x and y are not of type Long, so I decided to check their type but when I call some functions as :
PyObject_repr(x);
PyObject_str(x);

They also cause a segfault.
So, I'm pretty stuck. Do you have any suggestions ? Thanks in advance.

A: Thanks to Tanner Sansburry, I solved the problem by just adding :
Py_Initialize();

in my code.
Problem solved !


text:
Q: Turn a distances squareform to long format in python The code:
import numpy as np
import pandas as pd
from scipy.spatial.distance import pdist, squareform

ids = ['1', '2', '3']
points=[(0,0), (1,1), (3,3)]
distances = pdist(np.array(points), metric='euclidean')
print(distances)
distance_matrix = squareform(distances)
print(distance_matrix)

prints:
[1.41421356 4.24264069 2.82842712]
[[0.         1.41421356 4.24264069]
 [1.41421356 0.         2.82842712]
 [4.24264069 2.82842712 0.        ]]

as expected
I want to turn this into a long format for writing in csv, as in
id1,id2,distance
1,1,0
1,2,1.41421356
1,3,4.24264069
2,1,1.41421356
2,2,0
2,3,2.82842712

etc - how should I go about it for maximum efficiency? Using pandas is an option

A: Use DataFrame contructor with stack:
df = pd.DataFrame(distance_matrix, index=ids, columns=ids).stack().reset_index()
df.columns=['id1','id2','distance']
print (df)
  id1 id2  distance
0   1   1  0.000000
1   1   2  1.414214
2   1   3  4.242641
3   2   1  1.414214
4   2   2  0.000000
5   2   3  2.828427
6   3   1  4.242641
7   3   2  2.828427
8   3   3  0.000000

Or DataFrame contructor with numpy.repeat, numpy.tile and ravel:
df = pd.DataFrame({'id1':np.repeat(ids, len(ids)),
                   'id2':np.tile(ids, len(ids)),
                   'dist':distance_matrix.ravel()})
print (df)
  id1 id2      dist
0   1   1  0.000000
1   1   2  1.414214
2   1   3  4.242641
3   2   1  1.414214
4   2   2  0.000000
5   2   3  2.828427
6   3   1  4.242641
7   3   2  2.828427
8   3   3  0.000000

A: I would suggest using indices_merged_arr_generic_using_cp -
Helper function -
import numpy as np
import functools

# https://stackoverflow.com/a/46135435/ by @unutbu
def indices_merged_arr_generic_using_cp(arr):
    """
    Based on cartesian_product
    http://stackoverflow.com/a/11146645/190597 (senderle)
    """
    shape = arr.shape
    arrays = [np.arange(s, dtype='int') for s in shape]
    broadcastable = np.ix_(*arrays)
    broadcasted = np.broadcast_arrays(*broadcastable)
    rows, cols = functools.reduce(np.multiply, broadcasted[0].shape), len(broadcasted)+1
    out = np.empty(rows * cols, dtype=arr.dtype)
    start, end = 0, rows
    for a in broadcasted:
        out[start:end] = a.reshape(-1)
        start, end = end, end + rows
    out[start:] = arr.flatten()
    return out.reshape(cols, rows).T

Usage -
In [169]: out = indices_merged_arr_generic_using_cp(distance_matrix)

In [170]: np.savetxt('out.txt', out, fmt="%i,%i,%f")

In [171]: !cat out.txt
0,0,0.000000
0,1,1.414214
0,2,4.242641
1,0,1.414214
1,1,0.000000
1,2,2.828427
2,0,4.242641
2,1,2.828427
2,2,0.000000

To get distance_matrix we can also use Scipy's cdist : cdist(points, points). There's also eucl_dist  package  (disclaimer: I am its author) that contains various methods to compute euclidean distances that are much more efficient than SciPy's cdist, especially for large arrays.


text:
Q: Python: ConnectionError: HTTPSConnectionPool(host='api.foursquare-com', port=443) I'm having this issue while running the script:
(I'm using Spyder to build my script, but I'm trying at Jupyter Notebook and I'm getting the same error)
#STEP 3.8 - Get the URL request

LIMIT = 100

radius = 50

url = 'https://api.foursquare-com/v2/venues/explore?&client_id={}&client_secret={}&v={}&ll={},{}&radius={}&limit={}'.format(

CLIENT_ID, CLIENT_SECRET, VERSION, neighbor_lat, neighbor_long, radius, LIMIT)

#STEP 3.9 - Get request and examinate the result

results = requests.get(url).json()

print(results)

ConnectionError: HTTPSConnectionPool(host='api.foursquare-com', port=443): Max retries exceeded with url: /v2/venues/explore?&client_id=xxx&client_secret=xxx&v=20180605&ll=43.806686299999996,-79.19435340000001&radius=500&limit=100 (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

A: Try to add headers parameters in your request.get.
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'}

page = requests.get(url, headers=headers)

A: Try using the exceptions
results=" "
while results==" ":
    try:
        results = requests.get(url).json()

    except:
        time.sleep(50)
        continue

A: This is common error, after doing SSL to your VPS server, it only finds the url with https://domanName.com
in this case check you connection in you code File or .env file and
change connections from
http://domainName.com -- to -- https://domainName.com
I hope this will solve your problem
Thanks.


text:
Q: Speak Slower or Speak Slowlier? AFAIK the correct grammar for "speak slow" is "speak slowly" (slowly being an adverb). Please correct me if I am mistaken.
But in daily life I have not heard anyone saying "Speak slowlier".
I think I heard folks saying "Speak slower" but I also think it is incorrect.
Which is the best or correct form to convey the message?
Could that be the longish "Speak more slowly?"

A: Slower can either be an adjective, or an adverb.
"Speak slower" is grammatically correct. "*Slowlier" is not a word.
"*Slowlier" sounds very unnatural to a native English speaker; however, not all know that slower can also be an adverb.
Some incorrectly claim that the adverb "slower" should be avoided. However, it has been in use for about four centuries now and is well established as a real word.

A: Slow can be an adverb as well as an adjective. Not all native speakers know this, and some will tell you it's wrong to say 'Speak slower'. If you don't want to risk upsetting them, you can certainly say 'Speak more slowly'.
The Oxford English Dictionary has two citations for slowlier, including this from the seventeenth century philosopher Thomas Hobbes: 'They marched the slowlier for the rain which had fallen the same night.' It is, however, rare: I have never seen or heard it until now.

A: People confuse everyday speech with what is grammatically correct. "More slowly" you say is "acceptable" but awkward? :DDD
More slowly is a grammatically correct option, as adverbs are formed in most cases from and adj. + -ly = slow >>> slowly.
Unfortunately most people form their opinion solely based on everyday speech, which can be accepted in conversation. However, many of those things are not grammatically incorrect.
In this case yes, both slower and more slowly are correct, but by no means is more slowly awkward.
Furthermore, someone mentioned near, nearly. Do not compare them as they do not have the same meaning, just like late-lately.
P.S. I have yet to hear a native speaker use few/little in the right context. I have met so many who use less for every example, even though the noun is clearly countable.
Do not search for your answers online, opinions are just opinions and what you hear everyday may not be grammatically correct. Consult the holy Bible of English grammar books "English grammar in use" by Raymond Murphy or Oxford Advanced Learner's Dictionary, the holy Bible of English-English dictionaries, or someone who has a Master's Degree in the English language and literature.

A: I am a native English speaker and I only use "slowlier". "Slower" would be incorrect and "more slowly" would be acceptable, but awkward.

A: Slower is a comparative adverb or adjective, depending on its sentence allocation.  He talks slower than before.
Slow/slowly can be both adverbs that have two forms. Like loud loudly, near nearly.


text:
Q: Implementing IList facade, but GetEnumerator returns a count of 0 I'm a little bit new to programming in .NET, and there's a little bit of a problem that's truly confusing me.
I am trying to implement the IList<T> interface in one of my classes. I wanted to keep things simple for now, so I simply used the functionality of a declared List<T> field for the methods and added some custom data processing in between.
Most of the methods work well, and the field list gets added to as expected. However, when I try to use the class as a list (e.g. class.ForEach()), it returns a Count of 0. This is despite the internal List<T> having a count of 25.
I'm sure this is really simple, and I apologise if this question is a waste of database space, but it's something that's really holding me back. Can any of you guys help me solve it?
I'll post my current code to show what I'm trying to do:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using ClubEventsData;
using ClubEventsData.Attributes;
using ClubEventsDataHandling.System.Implementations.Conversion;
using Telerik.Sitefinity.DynamicModules.Model;

namespace ClubEventsDataHandling.System.Implementations
{
    public class DataRepository<T> : IDataRepository<T> where T : ClubEventData, new()
    {
        private readonly PropertyDictionaryBasedDynamicConverter<T> _converter;
        private readonly IDataHandler _dataHandler;
        private readonly List<T> _storageList;

        ///
        /// Initializes a new instance of the DataRepository class.
        ///
        public DataRepository()
        {
            _dataHandler = new SitefinityBasedDataHandler<T>();
            _converter = new PropertyDictionaryBasedDynamicConverter<T>();
            _storageList = new List<T>();

            // Populate the data repository.
            foreach (DynamicContent dynamicContent in _dataHandler.Get())
            {
                _storageList.Add(_converter.ConvertToModel(dynamicContent));
            }
        }

        #region Implementation of IEnumerable

        ///
        /// Returns an enumerator that iterates through the collection.
        ///
        /// <returns>
        /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
        /// </returns>
        /// <filterpriority>1</filterpriority>
        public IEnumerator<T> GetEnumerator()
        {
            return _storageList.GetEnumerator();
        }

        #endregion

        #region Implementation of ICollection<T>

        ///
        /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        ///
        /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
        public void Add(T item)
        {
            // Create the data item.
            T modelItem = CreateDataItem(item);

            // Add the item to the list.
            _storageList.Add(modelItem);
        }

        ///
        /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        ///
        /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. </exception>
        public void Clear()
        {
            throw new NotImplementedException();
        }

        ///
        /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
        ///
        /// <returns>
        /// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false.
        /// </returns>
        /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
        public bool Contains(T item)
        {
            // Determine if the database contains the item.
            return _dataHandler.Get(item.MasterContentID) != null;
        }

        ///
        /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
        ///
        /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param><param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param><exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.</exception><exception cref="T:System.ArgumentException">The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.</exception>
        public void CopyTo(T[] array, int arrayIndex)
        {
            _storageList.CopyTo(array, arrayIndex);
        }

        ///
        /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        ///
        /// <returns>
        /// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </returns>
        /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
        public bool Remove(T item)
        {
            // Determine if the master content ID has been set.
            ValidateItem(item);

            // Delete the item from the database.
            _dataHandler.Delete(item.MasterContentID);

            // Remove the item from the database.
            return _storageList.Remove(item);
        }

        ///
        /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        ///
        /// <returns>
        /// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </returns>
        public int Count { get; private set; }

        ///
        /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
        ///
        /// <returns>
        /// true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
        /// </returns>
        public bool IsReadOnly { get; private set; }

        ///
        /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
        ///
        /// <returns>
        /// true if <paramref name="itemID"/>'s item is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false.
        /// </returns>
        /// <param name="itemID">The ID of the object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
        public bool Contains(Guid itemID)
        {
            return _dataHandler.Get(itemID) != null;
        }

        ///Creates the data item in the database and returns the model version of it.
        private T CreateDataItem(T item)
        {
            // Get the properties of the item.
            Dictionary<string, object> propertyDictionary = GetItemProperties(item);

            // Create the data representation of the item.
            Guid createdItemID = _dataHandler.Create(propertyDictionary);

            // Convert a new model item from the dynamic content.
            DynamicContent dynamicContent = _dataHandler.Get(createdItemID);
            T modelItem = _converter.ConvertToModel(dynamicContent);
            return modelItem;
        }

        ///Gets the properties of the item as a dictionary that is ready to input into data handler methods.
        private static Dictionary<string, object> GetItemProperties(T item)
        {
            var propertyDictionary = new Dictionary<string, object>();

            // Filter  the properties according to the mapping attribute.
            foreach (PropertyInfo property in item.GetType().GetProperties())
            {
                // Get the mapping attribute.
                object[] customMappingAttributes = property.GetCustomAttributes(typeof (ClubEventDataMappingAttribute), true);
                var mappingAttribute = customMappingAttributes[0] as ClubEventDataMappingAttribute;

                // Apply the action, depending on the mapping attribute.
                if (mappingAttribute != null && mappingAttribute.MappingEnabled)
                {
                    string mappingValue = mappingAttribute.MappingName != null && string.IsNullOrEmpty(mappingAttribute.MappingName) ? property.Name : mappingAttribute.MappingName;
                    if (mappingValue != null)
                    {
                        propertyDictionary.Add(mappingValue, property.GetValue(item, null));
                    }
                }

                // Old code, in case didn't work.
                /*if ()
                {
                    propertyDictionary.Add(property.Name, property.GetValue(item, null));
                }*/
            }

            return propertyDictionary;
        }

        ///
        /// Performs validation operations on the item.
        ///
        private static void ValidateItem(T item)
        {
            // Check that the ID is present on the item.
            if (item.MasterContentID == Guid.Empty)
            {
                throw new ContentIDNotSetException("The master content ID was not set for this exception.");
            }
        }

        #endregion

        #region Implementation of IList<T>

        ///
        /// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1"/>.
        ///
        /// <returns>
        /// The index of <paramref name="item"/> if found in the list; otherwise, -1.
        /// </returns>
        /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1"/>.</param>
        public int IndexOf(T item)
        {
            return _storageList.IndexOf(item);
        }

        ///
        /// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1"/> at the specified index.
        ///
        /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param><param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1"/>.</param><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception>
        public void Insert(int index, T item)
        {
            // Create a new data item based off the properties of this one.
            T modelItem = CreateDataItem(item);

            // Insert the model item into the list.
            _storageList.Insert(index, modelItem);
        }

        ///
        /// Removes the <see cref="T:System.Collections.Generic.IList`1"/> item at the specified index.
        ///
        /// <param name="index">The zero-based index of the item to remove.</param><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception>
        public void RemoveAt(int index)
        {
            // Get the item at the index.
            T item = this[index];

            // Validate the item ID.
            ValidateItem(item);

            // Delete the item from the database.
            _dataHandler.Delete(item.MasterContentID);

            // Remove the item from the list.
            _storageList.RemoveAt(index);
        }

        ///
        /// Gets or sets the element at the specified index.
        ///
        /// <returns>
        /// The element at the specified index.
        /// </returns>
        /// <param name="index">The zero-based index of the element to get or set.</param><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception><exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception>
        public T this[int index]
        {
            get { return _storageList[index]; }
            set
            {
                // Validate the specified content ID.
                ValidateItem(value);

                // Update the database instance with the item properties.
                _dataHandler.Update(value.MasterContentID, GetItemProperties(value));

                // Reflect the changes in the list.
                _storageList[index] = value;
            }
        }

        #endregion

        #region Implementation of IEnumerable

        ///
        /// Returns an enumerator that iterates through a collection.
        ///
        /// <returns>
        /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
        /// </returns>
        /// <filterpriority>2</filterpriority>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion
    }
}

And here is the method I use to call the repository:
using System.Collections.Generic;
using ClubEventsData;
using System.Linq;
using System;

namespace ClubEventsDataHandling.System.Implementations.Controllers
{
    public class TicketDataController : IDataController
    {
        private DataRepository<Ticket> _repository;

        public TicketDataController()
        {
            _repository = new DataRepository<Ticket>();
        }

        public List<Ticket> GetDateTickets(Guid dateID)
        {
            return _repository.Where(ticket => ticket.EventDateBoughtFor.MasterContentID == dateID).ToList();
        }
    }
}

A: The reason for _repository.Count being 0 is simply that you don't access your _storageList in the Count property. You need to change it to this:
public int Count
{
    get { return _storageList.Count; }
}


text:
Q: spritekit collision detection not working No matter what I do I can't seem to get my code to note a single collision.  None of the Nslogs ever output anything so I know that the code never even notices a collision.  I've tried many images at many sizes and even tried changing the node type category multiple times, but still nothing.  What am I doing wrong here?
      #import "JKGPlayer.h"
#import "JKGMyScene.h"
static const uint32_t firstNodeTypeCategory     =  0x1 << 1;
static const uint32_t secondNodeTypeCategory        =  0x1 << 2;

// 1
@interface JKGMyScene () <SKPhysicsContactDelegate>
@property (nonatomic) JKGPlayer * player;
@property (nonatomic) SKSpriteNode * plat2;
@property (nonatomic) SKSpriteNode * a1;
@property (nonatomic) SKSpriteNode * a2;
@end
@implementation JKGMyScene

-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {

    // 2
    NSLog(@"Size: %@", NSStringFromCGSize(size));

    // 3
    self.backgroundColor = [SKColor colorWithRed:1.0 green:.50 blue:1.0 alpha:1.0];

    // 4
    _plat2 = [SKSpriteNode spriteNodeWithImageNamed:@"twa1.png"];
    _plat2.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:_plat2.size];
    _plat2.position = CGPointMake(500, 500);
    _plat2.zPosition = 15;
    _plat2.physicsBody.dynamic = NO;
    _plat2.physicsBody.usesPreciseCollisionDetection = YES;
    _plat2.physicsBody.friction = 0;
    _plat2.name = @"plat2";
    _plat2.physicsBody.categoryBitMask = secondNodeTypeCategory;
    _plat2.physicsBody.contactTestBitMask = firstNodeTypeCategory;
    _plat2.physicsBody.collisionBitMask = secondNodeTypeCategory;
    [self addChild:_plat2];

    _a1 = [SKSpriteNode spriteNodeWithImageNamed:@"sun.png"];
    _a1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:_a1.size];
    _a1.position = CGPointMake(500, 450);
    _a1.zPosition = 15;
    _a1.physicsBody.dynamic = NO;
    _a1.physicsBody.usesPreciseCollisionDetection = YES;
    _a1.physicsBody.friction = 0;
    _a1.name = @"plat2";
    _a1.physicsBody.categoryBitMask = firstNodeTypeCategory;
    _a1.physicsBody.contactTestBitMask = secondNodeTypeCategory;
    _a1.physicsBody.collisionBitMask = firstNodeTypeCategory;
    [self addChild:_a1];

    _a2 = [SKSpriteNode spriteNodeWithImageNamed:@"sun.png"];
    _a2.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:_a2.size];
    _a2.position = CGPointMake(500, 500);
    _a2.zPosition = 15;
    _a2.physicsBody.dynamic = NO;
    _a2.physicsBody.usesPreciseCollisionDetection = YES;
    _a2.physicsBody.friction = 0;
    _a2.name = @"plat2";
    _a2.physicsBody.categoryBitMask = secondNodeTypeCategory;
    _a2.physicsBody.contactTestBitMask = firstNodeTypeCategory;
    _a2.physicsBody.collisionBitMask = secondNodeTypeCategory;
    [self addChild:_a2];

    self.player = [[JKGPlayer alloc] initWithImageNamed:@"walkright1"];
    self.player.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.player.size];
    self.player.position = CGPointMake(500, 550);
    self.player.zPosition = 15;
    self.player.physicsBody.dynamic = NO;
    self.player.physicsBody.usesPreciseCollisionDetection = YES;
    self.player.physicsBody.friction = 0;
    self.player.name = @"player";
    self.player.physicsBody.categoryBitMask = firstNodeTypeCategory;
    self.player.physicsBody.contactTestBitMask = secondNodeTypeCategory;
    self.player.physicsBody.collisionBitMask = firstNodeTypeCategory;

    [self  addChild:self.player];
    self.userInteractionEnabled = YES;
    self.physicsWorld.gravity = CGVectorMake(0,0);
    self.physicsWorld.contactDelegate = self;

}
return self;
 }

 - (void)updateWithTimeSinceLastUpdate:(CFTimeInterval)timeSinceLast {

 }

 - (void)update:(NSTimeInterval)currentTime {
      self.player.desiredPosition = CGPointMake(self.player.position.x, self.player.position.y-1);
      self.player.position = self.player.desiredPosition;
     self.player.onGround = NO;
  }

 -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

int x = self.player.position.x-5;
int y = self.player.position.y-5;
CGPoint A = CGPointMake(x, y);
self.player.position = A;
// 1 - Choose one of the touches to work with
UITouch * touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
 }

 - (void)projectile:(SKSpriteNode *)projectile didCollideWithMonster:(SKSpriteNode *)monster {
      NSLog(@"Hit");
 }

 - (void)didBeginContact:(SKPhysicsContact *)contact{
     NSLog(@"AAAAAA");
     // 1
     SKPhysicsBody *firstBody, *secondBody;

if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask){
    firstBody = contact.bodyA;
    secondBody = contact.bodyB;
}
else
{
    firstBody = contact.bodyB;
    secondBody = contact.bodyA;
}

// 2
if ((firstBody.categoryBitMask & firstNodeTypeCategory) != 0 &&
    (secondBody.categoryBitMask & secondNodeTypeCategory) != 0)
{
    [self projectile:(SKSpriteNode *) firstBody.node didCollideWithMonster:(SKSpriteNode *) secondBody.node];
}

}


text:
Q: SSMS: Show execution plan for a stored procedure as a single tree I execute a stored procedure with an option "Include Actual Execution Plan". The execution plan always is represented by multiple statements each of which has its own execution plan.
MSDN states the following:

If the statement is a stored procedure
  or Transact-SQL statement, it becomes
  the root of the graphical execution
  plan tree structure. The stored
  procedure can have multiple children
  that represent statements called by
  the stored procedure. Each child is a
  node or branch of the tree.

In this case I expect to run a stored procedure and see only one tree where the root node is the stored procedure.
How it is possible to switch on such plan visualization for a stored procedure?
UPDATE:
It looks like an estimated subtree cost is not the same for actual and estimated execution plans.
Is there a way how one can see Estimated execution cost for the whole stored procedure and not only for its statements?

A: The Estimated plans (CTRL + L) show a tree structure. Actual plans (CTRL + M) do not.
I've never seen a tree for a procedure in an actual plan (and I never use estimated plans anyway)

A:
Is there a way how one can see
  Estimated execution cost for the whole
  stored procedure and not only for its
  statements?

The only way I think you can do this is by capturing the XML plans and inspecting these (aggregating the value for the individual plans). Capturing these plans is only possible by a trace as far as I know so you could create a couple of helper stored procedures to manage the setup and termination of the trace and sandwich your actual stored procedure call inbetween.
DECLARE @TraceID INT
EXEC StartCapture @@SPID, @TraceID OUTPUT
EXEC sp_help 'sys.objects' /*<-- Call your stored proc of interest here.*/
EXEC StopCapture @TraceID

Example StartCapture Definition
CREATE PROCEDURE StartCapture
@Spid INT,
@TraceID INT OUTPUT
AS
DECLARE @maxfilesize BIGINT = 5
DECLARE @filepath NVARCHAR(200) = N'C:\trace_' + LEFT(NEWID(),36)

EXEC sp_trace_create @TraceID OUTPUT, 0, @filepath, @maxfilesize, NULL

exec sp_trace_setevent @TraceID, 122, 1, 1
exec sp_trace_setevent @TraceID, 122, 22, 1
exec sp_trace_setevent @TraceID, 122, 34, 1
exec sp_trace_setevent @TraceID, 122, 51, 1
exec sp_trace_setevent @TraceID, 122, 12, 1
-- filter for spid
EXEC sp_trace_setfilter @TraceID, 12, 0, 0, @Spid
-- start the trace
EXEC sp_trace_setstatus @TraceID, 1

Example StopCapture Definition
CREATE  PROCEDURE StopCapture
@TraceID INT
AS
WITH  XMLNAMESPACES ('http://schemas.microsoft.com/sqlserver/2004/07/showplan' as sql),
      CTE
     as (SELECT CAST(TextData AS VARCHAR(MAX)) AS TextData,
                ObjectID,
                ObjectName,
                EventSequence,
                /*costs accumulate up the tree so the MAX should be the root*/
                MAX(EstimatedTotalSubtreeCost) AS EstimatedTotalSubtreeCost
         FROM   fn_trace_getinfo(@TraceID) fn
                CROSS APPLY fn_trace_gettable(CAST(value AS NVARCHAR(200)), 1)
                CROSS APPLY (SELECT CAST(TextData AS XML) AS xPlan) x
                CROSS APPLY (SELECT T.relop.value('@EstimatedTotalSubtreeCost',
                                            'float') AS EstimatedTotalSubtreeCost
                             FROM   xPlan.nodes('//sql:RelOp') T(relop)) ca
         WHERE  property = 2
                AND TextData IS NOT NULL
                AND ObjectName not in ( 'StopCapture', 'fn_trace_getinfo' )
         GROUP  BY CAST(TextData AS VARCHAR(MAX)),
                   ObjectID,
                   ObjectName,
                   EventSequence)
SELECT ObjectName,
       SUM(EstimatedTotalSubtreeCost) AS EstimatedTotalSubtreeCost
FROM   CTE
GROUP  BY ObjectID,
          ObjectName

-- Stop the trace
EXEC sp_trace_setstatus @TraceID, 0
-- Close and delete the trace
EXEC sp_trace_setstatus @TraceID, 2
GO


text:
Q: Is this ChannelFuture listener registration robust? Below is some code snippet from the book < Netty in Action >.

I am wondering if the connect action finished after 1 and before 2, will the ChannelFutureListener ever get a chance to be notified?

A: Check the Netty javadoc, specifically for addListener. It states that the listener will be notified immediately if the operation is already complete.
So the answer is yes, it's robust.


text:
Q: Delay before slide show animation start My slide show Activity is one of my list view rows , when click the slideshow row it must open slide images with animation but there is a delay of around 25 second till first image appear ,
i try to change the time here:
int delay = 1000;

but that not fix it ,
any help will be appreciated , thanks
public class SlideShow extends Activity {

public int currentimageindex=0;
Timer timer;
TimerTask task;
ImageView slidingimage;

private int[] IMAGE_IDS = {
        R.drawable.day_one_1, R.drawable.day_one_2,R.drawable.day_one_3,
        R.drawable.day_one_4, R.drawable.day_one_5,R.drawable.day_one_6,R.drawable.day_one_7,
        R.drawable.day_one_8, R.drawable.day_one_9,R.drawable.day_one_10
        };

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.slide);
     if (customTitleSupported) {
         getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title);
         TextView tv = (TextView) findViewById(R.id.title_tv1);
         tv.setTypeface(FontFactory.getBFantezy(getBaseContext()));
         tv.setText("slide show");
         }
    final Handler mHandler = new Handler();
 // Create runnable for posting
    final Runnable mUpdateResults = new Runnable() {
        public void run() {

            AnimateandSlideShow();
        }
    };

    int delay = 1000;

    int period = 5000;

    Timer timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {

    public void run() {

         mHandler.post(mUpdateResults);
    }

    }, delay, period);
}
private void AnimateandSlideShow() {

    SharedPreferences getPrefs = PreferenceManager
            .getDefaultSharedPreferences(getBaseContext());

    boolean animation_one = getPrefs.getBoolean("animation_one", true);
    boolean animation_two = getPrefs.getBoolean("animation_two", false);
    boolean animation_three = getPrefs.getBoolean("animation_three", false);
    boolean animation_four = getPrefs.getBoolean("animation_four", false);
    boolean animation_five = getPrefs.getBoolean("animation_five", false);

 if (animation_one == true) {
    slidingimage = (ImageView)findViewById(R.id.ImageView_slide);
    slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
    currentimageindex++;
    Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.custom_anim);
    Animation rotateimage1 = AnimationUtils.loadAnimation(this, R.anim.bounce);
      //
      AnimationSet s = new AnimationSet(false);
      s.addAnimation(rotateimage);
      s.addAnimation(rotateimage1);
      slidingimage.startAnimation(s);

}else if(animation_two == true) {
    slidingimage = (ImageView)findViewById(R.id.ImageView_slide);
    slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
    currentimageindex++;
    Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.fade_in);
      slidingimage.startAnimation(rotateimage);

}else if(animation_three == true) {
    slidingimage = (ImageView)findViewById(R.id.ImageView_slide);
    slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
    currentimageindex++;
    Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.move);
      slidingimage.startAnimation(rotateimage);

}else if(animation_four == true) {
    slidingimage = (ImageView)findViewById(R.id.ImageView_slide);
    slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
    currentimageindex++;
    Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.sequential);
      slidingimage.startAnimation(rotateimage);

}else if (animation_five == true) {
    slidingimage = (ImageView)findViewById(R.id.ImageView_slide);
    slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
    currentimageindex++;
    Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.slide_down);
      slidingimage.startAnimation(rotateimage);

}else if(animation_one == false && animation_two == false && animation_three == false
        && animation_four == false && animation_five == false){

    slidingimage = (ImageView)findViewById(R.id.ImageView_slide);
    slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
    currentimageindex++;
    Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.custom_anim);
      slidingimage.startAnimation(rotateimage);
    }
 }
public boolean onCreateOptionsMenu(android.view.Menu menu) {

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);

    getLayoutInflater().setFactory(new Factory() {
    public View onCreateView(String name, Context context,AttributeSet attrs) {

    if (name .equalsIgnoreCase("com.android.internal.view.menu.IconMenuItemView")) {
    try {
    LayoutInflater li = LayoutInflater.from(context);
    final View view = li.createView(name, null, attrs);

    new Handler().post(new Runnable() {
    public void run() {

    view .setBackgroundResource(R.drawable.border);

    ((TextView) view).setTextSize(30);

    ((TextView) view).setTypeface(FontFactory.getBFantezy(getBaseContext()));

    ((TextView) view).setTextColor(Color.RED);
    }
    });

    return view;
    }
     catch (InflateException e) {}
      catch (ClassNotFoundException e) {}
    }
    return null;
    }
    });
    return super.onCreateOptionsMenu(menu);
                                       }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
        case R.id.slide_pref:
              Intent i = new Intent("com.test.demo.SETTING");
              startActivity(i);
        break;
            }
    return false;
    }
}

A: Try to use postdelay:
private int mSampleDurationTime = 5000; // 1 sec
private boolean continueToNext = true;

Handler mHandler = new Handler();

mHandler.postDelayed(mRunnable, mSampleDurationTime);

where mRunnable is your task:
private final Runnable mRunnable = new Runnable() {

 //...
public void run() {

   // do something here

   if(continueToNext == true){
    mHandler.postDelayed(mRunnable, mSampleDurationTime);
   }

 }
    ...
};

A: Replace this piece of code :
final Handler mHandler = new Handler();
 // Create runnable for posting
 final Runnable mUpdateResults = new Runnable() {
    public void run() {

        AnimateandSlideShow();
    }
};

int delay = 1000;

int period = 5000;

Timer timer = new Timer();

timer.scheduleAtFixedRate(new TimerTask() {

public void run() {

     mHandler.post(mUpdateResults);
}

}, delay, period);

}
Write instead this code :
final Handler handler = new Handler();
 runnable = new Runnable() {
     @Override
    public void run() {
        handler.postDelayed(runnable, 5000);
        AnimateandSlideShow();
    }
};
handler.postDelayed(runnable, 500);
}

This will lead to start image without delay ,
then you can control the appearance time and the time in between image as you want,
Hope help you .


text:
Q: Woocommerce - Use SKU as unique identifier in the order creation with REST API I have a website where I want to transfer woocommerce orders. Everything is working very well now but I have a strungle with product pairing. Products ids on testing are not the same as on live website. What do I need to add products to order and pair them not with their ID but with the SKU which is the same on both websites. My code is bellow.
I'm following this structure over here but I have no clue how to pair line items by the SKU 'line_items': https://woocommerce.github.io/woocommerce-rest-api-docs/?php#create-an-order
add_action( 'woocommerce_order_status_processing_to_gls', 'transfer_order_woo_api', 9999, 3 );
function transfer_order_woo_api( $order_id, $order ) {
   $live_ck = 'ck_some ID';
   $live_cs = 'cs_SOME ID';
   $live_url = 'https://testsite.com/wp-json/wc/v3/orders?consumer_key=' . $live_ck . '&consumer_secret=' . $live_cs;
   $order = wc_get_order( $order_id );

    // Line items - HERE IS THE PROBLEM
    $lineitems = array();
    foreach ( $order->get_items() as $item_id => $item ) {
     $product_id = $item->get_product_id();
     $quantity = $item->get_quantity();
     $product = $item->get_product();

    $lineitem = array('quantity' => $quantity,
                     'product_id' => $product_id //I need to pair theese line items by the SKU because the product ID is not the same on different sites but the SKU is the same.

                      );
    $lineitems[] = $lineitem;
    }

   $body = array(
      'status' => 'processing',
      'meta_data' => array(
      array(
         'key' => 'carrier',
         'value' => ''.get_post_meta($order->id, 'ywot_carrier_id', true).''
      ),
      array(
         'key' => 'order_number',
         'value' => ''.get_post_meta($order->id, '_alg_wc_custom_order_number', true).''
      ),
      array(
         'key' => 'orderid',
         'value' => $order->get_id(),
      ),
      array(
         'key' => 'shipped_date',
         'value' => ''.get_post_meta($order->id, 'shipped_date', true).''
      ),
      array(
         'key' => 'ywot_tracking_code',
         'value' => ''.get_post_meta($order->id, 'ywot_tracking_code', true).''
      )),

      'billing' => array(
         'first_name' => $order->get_billing_first_name(),
         'last_name' => $order->get_billing_last_name(),
         'address1' => $order->get_billing_address_1(),
         'city' => $order->get_billing_city(),
         'postcode' => $order->get_billing_postcode(),
         'country' => $order->get_billing_country(),
         'phone' => $order->get_billing_phone(),
      ),
      'shipping' => array(
         'first_name' => $order->get_shipping_first_name(),
         'last_name' => $order->get_shipping_last_name(),
         'address1' => $order->get_shipping_address_1(),
         'city' => $order->get_shipping_city(),
         'postcode' => $order->get_shipping_postcode(),
         'country' => $order->get_shipping_country(),
      ),
      'line_items' => $lineitems,

   );

   $raw_response = wp_remote_post( $live_url,
      array(
         'headers' => array( 'Content-Type' => 'application/json' ),
         'timeout' => 30,
         'body' => json_encode( $body ),
      )
   );

Thanks in advance for your ideas.

UPDATE
add_action( "woocommerce_order_status_processing_to_gls", "transfer_order_woo_api", 9999, 3 );
function transfer_order_woo_api( $order_id, $order ) {
   $remote_keys = "consumer_key=ck_xxxx&consumer_secret=cs_xxxx";
   $live_url = "https://web.com/wp-json/wc/v3/orders?{$remote_keys}";
   $line_items = array();

   foreach ( $order->get_items() as $item_id => $item ) {
      $quantity = $item->get_quantity();
      $product = $item->get_product();
      $product_sku = $product->get_sku();

      // retrieve product ID by SKU, return product properties
      $remote_get = wp_remote_get("https://web.com/wp-json/wc/v3/products?sku={$product_sku}&{$remote_keys}");
      $remote_product = json_decode($remote_get['body'])[0];

      $line_item = array(
                       "quantity" => $quantity,
                       "product_id" => $remote_product->id
                      );

      $line_items[] = $line_item;
   }

 $body = array(
      'status' => 'processing',
      'meta_data' => array(
      array(
         'key' => 'carrier',
         'value' => ''.get_post_meta($order->id, 'ywot_carrier_id', true).''
      ),
      array(
         'key' => 'order_number',
         'value' => ''.get_post_meta($order->id, '_alg_wc_custom_order_number', true).''
      ),
      array(
         'key' => 'orderid',
         'value' => $order->get_id(),
      ),
      array(
         'key' => 'shipped_date',
         'value' => ''.get_post_meta($order->id, 'shipped_date', true).''
      ),
      array(
         'key' => 'ywot_tracking_code',
         'value' => ''.get_post_meta($order->id, 'ywot_tracking_code', true).''
      )),

      'billing' => array(
         'first_name' => $order->get_billing_first_name(),
         'last_name' => $order->get_billing_last_name(),
         'address1' => $order->get_billing_address_1(),
         'city' => $order->get_billing_city(),
         'postcode' => $order->get_billing_postcode(),
         'country' => $order->get_billing_country(),
         'phone' => $order->get_billing_phone(),
      ),
      'shipping' => array(
         'first_name' => $order->get_shipping_first_name(),
         'last_name' => $order->get_shipping_last_name(),
         'address1' => $order->get_shipping_address_1(),
         'city' => $order->get_shipping_city(),
         'postcode' => $order->get_shipping_postcode(),
         'country' => $order->get_shipping_country(),
      ),
      'line_items' => $lineitems,

   );

   $raw_response = wp_remote_post( $live_url,
      array(
         'headers' => array( 'Content-Type' => 'application/json' ),
         'timeout' => 30,
         'body' => json_encode( $body ),
      )
   );

}

A: You could retrieve each product ID from the other site using the API /wp-json/wc/v3/products?sku=xxxxx (GET) inside your loop. The example as below.
add_action( "woocommerce_order_status_processing_to_gls", "transfer_order_woo_api", 9999, 3 );
function transfer_order_woo_api( $order_id, $order ) {
   $remote_keys = "consumer_key=xxxxxx&consumer_secret=xxxxxx";
   $remote_url = "https://testsite.com/wp-json/wc/v3/orders?{$remote_keys}";
   $line_items = array();

   foreach ( $order->get_items() as $item_id => $item ) {
      $quantity = $item->get_quantity();
      $product = $item->get_product();
      $product_sku = $product->get_sku();

      // retrieve product ID by SKU, return product properties
      $remote_get = wp_remote_get("https://testsite.com/wp-json/wc/v3/products?sku={$product_sku}&{$remote_keys}");
      $remote_product = json_decode($remote_get['body'])[0];

      $line_item = array(
                       "quantity" => $quantity,
                       "product_id" => $remote_product->id
                      );

      $line_items[] = $line_item;
   }

   // rest of your code here...
}


text:
Q: Android Studio - How to turn off "typo in word 'word'? When naming variables or giving String arguments Android Studio seems to have a problem with how I label things.
Is there a way to turn that off?

A: On Android Studio 4.1.x you have to open File > Settings and uncheck Typo inside Editor > Inspections > Proofreading (you could also find it using the search box on top of Settings screen).

A: In Android Studio 3.6.1 (and probably some other versions), go into File > Settings, search for "spelling", and choose the Inspections category:

Either turn of "Typo" entirely or configure the options (lower-right corner in screenshot) to determine where you do and do not want spell-check.
The Spelling category lets you control what language dictionaries get used, etc.

A: Yes, open Preferences -> Editor -> Inspections -> Spelling -> toggle off Typo and press OK.
Edit
To make it as default not only for your project select Profile: Default.

A: You can add the word in "Accepted words" list:
Open File -> Settings -> Editor/Spelling, click + below "Accepted words" and add word, so you can let spell checing intact.

Edit: You can also add @SuppressWarnings("SpellCheckingInspection") for Java or @Suppress("SpellCheckingInspection") for Kotlin before a Class, Function or Sub and also keep spell checking for other parts of code.


text:
Q: Scapy: Is it possible to manually set the destination MAC address of ARP packets? Using python with Scapy, I have no problems changing the MAC address destination of the packets using the following sample code:
packet = Ether(dst=[MAC address])/IP()......

However, when I try to do the same with ARP like this:
packet = Ether(dst=[MAC address])/ARP(......

The packet does not get sent out. Is it because ARP is already a layer 2 protocol? If thats the case, is there any possibility of manually changing the destination MAC of an ARP packet?

A: This works for me:
sendp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(op=ARP.who_has, psrc="10.250.0.145", pdst="10.250.0.129"))


text:
Q: How can I rewrite the native HTML input element with Polymer? I want to rewrite the <input type="number"> element with Polymer so that i can <input is="number-input"> and style it in a way so that it looks and behaves the same on different browsers.
This is where I'm at now:
<link rel="import" href="../polymer/polymer.html">
<polymer-element name="number-input" extends="input" attributes="value">
  <script>
    Polymer('number-input', {
      valueChanged: function(){
        console.log(this.value)
      }
    });
  </script>
</polymer-element>

... and using it by <input is="number-input">, but it doesn't fire the valueChanged function.
What am I doin wrong?

A: Teltrik did a recent article on styling inputs with shadow dom that was pretty interesting: http://developer.telerik.com/featured/comprehensive-guide-styling-file-inputs/
In your case, you're doing everything correctly. The problem however, is that input already has a .value property. You're trying to override the native property which creates unpredictable behavior. The second issues is that Object.observe() cannot observe native properties on elements. For example, if you added the hidden attribute, hiddenChanged would never be called. Likewise for title and titleChanged.


text:
Q: What should be the ideal value for Maximum connections in the Websphere Connection pool for more than 125 concurrent users? Currently I'm facing the following issue from the websphere server,

[5/15/18 6:45:20:959 BST] 0000060d FreePool      E   J2CA0045E: Connection not available while invoking method createOrWaitForConnection for resource jdbc/ICWS.

The root cause of J2CA0045E error is,

*

*Use of Shareable Connections in Long-Running LTC

*Multiple connection requests on same thread without calling close()

*Connection leak in application

*Long-running queries or slow database response time

*Maximum Connections set too low

So I checked all the above mentioned causes and finally found that Maximum connections was set low. The difficulty that I'm facing is to find the ideal number for maximum connections. The webservice that I deployed in websphere has 125 concurrent requests and currently the maximum connection size is 50. But I found that It is not enough. Following are the server specification,
Memory usage at LPAR level is 12 GB out of 14 GB .
Heap :

*

*initial heap - 512

*max heap size – 2560

Can I set the maximum connection value to 200 or more with the above server specification?
OR
Is there any ideal value for this parameter?

A: There is no fixed answer that applies to all usage patterns. It's a matter of tuning. For a starting point, a good guideline is that if you have a web service that requires a single connection each time it is called, then aim to have the maximum number of concurrent web service requests and maximum number of connections match.


text:
Q: Android Fragment Reverse Animations Not Working I am developing the tablet portion of my application that incorporates a Master-Detail Flow Template. When I click a button on the detail side, a fragment transition animation takes place on that side with one fragment replacing the other with:
MenuFragment fragment = new MenuFragment();
FragmentManager fragmentManager = getSupportFragmentManager();

FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.abc_push_left_in, R.anim.abc_push_left_out,
     R.anim.abc_push_right_out, R.anim.abc_push_right_in);

transaction.replace(R.id.main_fragment_container, fragment);
transaction.addToBackStack(null);
transaction.commit();

The animation in the transition works perfectly. However, when I want to go back to the previous fragment by clicking a back button, the fragment that's coming in appears with the push animation working, but the fragment that's leaving is not executing its exiting push animation. It's simply disappearing with only one animation working.
I've tried using different animations but I get the same result. Does anyone have an idea of what's happening or if I'm not understanding something about fragment transitions?
EDIT: My activity_skill_twopane.xml's detail FrameLayout is the fragment container with its id as R.id.main_fragment_container. It appears that when I put an ImageView in the detail FrameLayout in the xml it shows up in the background while the animations are happening as well. Does anyone know why that's happening too?
EDIT: My animation xml's are as follows:
abc_push_left_in:
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="100%" android:toXDelta="0" android:duration="500"/>
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="500" />
</set>

abc_push_left_out:
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="-100%" android:duration="500"/>
    <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="500" />
</set>

abc_push_right_in:
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="100%" android:duration="500"/>
    <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="500" />
</set>

abc_push_right_out:
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="-100%" android:toXDelta="0" android:duration="500"/>
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="500" />
</set>

UPDATE: I managed to recreate the problem on a handset. If you have one Fragment Activity with a button that does a fragment transaction with animations like mine and press back from the second activity to call "popBackStackImmediate", you will notice that the fragment being replaced just disappears without animating while the fragment that's replacing executes its animation.

A: I got it wrong, the null is only for the name, so you are adding it to the backstack already.
You should have the animations in a different order like this:
transaction.setCustomAnimations(R.anim.abc_push_left_in, R.anim.abc_push_left_out,
 R.anim.abc_push_right_in, R.anim.abc_push_right_out);

Also you don't need to override onBackPressed the system should handle it for you.


text:
Q: Javascript; function (x,y,z), confused on how values are passed I searched and read about functions to no extent. I have seen my questions answered, but not in the detail I have understood. I'm less than one year into programming.
Okay, so I don't understand how the r,c,or the e get values.
How does Javascript know what to use "r" and "c" for when the code is later called. How does the "e" end up in the final function?
Maybe I'm shooting too high trying to understand this, but maybe not. Thanks
game.makeKeydown = function (r, c) {
    return function (e) {
        return game.onKeydown(e, r, c);
    };
};

A: The r and c variables are determined at the time that game.makeKeydown is called.  For example var fn = game.makeKeydown(1, 2); will return a function for which the values of r and c is always 1 and 2, respectively.
fn will also accept one value, which will become the value of e, so fn("s") will give the value "s" to e.
By the way, the mechanism that's assigning the values to r and c is called a "closure".

A: This is a technique called currying (partial function application).
So you have a function game.onKeydown that takes three parameters.  You want a function with one parameter, because you know two of the parameters now.  The values r and c get assigned local values inside makeKeydown, and the value e gets assigned when the new function makeKeydown is actually invoked.
The link above is an article by John Resig talking about currying (recommended).

A: I'm pretty amateur, but this is my understanding of this: When you pass parameters into a function, the function will then replace all instances of the variable that you used to name your parameter with the value that you pass as a parameter. So what this function is doing is creating a function with fixed values of r and c, as well as an additional parameter, e, which you can later pass through this new function that you have just created.

A: Simply put, the code you have is a closure. The inner function is constructed and returned when the outer function is called. Thus, when the outer function makeKeydown is called with arguments r and c, they are available at the time the inner function is being constructed.
the inner function will take only one argument, e which probably may be the event object that is passed to the event handler. Thus,
game.makeKeyDown( 2, 4 ) will return a function which can be saved in a var. This new function will be called with only one arguments as follows:
var handler = game.makeKeydown(1,2);
var result = handler(4)


text:
Q: NSIS script that installs Chrome extension kills Outlook This is an incredibly bizarre bug.
Here is an NSIS script that installs an extension into Google Chrome.  Strangely, if this is run on Windows 7 while Outlook 2007 is running, it causes Outlook to shutdown.  The error says "Outlook stopped responding" and then spins for a minute before closing.
Can anyone shed any light on what the cause is and how to fix it?
!define VERSION "1.0.0"
!define EXT_ID "kmffervcdaycdjlksmflkjghksdf"
!define INSTALL_DIR "$LOCALAPPDATA\Google\Chrome\User Data\Default\Extensions\${EXT_ID}\${VERSION}_0"
!define P_FILE "$LOCALAPPDATA\Google\Chrome\User Data\Default\Preferences"

!include "ZipDLL.nsh"

!include "TextFunc.nsh"
!insertmacro LineFind

!include "WordFunc.nsh"
!insertmacro WordFind

Name "Chrome Extension Installer"
OutFile "extension_installer.exe"
RequestExecutionLevel admin

Var PMEMORY
Var SIZE

Function .onInit
    SetSilent silent
FunctionEnd

Section
    SetOutPath $TEMP
    File "extension.crx"
    File "chrome_preferences.txt"

    CreateDirectory "${INSTALL_DIR}"
    ZipDLL::extractall "$TEMP\extension.crx" "${INSTALL_DIR}"

    StrCpy $0 "${P_FILE}"
    StrCpy $1 "${P_FILE}"
    StrCpy $R0 '"settings": {'
    StrCpy $R1 "$TEMP\chrome_preferences.txt"
    StrCpy $R2 "0"
    StrCpy $R3 "0"
    ${LineFind} "$0" "$1" "1:-2 -1" "LineFindCallback"
SectionEnd

Function LineFindCallback
    StrCmp $PMEMORY '0' end

    begin:
    ${WordFind} "$R9" "$R0" "E+1{" $1
    IfErrors freemem
    FileWrite $R4 "$1"

    StrCmp $PMEMORY '' 0 write
    FileOpen $1 $R1 a
    FileSeek $1 0 END $SIZE
    System::Alloc $SIZE
    Pop $PMEMORY
    FileSeek $1 0 SET
    System::Call 'kernel32::ReadFile(i r1, i $PMEMORY, i $SIZE, t.,)'
    FileClose $1

    write:
    IntOp $R3 $R3 + 1
    System::Call 'kernel32::WriteFile(i R4, i $PMEMORY, i $SIZE, t.,)'
    ${WordFind} "$R9" "$R0" "+1}" $R9
    StrCmp $R3 $R2 0 begin

    freemem:
    StrCmp $PMEMORY '' end
    StrCmp $R7 -1 +2
    StrCmp $R3 $R2 0 end
    System::Free $PMEMORY
    StrCpy $PMEMORY 0

    end:
    Push $0
FunctionEnd

A: I don't know if this is the problem, but your system calls to Write/ReadFile are wrong, try ...(i r?, i $PMEMORY, i $SIZE, *i,i 0)'

A: The problem turned out to be ZipDLL.  Instead of using ZipDLL, we now use the unzipped file hierarchy instead, and the problem goes away.
(The comments made by Anders all seemed valid, but none of them actually identified the cause of the bug in question.)


text:
Q: Capture video on android NO RECORDING I've been reading the android api for capture video and reading some code and I haven't been able to found a method that give me the frame captured and then work with it, for example send it across wifi or something like that.
There is a feature, on android, that allow me capture the frame but no record
it in a file?
Thanks.

A: I Have 2 solutions. First one is use the MediaRecorder object and in the setOutputFile() function, pass as parameter a socket descriptor, this way permits read the data from a socket. The second one is use a preview callback and intercept the frame with onPreviewFrame() function.


text:
Q: Find all internet facing servers We have a large network with many servers. What is the easiest way to find all the servers that are Internet facing?  Manually checking each server is not an option.

A: *

*Run nmap from the outside against all your address space?

*Examine the rule set on your firewall/border device to see what is permitted.

*Monitor traffic on your firewall/border device for a while and see what is being accessed?

You should probably do all of the above, and once you find the results, add it to your documentation, that will be maintained.  Once you find the results from the above, you would dig deeper, and check to see if the permitted traffic is going to some kind of device that is proxying or otherwise permitting traffic to other devices.

A: I would check with my CMDB or other documentation.
Failing that, you'll have to define "internet-facing" (responds to inbound requests only? Can get out to the internet on its own?) ... and then check each one. Not from the outside, either. What if you have a public DNS name that points to a cluster of LB and that has 30 servers behind it? From the outside, you'll never be able to tell what server you've hit, unless the server puts its name in the application payload somehow - over HTTP, this could be an X-header. Although it would probably be a bad idea if it did.
If you have a single device that can capture all internet traffic, you could parse the logs, but that will only tell you what servers talked, it would miss any servers that weren't hit during the log timeframe.

A: If you aren't just trying to figure out how to break into someone else's network, you should be able to work it out if you gather the following information:
You should at least know which devices have a physical connection to the internet, by whatever means, and hopefully some controlled points of entry (1 or more firewalls).  Looking at the configuration on those may help.
You should be able to find out the public IP addresses assigned to your network - that is somewhere else to check.  Reverse DNS lookups of these, both public and internal, should give some clues.
Are you using NAT on your network?  If so, then somewhere you must be mapping traffic from the internet through NAT to the servers.  Check the config for that.
If you are just trying to break into a network, then you will probably find more help in  other fora.


text:
Q: Run AIR Debug Launcher (ADL) without a GUI for continuous build Is it possible to run the ADL without a GUI so that I can run FlexUnit tests during a nightly build? Right now, when I execute our test runner on our server (Ubuntu 9.04) it fails with the output: "Gtk-WARNING **: cannot open display:".
Many thanks for any suggestions!

A: Yes.
We use hudson with xvnc plugin and vncserver installed on the server.
Some instructions to follow can be found at:- http://docs.flexunit.org/index.php?title=Continuous_Integration_Support
A more specific example is at :- http://www.brianlegros.com/blog/2009/12/20/using-xvnc-to-create-headless-ci-builds-for-flex-and-air-applications/
Hope you come right. It's a bit of a pain to get working.


text:
Q: How do I disable the keyboard shortcut overlay in Ubuntu 12.10? I'd like to be able to disable the keyboard shortcut overlay that appears when you hold the Super/Meta/Windows key or at least make it hidden. It is annoying, I find no use for it, and it interferes with usage of a Windows VM in VMWare - whenever I click the Meta key, the button is interpreted by both Ubuntu and the VM, causing the overlay to appear.
I am aware of this question describing how to solve the issue in Ubuntu 12.04. Unfortunately, both of the methods provided in there are unavailable in Ubuntu 12.10.
Is there some setting in gconf or dconf or even ccsm that I'm missing, or is this display now unable to be turned off in 12.10?


text:
Q: Chamar uma procedure PL/SQL passando uma data como parâmetro Eu tenho uma procedure PL/SQL
( LnCDOrigem            IN Company.COD_CD%TYPE,
   LnSotoreOrigem       IN Company.COD_STORE%TYPE,
   LvTipoEqpt           IN VARCHAR2,
   LdDtMovimento        IN DATE,
   LnRetorno            OUT NUMBER)

Quando faço a chamada dela pelo Java recebo um seguinte erro
ORA-01858: a non-numeric character was found where a numeric was expected
ORA-06512: at line 1

Meu codigo java está assim
CallableStatement statement = getConnection().prepareCall(
            "{ Call PCK_ABERTURA_CONTABIL.Abrir_Data_Contabil(:LnCDOrigem, :LnSotoreOrigem, " +
                    ":tipoEquipamento, :dataMovimento, :retorno) }");
    Date dataMovimento = Date.valueOf(dataHora);
    statement.setLong("LnCDOrigem", codigoOrigem);
    statement.setLong("LnStoreOrigem", codigoStore);
    statement.setDate("dataMovimento", dataMovimento);
    statement.setString("tipoEquipamento", "M");
    statement.registerOutParameter("retorno", OracleTypes.NUMBER);
    statement.execute();
    return statement.getLong("retorno");


text:
Q: Android AdMob Error The ad size and ad unit ID must be set before load is called Hi I'm trying to add ads into my application but i keep getting the error
The ad size and ad unit ID must be set before load is called.

heres what i have tried so far
heres my layout (I have the actual adUnitId number that i have put in the xml in my app just havn't put it in here as i didnt think it would be a good idea to post it online)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/levelView"
     >

     <RelativeLayout
      android:id="@+id/header"
      android:layout_width="match_parent"
      android:layout_height="70dp"
      >

          <TextView
            android:id="@+id/tv1"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
           android:layout_marginTop="5dp"
            android:textSize="15dp"
            android:textColor="@color/white"
            android:text="hello"
            android:gravity="center"
            android:singleLine="true"/>

         <TextView
            android:id="@+id/headertitle"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
             android:layout_below="@+id/headertitle"
           android:textSize="40dp"
            android:textColor="@color/white"
            android:layout_marginTop="15dp"
            android:text="2014"
            android:gravity="center"
            android:singleLine="true"/>

         <ImageView
             android:id="@+id/imageView1"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_centerVertical="true"
             android:layout_marginLeft="18dp"
             android:layout_toRightOf="@+id/headertitle"
             android:src="@drawable/level_logo" />

    </RelativeLayout>

   <GridView
        android:id="@+id/gridView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/header"
        android:numColumns="4"
        android:listSelector="@null"
        android:layout_centerHorizontal="true" >
    </GridView>

  <com.google.android.gms.ads.AdView android:id="@+id/adView"
                         android:layout_width="wrap_content"
                         android:layout_height="wrap_content"
                         android:layout_below="@+id/gridView1"
                         ads:adUnitId="MY ID NUMBER"
                         ads:adSize="BANNER"/>

</RelativeLayout>

And then in my onCreate() im running the following function
 public void loadAds(){
        // Look up the AdView as a resource and load a request.
        AdView adView = (AdView)this.findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        adView.loadAd(adRequest);
        }

Does anyone know what the error means and how can i fix it?

A: Change the xmlns:ads schema
from
 xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"

to
 xmlns:ads="http://schemas.android.com/apk/res-auto"

A: I figured out the answer it was to change
<com.google.android.gms.ads.AdView android:id="@+id/adView"
                         android:layout_width="wrap_content"
                         android:layout_height="wrap_content"
                         android:layout_below="@+id/gridView1"
                         ads:adUnitId="MY ID NUMBER"
                         ads:adSize="BANNER"/>

to
<com.google.android.gms.ads.AdView android:id="@+id/adView"

                         xmlns:ads="http://schemas.android.com/apk/res-auto"
                         android:layout_width="match_parent"
                         android:layout_height="wrap_content"

                         ads:adUnitId="ca-app-pub-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
                         ads:adSize="BANNER"
                         android:layout_alignParentBottom="true"
                         >

  </com.google.android.gms.ads.AdView>

A: I've faced the same error and finally used code instantiation to solve the issue.

A: Change your this code
   <com.google.android.gms.ads.AdView android:id="@+id/adView"
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:layout_below="@+id/gridView1"
                     ads:adUnitId="MY ID NUMBER"
                     ads:adSize="BANNER"/>

to
   <com.google.android.gms.ads.AdView android:id="@+id/adView"

                     xmlns:ads="http://schemas.android.com/apk/res-auto"
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"

                     ads:adUnitId="ca-app-pub-8510605212168324/8634800090"
                     ads:adSize="BANNER"
                     android:layout_alignParentBottom="true"
                     >

and Remove
                xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"


text:
Q: Ansible with Concourse I am trying to run ansible playbooks within Concourse for remote hosts, however i cannot do that. Below are my steps:-
Concourse Yaml File:-
---
resource_types:
- name: ansible-playbook
  type: docker-image
  source:
    repository: troykinsella/concourse-ansible-playbook-resource
    tag: latest

resources:
- name: ansible
  type: ansible-playbook
  source:
    debug: true
    user: cloud_user
    ssh_private_key: ((ssh-key))
    verbose: vvv

- name: source-code
  type: git
  source:
    uri: ((git-repo))
    branch: master
    private_key: ((ssh-key))

jobs:
  - name: ansible-concourse
    plan:
    - get: source-code # git resource
    - put: ansible
      params:
        check: true
        diff: true
        become: true
        become_user: root
        inventory: inventory/hosts
        playbook: site.yml
        path: source-code

Host File:-
[test]
localhost

Inside the Container:-
I intercepted the container and i can ssh to any IP inside, however i am not able to make ssh-login.
Ansible Playbook:-
---
- name: "Running Current Working Directory"
  hosts: test
  gather_facts: no

  tasks:
     - name: "Current Working Directory"
       shell: pwd
       register: value

     - debug:
          msg: "The Current Working Directory {{value.stdout_lines}}"

Output Coming in Concourse:-
ansible-playbook       -i inventory/hosts --private-key /tmp/ansible-playbook-resource-ssh-private-key   --user cloud_user   -vvv site.yml
ansible-playbook 2.9.0
  config file = /tmp/build/put/source-code/ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python3.6/dist-packages/ansible
  executable location = /usr/local/bin/ansible-playbook
  python version = 3.6.8 (default, Oct  7 2019, 12:59:55) [GCC 8.3.0]
Using /tmp/build/put/source-code/ansible.cfg as config file
host_list declined parsing /tmp/build/put/source-code/inventory/hosts as it did not pass its verify_file() method
script declined parsing /tmp/build/put/source-code/inventory/hosts as it did not pass its verify_file() method
auto declined parsing /tmp/build/put/source-code/inventory/hosts as it did not pass its verify_file() method
Parsed /tmp/build/put/source-code/inventory/hosts inventory source with ini plugin

PLAYBOOK: site.yml *************************************************************
1 plays in site.yml

PLAY [Running Current Working Directory] ***************************************
META: ran handlers

TASK [Current Working Directory] ***********************************************
task path: /tmp/build/put/source-code/site.yml:7
Monday 18 November 2019  12:38:49 +0000 (0:00:00.084)       0:00:00.085 *******
<localhost> ESTABLISH SSH CONNECTION FOR USER: cloud_user
<localhost> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o 'IdentityFile="/tmp/ansible-playbook-resource-ssh-private-key"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="cloud_user"' -o ConnectTimeout=10 -o ControlPath=/root/.ansible/cp/dc52b3112c localhost '/bin/sh -c '"'"'echo ~cloud_user && sleep 0'"'"''
<localhost> (255, b'', b'')
fatal: [localhost]: UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: ",
    "unreachable": true
}

PLAY RECAP *********************************************************************
localhost                  : ok=0    changed=0    unreachable=1    failed=0    skipped=0    rescued=0    ignored=0

Monday 18 November 2019  12:38:49 +0000 (0:00:00.029)       0:00:00.114 *******
===============================================================================
Current Working Directory ----------------------------------------------- 0.03s
/tmp/build/put/source-code/site.yml:7 -----------------------------------------

A: localhost is normally accessed through the local connection plugin (unless you are trying to do something really special and you have configured access through ssh which does not seem to be the case from your above error message).
If you don't declare it in you inventory, localhost is implicit, uses the local connection and is not matched in the all group.
However, if you declare localhost explicitly in your inventory, the default connection plugin becomes ssh and the all group matches this host too. You have to set the connection back to local yourself in that case.
You have two options to make your current test work:

*

*Delete your inventory (or use one that does not explicitly declare localhost) and modify your playbook to target localhost directly => hosts: localhost

*Keep your playbook as is and modify your inventory
[test]
localhost ansible_connection=local


text:
Q: Accelerating application loading through staged downloads I'm developing a game that I will distribute using Java Web Start / JNLP.
Currently the fully packaged .jar is around 11mb, which is not too bad, but I'd still like to get the application responsive as quickly as possible, i.e. before everything is downloaded - in particular I'd like a splash screen during loading, then allow other resources to continue to load in the background after the title screen is loaded and displayed.
Also, I'd like my users to benefit from client-side caching of already downloaded files if possible. I'm keen to do this in a browser neutral / cross-platform way.
What is the best approach to achieve this kind of staged downloading?

A: Java WebStart allows for lazy downloading of non-essential jars so the main routines can start quickly.  See http://download.oracle.com/javase/6/docs/technotes/guides/javaws/developersguide/syntax.html#resources


text:
Q: Added SSL to Static IP Address API Server I am not sure if anyone have this issue.
I have an

*

*Local API Server + Database with Static IP

*Web Site

My API server is holding all the information and the Web site is just a middleman and point all transaction to the server. So if we are talking about MVC, the website is like the View, and my API is the Model and Controller.
So my question is how should I add SSL to the API Server? Because my API server is running on an IP, so SSL is unable to attached to a Public IP. (Quoted from GoDaddy. IP Address to SSL will stop on 1st October 2016).
I seen online, saying to direct a domain name to the IP Address and get SSL for the domain but my question is, is there any security risk because technically I still access through the public IP directly.
Please advise on how should I proceed.
Thanks!

A: If you give it a hostname and a SSL cert for that hostname, anyone accessing via IP will get an "invalid SSL hostname mismatch" type error (exact error depends on what browser/client/etc. is being used to access it).  This is because your 10.42.56.113 doesn't match "db.example.com" and the SSL cert is for "db.example.com".
If you are using code to make the connection, then you need to know that some implementations of some things allow you to set flags/arguments/whatever that say "yes, use a self signed cert" or "don't freak out over SSL errors connect anyway".
But, that is bad practice.  Do it right.  Get a hostname assigned to your IP, get a SSL certificate for it (let's encrypt makes it super easy), and connect to it via that host name.


text:
Q: How debug a program that uses loops and sorting? I have a problem, I try to sort tabs and display them. User inputs number of how many tabs he wants to sort, but the last tab is not displayed.
I am beginner. How can I find where I made an error?
I tried tracking n integer, it resets to 0 after sorting the last tab, probably sorting algorithm messes it up, but I don't know how.
#include<iostream>
using namespace std;

void bsort(int tab[]) {
    for(int i=0; i<sizeof(tab)-1; i++) {
        for(int j=0; j<sizeof(tab)-1; j++) {
            if(tab[j] < tab[j+1]) swap(tab[j+1], tab[j]);
        }
    }
}

int main() {
    int t, n;
    cin >> t;
    for(int i=0; i<t; i++) {

        cin >> n;
        int tab[n];

        for(int j=0; j<n; j++) {
            cin >> tab[j];
        }

        bsort(tab);
        cout << n << endl;
        for(int k=0; k<n; k++) {
            cout << tab[k] << " ";
        }
    }
    return 0;
}

A: Arrays are always passed by pointer to functions and the "length" of that array is lost.  sizeof on an array parameter of the function will always return the size of a pointer (4 or 8 depending if your app is 32-bit or 64-bit).
Instead of this:
void bsort(int tab[]) {

This (with a few additional fixes and optimizations thrown in):
void bsort(int* tab, int length) {
    for(int i=0; i<length; i++) {
        for(int j=i+1; j<length; j++) {
            if(tab[i] > tab[j]) {        // replace "<" with ">" if you want descending sort
               int temp = tab[i];
               tab[i] = tab[j];
               tab[j] = tab[i];
            }
        }
    }
}

Then, in your main function, invoke with the length of that array;
bsort(tab, n);

Also, I suspect there are other optimizations you can make to your bsort function.


text:
Q: How to merge two subversion repositories using svnadmin How to merge two subversion (1.6) repositories on Debian Wheezy assuming the following repository layout:
reposA
    +-trunk
        +-project-1
        +-project-2
        +-project-3
    +-tags
        +-project-1
    +-branches
        +-project-1

reposB
    +-trunk
        +-project-4
        +-project-5
        +-project-6
    +-tags
        +-project-4
    +-branches
        +-project-4

Target layout should look like this:
reposAB
        +-trunk
            +-project-1
            +-project-2
            +-project-3
            +-project-4
            +-project-5
            +-project-6
        +-tags
            +-...
        +-branches
            +-...

What I already tried is:
svnadmin dump reposA > reposA.dmp
svnadmin dump reposB > reposB.dmp
svnadmin create new_common_repos
svnadmin load new_common_repo < reposA.dmp
svnadmin load new_common_repo < reposB.dmp

A: You can load two dump to separate sub folders and then rearrange as you like:
svnadmin create new_common_repo
svn mkdir file:///path/to/new_common/repo/reposA -m "Created folder reposA"
svnadmin dump reposA | svnadmin load new_common_repo --parent-dir reposA
svn mkdir file:///path/to/new_common/repo/reposB -m "Created folder reposB"
svnadmin dump reposB | svnadmin load new_common_repo --parent-dir reposB

And then for each project:
svn mkdir file:///path/to/new_common/repo/trunk -m "Created folder trunk"
svn mv file:///path/to/new_common/repo/reposA/project-1  file:///path/to/new_common/repo/trunk/project-1