text:
Q: Is there any testing tool to verify the font consistency throughout the web application? The purpose is to check for any inconsistency fonts used across the web application so that the developers can fix the issue.
Consistency in terms of all font properties (Font families,font sizes etc.) needs to be checked. As suggested by Pekka below, I can use CSS to define consistent font properties which can be used in all web pages but how can a QA auto test this and confirm the same CSS and hence the same font is applied to the entire web application?

A: If a font-family is set on the body tag in your stylesheet, then that font will apply to nearly every element throughout your site (form and table elements being the exception where you have to redeclare the font-family for those).
The only time the font-family declared on the body won't apply is if it's overridden by a different font-family applied on individual elements elsewhere in the stylesheet, or if it is applied by inline styles.
So you can check on font-family consistency in the stylesheet/s just be doing a search for 'font:' (for cases where shorthand is being used) and 'font-family' and making sure any references to it match what your default font should be.
To override different fonts set by inline style, take a look at this.


text:
Q: How do I get the str in a file as integers? i made a code that generate a file like this
import sys
file = open('output.txt','w')
x = [1,2,3,4,5,6,7,8,9,10]
f = [i**2 for i in x]
g = [i**3/100 for i in x]

strlist = list(map(str,f))
strlist1 = list(map(str,g))

file.write(','.join(strlist))
file.write('\n')
file.write('.'.join(strlist1))

and result is (file content)
1,4,9,16,25,36,49,64,81,100
0.01.0.08.0.27.0.64.1.25.2.16.3.43.5.12.7.29.10.0

and i want to read this file as integer to make a list like this
[1,4,9,16,25,36,49,64,81,100]
[0.01.0.08.0.27.0.64.1.25.2.16.3.43.5.12.7.29.10.0]

i got this error when i tried
with open('output.txt','r') as a:
    data = a.readlines()[0]

with open('output.txt','r') as a:
    data1 = a.readlines()[1]

intlist = []
intlist.append(data)

['1,4,9,16,25,36,49,64,81,100\n']
['0.01.0.08.0.27.0.64.1.25.2.16.3.43.5.12.7.29.10.0']

how can i fix it?

A: You made a whole process to make it a string delimited by ,s but haven't done the opposite way.
strlist = list(map(str,f))
strlist1 = list(map(str,g))

a = ','.join(strlist)
b = ','.join(strlist1)

strlist_as_int = [int(i) for i in a.split(',')]
strlist1_as_float = [float(i) for i in b.split(',')]

print(strlist_as_int)
print(strlist1_as_float)

output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[0.01, 0.08, 0.27, 0.64, 1.25, 2.16, 3.43, 5.12, 7.29, 10.0]

In order to make it a complete whole answer, sometimes (in real cases rather than synthetic ones), the lines can contain non-integer, or non-float elements, in such case the best practice is to error-handle the exception like in here:
def convert_int_with_try_except(num):
    try:
        converted_int = int(num)
        return converted_int
    except ValueError:
        return num

def convert_float_with_try_except(num):
    try:
        converted_float = float(num)
        return converted_float
    except ValueError:
        return num

strlist = list(map(str,f)) + ["not_an_int"]
strlist1 = list(map(str,g)) + ["not_a_float"]

a = ','.join(strlist)
b = ','.join(strlist1)

strlist_as_int = [convert_int_with_try_except(i) for i in a.split(',')]
strlist1_as_float = [convert_float_with_try_except(i) for i in b.split(',')]

print(strlist_as_int)
print(strlist1_as_float)

output - pay attention that "non-integer" and "non-float" appended to list:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 'not_an_int']
[0.01, 0.08, 0.27, 0.64, 1.25, 2.16, 3.43, 5.12, 7.29, 10.0, 'not_a_float']

A: First when writing the strlist1, use ',' as a delimiter to avoid confusion whether the dot is indicating decimal point or not.
file.write(','.join(strlist))
file.write('\n')
file.write(','.join(strlist1)) # <- note the joining str

and when you read the file back,
with open('output.txt','r') as a:
    data = list(map(int, a.readline().split(','))) # split by the delimiter and convert to int
    data1 = list(map(float, a.readline().split(','))) # same thing but to a float

print(data)
print(data1)

output:
~ python script.py
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[0.01, 0.08, 0.27, 0.64, 1.25, 2.16, 3.43, 5.12, 7.29, 10.0]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Install4j Uninstall Previous Installation does not show all screens from Uninstaller We have created a custom Welcome screen (Configurable banner form) to upgrade and remove application with the help of install4j.

We are providing radio button to remove an application using action Uninstall Previous Installation and we perform successful uninstall from this action, but my uninstall wizard consists few Screens, Actions and Display progress screens which are not displayed during uninstall process.\

How can we show the all these screens, actions to user which we have added in the uninstaller?

A: No, that is not possible. The "Uninstall previous installation" executes the uninstaller of the previous installation. If you have additional actions that are not contained in the previous uninstaller you have to add them to the "Welcome" screen and give them a condition expression of
context.isUpdateInstallation()

Similary, you can add screens that are only shown for an update installation.

A: As explained by Ingo,  Install4j execute the uninstaller of previous installer and it is not showing any screen to user.
We need to design custom screens for uninstall  previous installation hence added required screens with condition expression.

And this works for me. Thanks Ingo.


text:
Q: Getting wrong output while executing sizeof(char) My question is sizeof(char) is 1 byte but while executing below code why I am getting wrong output. Kindly help me. Thank you
typedef struct {

   int x;
   int y;

   char a;

}Point2D;

main() {
   Point2D *myPoint=malloc(sizeof(Point2D));
   NSLog(@"sizeof(Point2D): %zu", sizeof(Point2D));
}

Output: sizeof(Point2D) : 12 //But it should return 9 [int + int + char / 4 + 4 + 1]
Note: While running char individually , I am getting correct output
Example:
typedef struct {

   char a;

   char b;

}Point2D;

main() {

   Point2D *myPoint=malloc(sizeof(Point2D));

   NSLog(@"sizeof(Point2D): %zu", sizeof(char));

}

output: sizeof(char) : 2

A: You are not getting "wrong" output, when an (Objective-)C compiler lays out a struct it is allowed to use internal padding so that the fields start at the best memory alignment for their type.
If you need the size of a struct to be exactly the sum of its field sizes you can use __attribute__((__packed__)). E.g:
typedef struct
{
   int x;
   int y;
   char a;
} __attribute__((__packed__)) Point2D;

has a size of 9. However access to the fields may be slower due to the CPU having to deal with values not having optimal storage alignment.


text:
Q: pydev coverage: pytest and local pytest plugin running in two separate processes, talking over http All started here: https://github.com/pytest-dev/pytest-cov/issues/425
I can say by now that I have a working solution on my terminal, so when I run:
pytest --cov views --cov db --cov-report term-missing:skip-covered -sv

==================== test session starts ====================
platform darwin -- Python 3.7.6, pytest-5.4.3, py-1.9.0, pluggy-0.13.1 -- /usr/local/Caskroom/miniconda/base/bin/python
cachedir: .pytest_cache
rootdir: /Users/alan/myproject
plugins: xdist-1.33.0, forked-1.2.0, cov-2.10.0
collected 46 items

tests/test_admin.py::test_attempt_create_user PASSED
tests/test_auth.py::test_login_logout  * Serving Flask app "views" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
2020-09-03 18:26:26,157-INFO-werkzeug::_internal|113::  * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

PASSED
...
---------- coverage: platform darwin, python 3.7.6-final-0 -----------
Name                          Stmts   Miss  Cover   Missing
-----------------------------------------------------------
views/general.py                 52      2    96%   111, 113
views/helpers.py                 18     11    39%   10-14, 18-24
views/individual.py             218    113    48%   49-68, 74-125, 129-139, 145-155, 190, 336-382, 386-393, 400-428
views/save_configuration.py      34     23    32%   17-44
views/users.py                  128    104    19%   18-37, 52-90, 96-140, 144-155, 159-164, 168-173, 177-184
views/variant.py                 61      5    92%   34-36, 74-75
-----------------------------------------------------------
TOTAL                           985    258    74%

11 files skipped due to complete coverage.

I can see the coverage correctly reporting.
Now I'm trying to get that to work inside Eclipse/PyDev.
Essentially, when running Eclipse:Run:Run As:Python unit-test
Tests using my local pytest plugin (fix_api.py) will fail complaining basically that it waited for the application service to start and it timed out.
@pytest.fixture(scope="session")

    def app_server():

        with TestProcess("python", "application.py") as app_server:

>           wait_for_strings(app_server.read, 10, "Running")

../Programmes/myproject/tests/fix_api.py:17:

_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

cb = <bound method BufferingBase.read of TestProcess(pid=78818, is_alive=False)>

seconds = 10, strings = ('Running',), start = 1599149418.9482582

buff = '  File "/usr/local/Caskroom/miniconda/base/lib/python3.7/site.py", line 177\n    file=sys.stderr)\n        ^\nSyntaxError: invalid syntax\n'

check_strings = ['Running']

    def wait_for_strings(cb, seconds, *strings):

        """

        This checks that *string appear in cb(), IN THE GIVEN ORDER !

        """

        start = time.time()

        while True:

            buff = cb()

            check_strings = list(strings)

            check_strings.reverse()

            for line in buff.splitlines():

                if not check_strings:

                    break

                while check_strings and check_strings[-1] in line:

                    check_strings.pop()

            if not check_strings:

                return

            if time.time() - start > seconds:

                break

            time.sleep(0.05)

        raise AssertionError("Waited %0.2fsecs but %s did not appear in output in the given order !" % (

>           seconds, check_strings

        ))

E       AssertionError: Waited 10.00secs but ['Running'] did not appear in output in the given order !

/usr/local/Caskroom/miniconda/base/lib/python3.7/site-packages/process_tests.py:247: AssertionError

The most important feature for me is to be able to use the "Code Coverage" view in Eclipse and be able to quickly see the the code not covered.
If I can't make pytest with two separated processes to work for coverage, I was wondering how I could load the coverage.xml file for PyDev when running in my terminal, something like:
pytest --cov views --cov db --cov-report xml:coverage.xml -sv

Code Coverage view has this button "Open cov" but it does not do what I hoped it for, neither doing a "Refresh" loads from my local .coverage file.
So, if anyone could give any tip here on how to get it to work that would be highly appreciated.

A: On the PyDev side, code-coverage information is loaded from a specific directory.
In the code coverage view there's a Open cov dir (see picture below) where the coverage contents must be placed (I can see that PyDev sets --coverage_output_dir and --coverage_include -- https://github.com/fabioz/Pydev/blob/master/plugins/org.python.pydev.debug/src/org/python/pydev/debug/ui/launching/PythonRunnerConfig.java#L913 -- in the command line when you have set Enable code coverage for new launches? and already chose the dir to analyze, so, if you're running tests from inside PyDev it should work out of the box).
Now, if you run it from the terminal, you have to set those from the command line when running the test.
Files in the PyDev coverage directory are expected to be named: .coverage.<xxx> (then on Refresh PyDev will gather all the multiple files that start with .coverage. and will consolidate them in a single .coverage which will then be used to show coverage info inside of PyDev).
So, what you need to do is make it so that the generated coverage files are created in the proper place (which should be possible either running from PyDev or using the proper command line arguments to create the files in the PyDev coverage dir and manually refreshing later).


text:
Q: Should i use MongoTemplate or DBCollection when query data [Java Spring] At the moment, I'm using MongoTemplate to query data

*

*MongoTemplate --> return List
mongoTemplate.find(query, entity)

*DbCollection --> return DbCursor
dbCollection.find()
Then what should i use to best way

A: since your application is a spring application i would suggest to stick with mongotemplate as it is springframework provided class and can go along well with other spring features.
whereas DBcollection is a class from mongo API for java and there might be some cases where you have to play around to get your stuff done.


text:
Q: jquery/ajax is there a better way to post this data? Ok currently I'm creating a list that is generated from a database with the format below.
    echo '
';
    echo '

'.$value.'
▲ | ▼
'.$list.'
'.$description.'
'.$date.'
✗

';
   echo '
';

The spans with the class item1 and with class item6 I'm using urls to pass the (encrypted) id of the list to a seperate php site that gets the results and plugs them into a database.  It then uses javascript to redirect the user back to the original site so that you can see the changes.  This takes a small amount of time however and briefly blanks out the page while the script is working.  Is it possible to do this same functionality with some sort of jquery/ jquery ajax call to the script page?  My main concerns are that the id must be the one that I'm clicking on so that I'm not deleting or modifying other content.  Anyway, Thanks in advance for the help!
edit----
here is the script that catches the data
    $oldlistid = $_GET['id1'];

... some decryption stuff to make it $listid
$checkdb = $db->prepare('SELECT checkbox FROM list_simple WHERE LIST_ID=?');
$checkdb->execute(array($listid));
$row = $checkdb->fetch(PDO::FETCH_ASSOC);
$stmt = $db->prepare('UPDATE list_simple SET checkbox=? WHERE LIST_ID=?');
    if ($row['checkbox']) {

        $check = 0;
        $stmt->execute(array($check, $listid));
        echo '';
    }
    else {
        $check = 1;
        $stmt->execute(array($check, $listid));
        echo '';
    }

?>


text:
Q: Apple Production iOS Push Services certificate is not working for app distribution Push notification is working fine when I was using the development provisioning profile and development push certificate.
But when I have builded my app with adhoc provisioning profile inorder to do the distribution via testflightapp.
Person who install my app via the testflightapp didn't get any push notification. I also changed the push certification to production certification with the server.
I don't understand why the push notification is not working with my testflight distribution.
This is what I understand. If there is anything wrong please correct me.
   Apple Development iOS Push Services Certification use for development.

Push notification should works when the app was build with the development provisioning profile.
   Apple Production iOS Push Services Certification use for production and distribution.

Push notification should works when the app was build with the adhoc or appstore provisioning profile.

A: The device tokens are different between development and production, have you changed it?


text:
Q: How can I take objects from the second set of objects which don't exist in the first set of objects in fast way? I have records in two databases. That is the entity in the first database:
public class PersonInDatabaseOne
{
    public string Name { get; set; }
    public string Surname { get; set; }
}

That is the entity in the second database:
public class PersonInDatabaseTwo
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

How can I get records from the second database which don't exist in the first database (the first name and the last name must be different than in the first database). Now I have something like that but that is VERY SLOW, too slow:
List<PersonInDatabaseOne> peopleInDatabaseOne = new List<PersonInDatabaseOne>();
// Hear I generate objects but in real I take it from database:
for (int i = 0; i < 100000; i++)
{
    peopleInDatabaseOne.Add(new PersonInDatabaseOne { Name = "aaa" + i, Surname = "aaa" + i });
}

List<PersonInDatabaseTwo> peopleInDatabaseTwo = new List<PersonInDatabaseTwo>();
// Hear I generate objects but in real I take it from database:
for (int i = 0; i < 10000; i++)
{
    peopleInDatabaseTwo.Add(new PersonInDatabaseTwo { FirstName = "aaa" + i, LastName = "aaa" + i });
}
for (int i = 0; i < 10000; i++)
{
    peopleInDatabaseTwo.Add(new PersonInDatabaseTwo { FirstName = "bbb" + i, LastName = "bbb" + i });
}

List<PersonInDatabaseTwo> peopleInDatabaseTwoWhichNotExistInDatabaseOne = new List<PersonInDatabaseTwo>();

// BELOW CODE IS VERY SLOW:
foreach (PersonInDatabaseTwo personInDatabaseTwo in peopleInDatabaseTwo)
{
    if (!peopleInDatabaseOne.Any(x => x.Name == personInDatabaseTwo.FirstName && x.Surname == personInDatabaseTwo.LastName))
    {
        peopleInDatabaseTwoWhichNotExistInDatabaseOne.Add(personInDatabaseTwo);
    }
};

A: The fastest way is dependent on the number of entities, and what indexes you already have.

*

*If there's a few entities, what you already have performs better because multiple scans of a small set takes less than creating HashSet objects.

*If all of your entities fit in the memory, the best way is to build HashSet out of them, and use Except which is detailed nicely by @alex.feigin.

*If you can't afford loading all entities in the memory, you need to divide them into bulks based on the comparison key and load them into memory and apply the HashSet method repeatedly. Note that bulks can't be based on the number of records, but on the comparison key. For example, load all entities with names starting with 'A', then 'B', and so on.

*If you already have an index on the database on the comparison key (like, in your case, FirstName and LastName) in one of the databases, you can retrieve a sorted list from the database. This will help you do binary search (http://en.wikipedia.org/wiki/Binary_search_algorithm) on the sorted list for comparison. See https://msdn.microsoft.com/en-us/library/w4e7fxsh(v=vs.110).aspx

*If you already have an index on the database on the comparison key on both databases, you can get to do this in O(n), and in a scalable way (any number of records). You need to loop through both lists and find the differences only once. See https://stackoverflow.com/a/161535/187996 for more details.

A: Edit: with respect to the comments - using a real model and a dictionary instead of a simple set:
Try hashing your list into a Dictionary to hold your people objects, as the key - try a Tuple instead of a name1==name2 && lname1==lname2.
This will potentially then look like this:
// Some people1 and people2 lists of models already exist:
var sw = Stopwatch.StartNew();
var removeThese = people1.Select(x=>Tuple.Create(x.FirstName,x.LastName));
var dic2 = people2.ToDictionary(x=>Tuple.Create(x.Name,x.Surname),x=>x);
var result =  dic2.Keys.Except(removeThese).Select(x=>dic2[x]).ToList();
Console.WriteLine(sw.Elapsed);

I hope this helps.


text:
Q: wtpwebapps/myapp is empty when running Tomcat under Eclipse I know that tomcat is running because when I type http://localhost, the tomcat page dispay. My problem is I can't figure out why the wtpwebapps/myapp is empty, is like the eclipse doesn't publish it and when i type http://localhost/myapp, I get 404 error.
In the server overview :

*

*Server Location is set to "Use Tomcat installation" | server path: the servers's folder  | deploy path : wtpwebapps

*Server Option : Publish module contexts to separate XML file

*Publishing : Automatically publish when ressource change

I use eclipse Ganymede 3.4.2, tomcat 6.0, under Win7
Any help would be appreciated, thanks

A: your files must be somwhere, so start searching in:
<YOUR_WORKSPACE_DIR>\.metadata\.plugins\org.eclipse.wst.server.core\tmp<SOME_NUMBER>\wtpwebapps

A: I had a similar problem, when updating our project (.project and .classpath are checked in for convenience, but causes sometimes problems).
Console-Log in eclipse always says:
Error configuring application listener of class org.sth.ThisClass
java.lang.ClassNotFoundException: org.sth.ThisClass
The reason was that $WORKSPACE_DIR/.metadata/.plugins/org.eclipse.wst.server.core/tmp$NUMBER/wtpwebapps/$CONTEXT/WEB-INF/lib/classes was empty. The solution was to enter under Project Properties > Deployment Assembly an entry:
Source: /src
Deploy Path: WEB-INF/classes

A: If you use a Maven in your project, this is a solution for you:

*

*Delete the project(s) in the Eclipse.

*create project from Maven sources (select your workspace directory).

*Check found pom.xml to import.

Restart the Tomcat.

A: Try to look into servers explorer and it will show you what state is your application at and if its deployed.

A: Since I had difficulty finding where this "server overview" is, I like to add that you just double click on a server under the "servers" view.  I kept on right click and look at the "Properties" and was not getting to this information.


text:
Q: Getting Local File Path from imagePicker (iOS, Objective C) I am struggling to get the file path from imagePicker and sending it to the server.
This is the attempt to pass over the local path client-side:
NSData *webData = UIImagePNGRepresentation(info[UIImagePickerControllerOriginalImage]);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:@"test.png"];
[webData writeToFile:localFilePath atomically:YES];

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:url.absoluteString
   parameters:@{@"path": localFilePath}
     progress:nil
      success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
... //results always in error

This is the backend code snipped receiving the path key (in JavaScript):
var fs = require('file-system');

file {
 data: fs.readFileSync(path),
}

However, I always get errors like this:
Error: ENOENT: no such file or directory, open '/Library/Developer/CoreSimulator/Devices...
Is there a problem in my JS-Code? Or what other approach should I use to get the file path?
I'd be happy if someone could help me out here.
P.S. other popular existing StackOverflow answers on getting the file path induce the same error code.

A: It is not possible. You need to create a Data of that image and upload it using multipart to server.
I hope this link would work for you:
How to get UIImage from local url and post the image to server ?

A: Either I've misunderstood the question, or you're trying to do the impossible.
The path on your device (in this case the simulator) isn't accessible to the server, because it only exists on the device.
If you want to pass the actual image across, you need to send the data itself in the request, you can't have the server get it's path and reach over the internet into the device to get it.
The accepted answer to this question is an example of how to attach the image's data to an AFNetworking request. Unfortunately, I don't know enough about the server to help much there but I'd expect you to be able to get it the same way you got your path out of the request, it would just the the raw image data instead of a file path.


text:
Q: Reload Collection View in a Collection View Cell through delegation I have a controller (A) with a Collection View that features 2 cell classes. One of them (B) contains another Collection View. After doing some research, I still cannot figure out how to update the cells in (B) from (A) or elsewhere to get what I want.
Issues
(B) does not reload properly when its button is pressed: the cell with whom the button was tied is still visible even though it is deleted from the userFriendRequests array in (A) in its delegate method. As a bonus I get a crash when I scroll to a new cell in (B) stating that "index is out of range" on the line cell.user = userFriendRequests[indexPath.row].
What I Have
Controller (A)
protocol UserFriendRequestsDelegate: class {

func didPressConfirmFriendButton(_ friendId: String?)
}

/...

fileprivate var userFriendRequests = [User]()

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if userFriendRequests.isEmpty == false {

        switch indexPath.section {

        case 0:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: friendRequestCellId, for: indexPath) as! UserFriendRequests
            cell.userFriendRequests = userFriendRequests
            cell.delegate = self
            return cell
        case 1:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! UserFriendCell
            let user = users[indexPath.row]
            cell.user = user
            return cell
        default:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! UserFriendCell
            return cell
        }
    }

/...

extension AddFriendsController: UserFriendRequestsDelegate {

internal func didPressConfirmFriendButton(_ friendId: String?) {

    guard let uid = FIRAuth.auth()?.currentUser?.uid, let friendId = friendId else {
        return
    }

    let userRef = FIRDatabase.database().reference().child("users_friends").child(uid).child(friendId)
    let friendRef = FIRDatabase.database().reference().child("users_friends").child(friendId).child(uid)
    let value = ["status": "friend"]

    userRef.updateChildValues(value) { (error, ref) in

        if error != nil {
            return
        }

        friendRef.updateChildValues(value, withCompletionBlock: { (error, ref) in

            if error != nil {
                return
            }

            self.setUpRequestsStatusesToConfirmed(uid, friendId: friendId)

            DispatchQueue.main.async(execute: {

                let index = self.currentUserFriendRequests.index(of: friendId)

                self.currentUserFriendRequests.remove(at: index!)

                for user in self.userFriendRequests {

                    if user.id == friendId {

                        self.userFriendRequests.remove(at: self.userFriendRequests.index(of: user)!)
                    }
                }
                self.attemptReloadOfCollectionView()
            })
        })
    }
}

PS: self.attemptReloadOfCollectionView() is a func that simply invalidates a timer, sets it to 0.1 sec and then calls reloadData() on (A)'s Collection View.
CollectionViewCell (B)
weak var delegate: UserFriendRequestsDelegate?
var userFriendRequests = [User]()

/...

@objc fileprivate func confirmFriendButtonPressed(_ sender: UIButton) {

    delegate?.didPressConfirmFriendButton(friendId)
}

/...

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return userFriendRequests.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: friendRequestCellId, for: indexPath) as! FriendRequestCell

    cell.user = userFriendRequests[indexPath.row]

    return cell
}

/...

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {

    guard let firstName = userFriendRequests[indexPath.row].first_name, let lastName = userFriendRequests[indexPath.row].last_name, let id = userFriendRequests[indexPath.row].id else {
        return
    }

    nameLabel.text = firstName + " " + lastName
    friendId = id
    confirmButton.addTarget(self, action: #selector(confirmFriendButtonPressed(_:)), for: .touchUpInside)
}

What I want to achieve
Update (B) when a User is removed from the userFriendRequests array in (A), this User being identified by his id passed by (B) through delegation.
Any good soul that might have an idea on how to tackle this issue ?
Thanks in advance for your help !


text:
Q: Android Programatically Close Out App1 and Start App2 from App1 My app needs to close itself out but before doing so initiate the startup of another app.  What is the best way to 1) issue startup request of second app (via broadcast or just startup activity), and 2) what is the best way to close out the first app.  Finish comes to mind but I want to close out the whole app and not just the current activity.  Thanks

A: Just before closing your application you can fire an intent like this
Intent intent = new Intent(this, package name of application 2);
startAcvity(intent);

this will launch application 2 via an intent call.
as for closing application 1 goes have a look at the following link
Finish sub activities programmatically

A: Try this code
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent res = new Intent();
/* Another App Package name*/
String mPackage = "com.ReachOut";
/* Class name */
String mClass = ".splash1";
res.setComponent(new ComponentName(mPackage,mPackage+mClass));
startActivity(res);
}
});
&  here u want to finish() your first App Activity .


text:
Q: Sumproduct with max condition in excel I have this formula but it's not working
=SUMPRODUCT(--(NUMBERVALUE(RIGHT(Sheet1!A:A,2))=MAX(NUMBERVALUE(Sheet1!A:A,2))),--(Sheet1!AG:AG=A9),(Sheet1!AA:AA))

My problem is in the first section array of the sumproduct
NUMBERVALUE(RIGHT(Sheet1!A:A,2))=MAX(NUMBERVALUE(Sheet1!A:A)))

The column A contain the below kind of values:
Till_Date
2016/10
2016/10
2016/11
2016/11
2016/12
2016/8

etc..
For each row, I want to set a condition on the month if it is the last month in the whole column, so the idea is to get the max of the right 2 digits and for each row compare right 2 digits with the max value of the whole columns.
However it is not working, feeling that im so close to fix it but could not locate the problem
Any assistance would be much much appreciated.
Thanks in advance
Georges Sabbagh

A: I don't think you are very close to the solution.

*

*From "2016/8" what do you think, the rightmost 2 digits will be?

*Even NUMBERVALUE will result in #VALUE error in cell A1 = "Till_Date" - rightmost 2 = "te"

*In your MAX(NUMBERVALUE(Sheet1!A:A)) NUMBERVALUE will result in #VALUE error for each cell in A1:A7 since all are text. So MAX is #VALUE error also.

Problem 1 is solvable by calculating the position of the "/" and taking the number after that.
Problems 2 and 3 are solvable only by excludig the errors. But IFERROR does not work within the matrix context produced by SUMPRODUCT. For this a real array formula is needed.
So maybe
{=SUM(IF(IFERROR(--RIGHT(Sheet1!A:A,LEN(Sheet1!A:A)-FIND("/",Sheet1!A:A)),0)=MAX(IFERROR(--RIGHT(Sheet1!A:A,LEN(Sheet1!A:A)-FIND("/",Sheet1!A:A)),0)),IF(Sheet1!AG:AG=A9,Sheet1!AA:AA)))}

will work for you.
This is an array formula. Input it into the cell without the curly brackets and press [Ctrl]+[Shift]+[Enter] to confirm. The curly brackets will then appear automatically.
Using the whole Sheet1!A:A range this will be of very bad performance. So you should shrink the range. Sheet1!$A$1:$A$10000 for example. Same with Sheet1!$AG$1:$AG$10000 and Sheet1!$AA$1:$AA$10000.


text:
Q: Query using LIKE '% term %' is very slow I have a InnoDB table, about 1,000,000 rows:
Data            164.7   MiB
Index           250.1   MiB
Overhead        168.0   MiB
Effective       246.8   MiB
Total           414.8   MiB

Table structure:
CREATE TABLE IF NOT EXISTS `gift` (
  `tm` varchar(15) NOT NULL,
  `col` smallint(2) NOT NULL,
  `myindex` varchar(255) NOT NULL,
  `date` int(10) NOT NULL,
  KEY `tm` (`tm`),
  KEY `date` (`date`),
  KEY `myindex` (`myindex`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

tm is a un-duplicate string generated by PHP (products id),
date store use strtotime('now'),
myindex store search keywords
because some products have long descriptions(more than 255 characters), so col is separate long descriptions with many parts (the same products,  keywords part 1, keywords part 2...).
A query like this will make (10 total, Query took 51.0829 sec)
SELECT *
FROM gift
WHERE myindex LIKE  '% keywords1 %'
AND myindex LIKE  '% keywords2 %'
GROUP BY tm
ORDER BY DATE DESC
LIMIT 10

make an explain, that get:
id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE      gift    index   NULL            date    4   NULL 10 Using where; Using temporary

possible_keys is null, Have I made a bad index? How to make it fastest?
here is my.cnf, my server has 4GB ram, mysql also support fulltext search.
And I tried set key_buffer_size and innodb_buffer_pool_size to 512MB, but the server would easly crash down with warning apache child process still did not exit sending a sigterm. Must I left at least 1GB ram for system and apache? (Only about 2.5-3GB for my.cnf?)
[mysqld]
character_set_server=utf8
port        = 3306
socket      = /var/lib/mysql/mysql.sock
skip-external-locking
skip-networking
key_buffer = 256M
tmp_table_size = 64M
max_connections = 300
wait_timeout=15
back_log = 2048
key_buffer_size = 384M
max_allowed_packet = 2M
table_cache = 2048
table_open_cache = 2048
sort_buffer_size = 6M
read_buffer_size = 4M
net_buffer_length = 92K
read_rnd_buffer_size = 4M
myisam_sort_buffer_size = 256M
thread_cache = 384
query_cache_size= 256M
bulk_insert_buffer_size = 192M
ft_min_word_len=2
skip-networking

binlog_format=mixed

innodb_buffer_pool_size = 384M
innodb_buffer_pool_instances=4

innodb_use_sys_malloc = 0

[mysqldump]
quick
max_allowed_packet = 8M

[mysql]
no-auto-rehash

[myisamchk]
key_buffer_size = 96M
sort_buffer_size = 96M
read_buffer = 3M
write_buffer = 3M

A: Your actual problem is that it is not possible for MySQL to use an index for a condition such as myindex LIKE  '% keywords1 %'. This topic is covered far and wide on the web, so I'd suggest you look for full-text indexing solution. You can use either one internal (indexes in MySQL) or external (Sphinx, Lucene, etc.).

A: First of all, you are using an illegal grouping. check first paragraph of http://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html
Second, seems like the group by is not even necessary, and is causing your 'temporary' to show in explain
Third,(don't quote me o nthis, not 100% sure) your temorary tmp_table_size = 64M may be  too small for this query alone, as it stores the filtered results in memory before grouping
4th, if you do need to group, assign an integer to that string, and group on integer.
5th, if you have keywords, store them in an item-keyword table, and use them with a join. Will give you some performance hit due to the join, but it will allow you to use an index. Indexes only come into play when you are comparing strings from the beginning (hence using a length 6-10 index on varchar might be just as effective as using a 100 length index)
happy optimising :)


text:
Q: Parse - Xcode - Using data from a Query outside of the Query I am fairly new to Swift and Parse. I am having trouble with queries. I cannot get my list pickerData to contain the data provided from my query. With this issue, I cannot push information to a picker I have set up
These are my declared variables:
    var users = [PFObject]() //array to hold users
    var pickerData: [String] = [String]() //array to hold picker items

And here is where my issue arises:
    override func viewDidLoad() {
        super.viewDidLoad()

        self.AssignToPicker.delegate = self
        self.AssignToPicker.dataSource = self

        // Do any additional setup after loading the view.

        let query = PFUser.query()
        query?.findObjectsInBackground(block: { users, error in
            if users != nil{
                self.users = users!
                for user in self.users {
                    self.pickerData.append(user["username"] as! String)
                }
                print("Printing contents of pickerData INSIDE of query:")
                for item in self.pickerData {
                    print(item)
                }
            }
        })

        print("printing content of pickerData outside of query:")
        for item in self.pickerData {
            print(item)
        }
    }

The for loop within my query provides me with the correct information. The for loop outside of my query provides me with nothing. If I were to set pickerData as such
pickerData = ["name1", "name2"] everything would be working perfectly. But as it is now, when I load my pickerData within the query, it seems to be erased after I leave it
The essence of my question is how do I get this query information to save outside of the findObjectsInBackgroundmethod?

A: the findObjectsInBackground method happens asynchronous with the rest of the file. This means that it kind of lags behind everything else. The data that you set inside the query is only ready at the end of the compilation of the file. This means when you try to do
for item in self.pickerData {
            print(item)
        }

outside of your query, pickerData has not yet been populated.
The is a synchronous option out there but I'm not sure if it is beneficial to your subject
let query = PFQuery(className: "yourClassName")
do {
    //synchronous
    let item = try query.getObjectWithId(yourIdHere)
} catch {
    print("error")
}

This query happens synchronously. The data you save in item can be used immediately afterward


text:
Q: Boot Camp Windows 10 not connecting to Magic Mouse 1 A week or so ago I installed Windows 10 on my 2015 MacBook Pro Retina with Boot Camp. At the start my Magic Mouse 1 and my keyboard were already paired. Today my mouse wouldn't click for some reason so I unpaired the mouse, now the mouse won't pair. In the Windows 10 Control Panel I don't see any drivers that aren't installed. I already tried restarting my laptop and turning the mouse off and back on.
Whenever I try pairing the mouse I get an pop-up from windows saying it can't find the mouse anymore and asks me to try this again. I just finished installing all my programs, I really don't want to do that again.
Anyone knows how to solve this issue?

A: So far, I learned from experimenting and the blogs: I have to REMOVE (not just DISCONNECT) the Bluetooth mouse in Mac OS X, before I can pair it in BootCamp Windows. Since this is not comfortable enough, I'm not fully done yet.
After another entire day of fumbling around in blogs, Apple sites and the machine itself, it seems to work.
1st of all, I have to correct myself - the mouse is an Apple Bluetooth MIGHTY Mouse (not a MAGIC one). Sorry for the wrong place - there is not much word about the Mighty in the blogs.
The machine is a late 2006 MBP15 (2,2 A1211). The Mac OS X is a Lion, the BootCamp is 4.0.4 running Windows 10. Apple doesn't support this combo. They don't provide Windows Support Software for it either (the download attempt through BootCamp Assistant fails). So I'm in fact on my own.
Having eventually learned that, I decided to UNPAIR (not REMOVE) the mouse in Mac OS X, before I switched to Windows 10. In Windows 10, I managed to pair it within the Bluetooth Preference window. However, the transition had switched the mouse OFF, so I had to switch it OFF/ON again. And, I had to toggle the Bluetooth switch in the Preference window; otherwise the radio wouldn't at all search for the mouse! I think that I even had to click the mouse - but I'm not sure about that. Anyway - the mouse worked than, and I could open the Device Manager to check the Bluetooth entries and the Mouse entries. (With the mouse, the Bluetooth entry has to have 2 extra sub-entries, while the Mouse entry has to have just one extra sub-entry.)
From there, I could switch to Mac OS X. Of course, the mouse was dead, but I could pair it after having switched it OFF/ON and clicked to make it alive.
For the return to Windows 10 I could keep it paired. Arriving in Windows 10, I had just to switch the mouse OFF/ON and click to make it work.
I'm going to test this for a while - happy that there is no need for additional drivers.

A: Kinda late to the party, I know, but having just encountered this problem myself, and solving it using Mike6's convoluted answer, figured I would describe it to you in layman's terms.
If you are having difficulty connecting your Apple mouse to your MAC OS X with Bootcamp Windows 10 installed:

*

*Remove the device from your MAC OS X's paired devices. This does not mean just Disconnect the device, go into the Bluetooth preferences and REMOVE the device from your list of paired devices (click on the "x" next to the device in that screen and UNPAIR your device).

*Make sure your device is turned On.

*Load up Bootcamp. Navigate over to your Bluetooth Devices and "Add Bluetooth or other device". Select "Bluetooth" from the box that pops open. Select your device. The device should now connect.
*Side note: Your mouse may have a more generic name, such as "Mouse", when searching for it in Bootcamp's Bluetooth Devices (after you've removed it from MAC OS X's paired devices), this is still your mouse, select it and connect.

A: You would think the pairing on macOS wouldn't have anything to do with the pairing in Windows 10 since they are two different OSs on different partitions, but this is not true. I guess it has to do with how the Mac pairs with the bluetooth mouse on a hardware level.
Solution is to:

*

*Go to macOS's Settings and Bluetooth Options

*Remove Magic Mouse by clicking the x button

*Reboot into Bootcamp

*You should now be able to pair it on Windows.

*When you go back to MacOS it will ask you to reconnect to the Magic Mouse and you won't lose it again on the Windows

This works for Late 2016 Macbook Pro Retina with Touchbar, Mac OS High Sierra, Windows 10 1709 (Fall Creators Update)


text:
Q: SQL Alchemy selecting data I'm trying to do a group by + count with a weather stations table to answer the following questions:
What are the most active stations? (i.e. what stations have the most rows)?
List the stations and the counts in descending order
The table consists of the following values:
id INTEGER
station TEXT
date TEXT
prcp FLOAT
tobs FLOAT
This is my current formulation of the select statement:
sel = [Measurement.station, func.count(Measurement.id)]
count = session.query(*sel).all()

count

A: As you mention, a GROUP BY clause needs to be applied to that query. This can be easily done in sqlalchemy: count = session.query(*sel).group_by(Measurement.station).all().


text:
Q: Default settings for Inkscape ? I want to take default settings for Inkcape in my Ubuntu 14.04 but I can't change by default setting.
I already remove Inkscape, and re-install, but the configurations keep the same.
How can I change by default all setting in Inkscape?

A: To remove inkscape and all its settings do:
sudo apt-get remove --purge inkscape

If this dosn't work look in your home folder, show hidden files, look for ~/.config/inkscape that folder should contain your users settings so you can transfer and/or delete those settings.

A: The Templates that Inkscape(Debian&co/Linux) use are bound to your locale-setting and are stored at: /usr/share/inkscape/templates/ for system wide configuration.
E.g. for me, the template default.de.svg has to be overwritten, as root, as i need it.

A: Update for readers using Inkscape 1.x.
First open preferences with Ctrl+Shift+P.
Now you can reset the user preferences here:


text:
Q: Why doesn't SaveChanges detect changes to a entity? I have a .Net Mvc projekt where i have a problem with my Databasecontext. More specific with update/saveChanges. When i am debugging the code with a debug point in the method(below) it seams to work but not without a debug point. I can´t understand why? Somehow the SaveChanges doesn't detect the changes to entity.
var user = DatabaseContext.Users.Single(u => u.Id == userId && u.Newsdesk.Id == newsdeskId);
user.Newsdesk = null;
DatabaseContext.Update(user);
DatabaseContext.SaveChanges();

My update method in DatabaseContext looks like this:
public T Update<T>(T entity) where T : class
    {
        var set = Set<T>().Attach(entity);
        Entry(entity).State = EntityState.Modified;
        return set;
    }

If someone could point me in the right direction i would be very grateful

A: Quickly in and quickly out (that's what Gandalf said in one of the movies... :) I think).
By that I mean that if some godly observer were sitting inside the CPU looking at your app,
what they should see is that your app runs the following sequence
{ connect, create context, make changes, commit them, destroy context, disconnect }
in a number of tens of milliseconds for (almost) each web request it receives.
Are you actually creating a context (entity container + unit of work)
that exists throughout the app globally ?
I would recommend a more classical and not-so-dbconnection-friendly approach (not to mention transactionally-sanitized):
using (var context = DataContextHelper.CreateContext()) {
    var user = DataContextHelper.QueryAndSingleByLambdaBasedOnContext(
        context,
        u => u.Id == userId && u.Newsdesk.Id == newsdeskId
    );
    if (null == user)
       // complain somehow (by exception or special return value)
    user.Newsdesk = null;

    // don't mark it anymore, in the straight-forward, good'ol way
    // user will already have been marked
    //DatabaseContext.Update(user);

    context.SaveChanges();
}

It is generally bad (especially if you're not careful) to somehow host
a globally accessible context, that more than one thread can use concurrently.
I'm not talking about concurrency hazards while accessing some property.
I'm talking about the big picture
(maybe another request read the user and marked it as "not being modified" somewhere
between your Update and the SaveChanges).
Event if that's not the case, you shouldn't worry about concurrent connections to the db.
Concurrent access to the context is much harder to manage.


text:
Q: How to call an a 2D Array (Matrix) In a Soap WebService I am stuck in calling an Array of Type  double[][] in a Soap Webservice. Actually, I have configured my Soap Webservice at my glass fish and it is generating randomly two Arrays (Matrices), then multiply both the matrices and return the resulted matrix (2D Array). I am stuck in how to call the Array from Client. I can call any string or int value but dunt know how to call an array. The Webservice sucessfully generate the Matrices and then Multiply both. I have tested it in  http://172.25.181.23:8080/TestWebService/ResourceClassService?Tester
here is the browser test result:
matrixMulti Method invocation

Method parameter(s)

Type    Value
int
10
int
10
Method returned

java.util.List : "[org.moeez.javabrains.ModelClass@96c762]"
SOAP Request

<?xml version="1.0" encoding="UTF-8"?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Header/>
    <S:Body>
        <ns2:MatrixMulti xmlns:ns2="http://javabrains.moeez.org/">
            <arg0>10</arg0>
            <arg1>10</arg1>
        </ns2:MatrixMulti>
    </S:Body>
</S:Envelope>
SOAP Response

<?xml version="1.0" encoding="UTF-8"?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Header/>
    <S:Body>
        <ns2:MatrixMultiResponse xmlns:ns2="http://javabrains.moeez.org/">
            <return>
                <result>
                    <item>16675.0</item>
                    <item>23888.0</item>
                    <item>31099.0</item>
                    <item>18575.0</item>
                    <item>17015.0</item>
                    <item>30272.0</item>
                    <item>26010.0</item>
                    <item>21229.0</item>
                    <item>14888.0</item>
                    <item>24212.0</item>
                </result>
                <result>
                    <item>25347.0</item>
                    <item>28895.0</item>
                    <item>39055.0</item>
                    <item>20141.0</item>
                    <item>24993.0</item>
                    <item>34906.0</item>
                    <item>30242.0</item>
                    <item>30895.0</item>
                    <item>20351.0</item>
                    <item>26011.0</item>
                </result>
                <result>
                    <item>12012.0</item>
                    <item>24454.0</item>
                    <item>28071.0</item>
                    <item>14582.0</item>
                    <item>18386.0</item>
                    <item>23981.0</item>
                    <item>21852.0</item>
                    <item>22986.0</item>
                    <item>13975.0</item>
                    <item>21444.0</item>
                </result>
                <result>
                    <item>15691.0</item>
                    <item>28936.0</item>
                    <item>29329.0</item>
                    <item>16119.0</item>
                    <item>20362.0</item>
                    <item>30584.0</item>
                    <item>29399.0</item>
                    <item>27267.0</item>
                    <item>20573.0</item>
                    <item>29378.0</item>
                </result>
                <result>
                    <item>15118.0</item>
                    <item>27503.0</item>
                    <item>29980.0</item>
                    <item>11625.0</item>
                    <item>20176.0</item>
                    <item>31631.0</item>
                    <item>24869.0</item>
                    <item>24998.0</item>
                    <item>15587.0</item>
                    <item>33234.0</item>
                </result>
                <result>
                    <item>24949.0</item>
                    <item>34045.0</item>
                    <item>40347.0</item>
                    <item>20842.0</item>
                    <item>27634.0</item>
                    <item>40127.0</item>
                    <item>38795.0</item>
                    <item>34945.0</item>
                    <item>24957.0</item>
                    <item>33485.0</item>
                </result>
                <result>
                    <item>15731.0</item>
                    <item>21584.0</item>
                    <item>27399.0</item>
                    <item>19865.0</item>
                    <item>13156.0</item>
                    <item>28831.0</item>
                    <item>24961.0</item>
                    <item>15857.0</item>
                    <item>21462.0</item>
                    <item>21472.0</item>
                </result>
                <result>
                    <item>25052.0</item>
                    <item>29964.0</item>
                    <item>34718.0</item>
                    <item>19675.0</item>
                    <item>24144.0</item>
                    <item>35858.0</item>
                    <item>31764.0</item>
                    <item>32143.0</item>
                    <item>19417.0</item>
                    <item>32549.0</item>
                </result>
                <result>
                    <item>15470.0</item>
                    <item>26586.0</item>
                    <item>24474.0</item>
                    <item>15548.0</item>
                    <item>17297.0</item>
                    <item>29695.0</item>
                    <item>26752.0</item>
                    <item>26596.0</item>
                    <item>18556.0</item>
                    <item>22777.0</item>
                </result>
                <result>
                    <item>14608.0</item>
                    <item>28779.0</item>
                    <item>30670.0</item>
                    <item>10239.0</item>
                    <item>18995.0</item>
                    <item>30324.0</item>
                    <item>26900.0</item>
                    <item>26970.0</item>
                    <item>18125.0</item>
                    <item>34044.0</item>
                </result>
            </return>
        </ns2:MatrixMultiResponse>
    </S:Body>
</S:Envelope>

When I am testing it from android device, it is giving an error as below:
ava.lang.ClassCastException: org.ksoap2.serialization.SoapObject cannot be
cast to org.ksoap2.serialization.SoapPrimitive
07-31 17:53:37.983  12082-12140/com.example.mushtaqali.offloadwithsoap
W/System.err﹕ at
com.example.mushtaqali.offloadwithsoap.MainActivity$MyTask.doInBackground

(MainActivity.java:115)
07-31 17:53:37.983  12082-12140/com.example.mushtaqali.offloadwithsoap
W/System.err﹕ at
com.example.mushtaqali.offloadwithsoap.MainActivity$MyTask.doInBackground
(MainActivity.java:80)
07-31 17:53:37.983  12082-12140/com.example.mushtaqali.offloadwithsoap
W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-31 17:53:37.983  12082-12140/com.example.mushtaqali.offloadwithsoap
W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-31 17:53:37.983  12082-12140/com.example.mushtaqali.offloadwithsoap
W/System.err﹕ at
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-31 17:53:37.983  12082-12140/com.example.mushtaqali.offloadwithsoap
W/System.err﹕ at
java.util.concurrent.ThreadPoolExecutor.runWorker
(ThreadPoolExecutor.java:1112)
07-31 17:53:37.983  12082-12140/com.example.mushtaqali.offloadwithsoap
W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run
(ThreadPoolExecutor.java:587)
07-31 17:53:37.983  12082-12140/com.example.mushtaqali.offloadwithsoap
W/System.err﹕ at java.lang.Thread.run(Thread.java:818)

I am going to attach my Client Codes here.
package com.example.mushtaqali.offloadwithsoap;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.ksoap2.transport.HttpTransportSE;

import android.annotation.SuppressLint;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;

public class MainActivity extends Activity {

    private static String SOAP_ACTION1 = "http://javabrains.moeez.org/MatrixMulti";
    private static String NAME_SPACE = "http://javabrains.moeez.org/";
    private static String METHOD_NAME1 = "MatrixMulti";
    private static String URL = "http://172.25.181.23:8080/TestWebService/ResourceClassService";

    Button enter, clr;
    TextView tv1, tv2, tv3;
    EditText et1, et2;
    private String re;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        clr = (Button) findViewById(R.id.button2);
        enter = (Button) findViewById(R.id.button);
        tv1 = (TextView) findViewById(R.id.textView);
        tv2 = (TextView) findViewById(R.id.textView2);
        tv3 = (TextView) findViewById(R.id.textView3);
        et1 = (EditText) findViewById(R.id.editText);
        et2 = (EditText) findViewById(R.id.editText2);

        enter.setOnClickListener(new View.OnClickListener() {

            @SuppressLint("ShowToast")
            @Override
            public void onClick(View view) {

                MyTask mytask = new MyTask(et1.getText().toString(), et2.getText().toString());
                mytask.execute();

            }
        });

        clr.setOnClickListener(new View.OnClickListener()

        {

            @SuppressLint("ShowToast")
            public void onClick(View v) {
                et1.setText("");
                et2.setText("");
                tv1.setText("");
                et1.requestFocus();
            }

        });

    }

    class MyTask extends AsyncTask<Void, Void, SoapPrimitive> {

        private final String a;
        private final String b;

        MyTask(String a, String b) {

            this.a = a;
            this.b = b;

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected SoapPrimitive doInBackground(Void... voids) {

            SoapObject request = new SoapObject(NAME_SPACE, METHOD_NAME1);
            request.addProperty("arg0", a);
            request.addProperty("arg1", b);

            SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            soapEnvelope.dotNet = false;
            soapEnvelope.setOutputSoapObject(request);

            HttpTransportSE aht = new HttpTransportSE(URL);

            SoapPrimitive resultString = null;

            try {
                aht.call(SOAP_ACTION1, soapEnvelope);
                resultString = (SoapPrimitive) soapEnvelope.getResponse();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return resultString;
        }

        @Override
        protected void onPostExecute(SoapPrimitive resultString) {
            //super.onPostExecute(result);
            if(resultString!=null)
            tv1.setText(resultString.toString());

        }

    }
}

Please suggest how to call this array/ what to add in my codes to call it. Thanks


text:
Q: Connect GPON to my home fiber network Next year, FTH will be available to me. If I understand correctly, a GPON is used to convert the signal to ethernet, which can go to my router.
However, I'm in the process of replacing my CAT6 wiring to OM4 optical cabling, and now I am confused on how I need to connect the FTH to my network. I don't want to convert to ethernet anymore. Are there GPON's that can convert the signal from the ONT to a "normal" multimode LC connection instead of an ethernet connection?

A:
If I understand correctly, a GPON is used to convert the signal to ethernet, which can go to my router.

GPON is the signal, or rather it is the optical network that delivers the signal to you.
The converter for GPON is called either an "ONT" (optical network terminal) or I think an "ONU"? depending on manufacturer.
Also, an ONT does slightly more than just convert the raw signal; it has to actually coordinate with the OLT at the base to avoid colliding with all the other ONTs (i.e. other nearby customers) connected to the same PON, as well as to authenticate you (and get the decryption keys).
(This is in contrast to Ethernet media converters, which do indeed just put the same Ethernet signal on a different medium. Some ISPs actually use Ethernet as their FTTH protocol, but GPON is more common.)

Are there GPON's that can convert the signal from the ONT to a "normal" multimode LC connection instead of an ethernet connection?

A "normal" multimode LC connection would still be Ethernet. There are a few other networks that run over fiber, but for building a general-purpose home LAN that uses IP networking, you'll almost certainly be using not Infiniband and not Fibre Channel, but Ethernet over that OM4.
GPON, meanwhile, is not Ethernet – due to being a passive network with many customers sharing the same fiber it has its own specific signalling that really needs an ONT to be present.
Also, many GPON-using ISPs will insist that you use their ONT specifically (partly because such devices aren't entirely compatible across manufacturers), so likely you won't have much of a choice but to use the ONT that you were issued, which will have only copper Ethernet ports most of the time.
So the easiest option is to plug your ONT into an RJ45 port of an Ethernet switch (or media converter), with your OM4 fiber being connected to an SFP port of the same Ethernet switch (or media converter).


text:
Q: Import CSV file as a Pandas DataFrame How do I read the following CSV file into a Pandas DataFrame?
Date,"price","factor_1","factor_2"
2012-06-11,1600.20,1.255,1.548
2012-06-12,1610.02,1.258,1.554
2012-06-13,1618.07,1.249,1.552
2012-06-14,1624.40,1.253,1.556
2012-06-15,1626.15,1.258,1.552
2012-06-16,1626.15,1.263,1.558
2012-06-17,1626.15,1.264,1.572

A: import pandas as pd
df = pd.read_csv('/PathToFile.txt', sep = ',')

This will import your .txt or .csv file into a DataFrame.

A: To read a CSV file as a pandas DataFrame, you'll need to use pd.read_csv.
But this isn't where the story ends; data exists in many different formats and is stored in different ways so you will often need to pass additional parameters to read_csv to ensure your data is read in properly.
Here's a table listing common scenarios encountered with CSV files along with the appropriate argument you will need to use. You will usually need all or some combination of the arguments below to read in your data.
┌───────────────────────────────────────────────────────┬───────────────────────┬────────────────────────────────────────────────────┐
│ pandas Implementation                                 │ Argument              │ Description                                        │
├───────────────────────────────────────────────────────┼───────────────────────┼────────────────────────────────────────────────────┤
│ pd.read_csv(..., sep=';')                             │ sep/delimiter         │ Read CSV with different separator¹                 │
│ pd.read_csv(..., delim_whitespace=True)               │ delim_whitespace      │ Read CSV with tab/whitespace separator             │
│ pd.read_csv(..., encoding='latin-1')                  │ encoding              │ Fix UnicodeDecodeError while reading²              │
│ pd.read_csv(..., header=False, names=['x', 'y', 'z']) │ header and names      │ Read CSV without headers³                          │
│ pd.read_csv(..., index_col=[0])                       │ index_col             │ Specify which column to set as the index⁴          │
│ pd.read_csv(..., usecols=['x', 'y'])                  │ usecols               │ Read subset of columns                             │
│ pd.read_csv(..., thousands='.', decimal=',')          │ thousands and decimal │ Numeric data is in European format (eg., 1.234,56) │
└───────────────────────────────────────────────────────┴───────────────────────┴────────────────────────────────────────────────────┘

Footnotes

*

*By default, read_csv uses a C parser engine for performance. The C parser can only handle single character separators. If your CSV has
a multi-character separator, you will need to modify your code to use
the 'python' engine. You can also pass regular expressions:
 df = pd.read_csv(..., sep=r'\s*\|\s*', engine='python')

*UnicodeDecodeError occurs when the data was stored in one encoding format but read in a different, incompatible one. Most common
encoding schemes are 'utf-8' and 'latin-1', your data is likely to
fit into one of these.

*header=False specifies that the first row in the CSV is a data row rather than a header row, and the names=[...] allows you to
specify a list of column names to assign to the DataFrame when it is
created.

*"Unnamed: 0" occurs when a DataFrame with an un-named index is saved to CSV and then re-read after. Instead of having to fix the
issue while reading, you can also fix the issue when writing by using
 df.to_csv(..., index=False)

There are other arguments I've not mentioned here, but these are the ones you'll encounter most frequently.

A: pandas.read_csv to the rescue:
import pandas as pd
df = pd.read_csv("data.csv")
print(df)

This outputs a pandas DataFrame:
        Date    price  factor_1  factor_2
0  2012-06-11  1600.20     1.255     1.548
1  2012-06-12  1610.02     1.258     1.554
2  2012-06-13  1618.07     1.249     1.552
3  2012-06-14  1624.40     1.253     1.556
4  2012-06-15  1626.15     1.258     1.552
5  2012-06-16  1626.15     1.263     1.558
6  2012-06-17  1626.15     1.264     1.572

A: Here's an alternative to pandas library using Python's built-in csv module.
import csv
from pprint import pprint
with open('foo.csv', 'rb') as f:
    reader = csv.reader(f)
    headers = reader.next()
    column = {h:[] for h in headers}
    for row in reader:
        for h, v in zip(headers, row):
            column[h].append(v)
    pprint(column)    # Pretty printer

will print
{'Date': ['2012-06-11',
          '2012-06-12',
          '2012-06-13',
          '2012-06-14',
          '2012-06-15',
          '2012-06-16',
          '2012-06-17'],
 'factor_1': ['1.255', '1.258', '1.249', '1.253', '1.258', '1.263', '1.264'],
 'factor_2': ['1.548', '1.554', '1.552', '1.556', '1.552', '1.558', '1.572'],
 'price': ['1600.20',
           '1610.02',
           '1618.07',
           '1624.40',
           '1626.15',
           '1626.15',
           '1626.15']}

A: You can use the csv module found in the python standard library to manipulate CSV files.
example:
import csv
with open('some.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        print row

A: Note quite as clean, but:
import csv

with open("value.txt", "r") as f:
    csv_reader = reader(f)
    num = '  '
    for row in csv_reader:
        print num, '\t'.join(row)
        if num == '  ':
            num=0
        num=num+1

Not as compact, but it does the job:
   Date price   factor_1    factor_2
1 2012-06-11    1600.20 1.255   1.548
2 2012-06-12    1610.02 1.258   1.554
3 2012-06-13    1618.07 1.249   1.552
4 2012-06-14    1624.40 1.253   1.556
5 2012-06-15    1626.15 1.258   1.552
6 2012-06-16    1626.15 1.263   1.558
7 2012-06-17    1626.15 1.264   1.572


text:
Q: Read number from file into a 2D matrix I am trying to write a function to read number from a file into a 2D matrix; mm_alloc() function is a function that creates an empty matrix, and
the first line of this file is the size of the matrix; but code seems can not read from the file, what is my problem? Do I use fgets() and sscanf() wrongly?
double **mm_alloc( int size )
{
    double **matrix;
    int i;
    matrix = (double **)malloc((size) * sizeof(double *));
    for ( i = 0; i < size; i++ ) {
        matrix[i] = (double *)malloc(size);
    }
    return( matrix );
}

double **mm_read( char *filename, int *size )
{
    FILE *myfile;
    myfile = fopen(filename, "r");
    char read[256];
    fgets(read, 256, myfile);
    sscanf(read, "%d", size);
    int i, j;
    double **Matrix;
    Matrix = mm_alloc( *size );
    for ( i = 0; i < *size; i++ ) {
        for ( j = 0; j < *size; j++) {
            fgets(read, 256, myfile);
            sscanf(read, "%lf", &Matrix[i][j]);
        }
    }
    fclose (myfile);
    return( Matrix );
}

void mm_free( int size, double **matrix  )
{
    int i;
    for ( i = 0; i < size; i++ ) {
        free(matrix[i]);
    }
    free(matrix);
}

void mm_print( int size, double **matrix )
{
    int i, j;
    for ( i = 0; i < size; i++ ) {
        for ( j = 0; j < size; j++ ) {
            printf("%16f", matrix[i][j]);
        }
        printf("\n");
    }
}

double **mm_swap( int size, double **matrix )
{
    double **swap;
    swap = mm_alloc(size);
    int i, j;
    for ( i = 0; i < size; i++ ) {
        for ( j = 0; j < (size-2); j++) {
            swap[i][j] = matrix[i][j+2];
            swap[i][j+2] = matrix[i][j];
        }
    }
    return( swap );
}

double **mm_matrix_mult( int size, double **matrix, double **transpose )
{
    double **matrix_mult;
    matrix_mult = mm_alloc(size);
    int i, j, k;
    double result;
    for ( i = 0; i < size; i++ ) {
        for ( j = 0; j < size; j++ ) {
            result = 0;
            for ( k = 0; k < size; k++ ) {
                result += (matrix[i][k] * transpose[k][j]);
            }
            matrix_mult[i][j] = result;
        }
    }
    return( matrix_mult );
}

int main()
{
    char filename[256];
    double **matrix=NULL;
    double **swap_matrix=NULL;
    double **results_matrix=NULL;
    int size=0;

    printf("Please enter the matrix data file name: ");
    scanf( "%s", filename );

    matrix = mm_read( filename, &size );
    swap_matrix = mm_swap( size, matrix );
    results_matrix = mm_matrix_mult( size, matrix, swap_matrix );

    mm_print( size, results_matrix );
    mm_free( size, matrix );
    mm_free( size, swap_matrix );
    mm_free( size, results_matrix );
    return( 0 );
}

the file content:
4
1.0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9.0
10.0
11.0
12.0
13.0
14.0
15.0
16.0

A: You are opening the file with "w".
That will erase the file. You need to open with "r" to read from a file.

A: You allocation function allocates to few memory.
This line
    matrix[i] = (double *)malloc(size);

should at least be
    matrix[i] = (double *)malloc(size * sizeof(double));

Or even better removing this useless cast:
    matrix[i] = malloc(size * sizeof(double));

Also the allocation function fully missed to perform any error checking. `malloc() might very well fail, depending of the size of memory requested.
Below please find a safe implementation:
/* Allocates a pointer matrix to an array of size pointers
   each pointing to size doubles.

   Returns matrix or NULL on error.
 */

double ** mm_alloc(size_t size)
{
  double ** matrix =  malloc(size * sizeof *matrix);
  if (NULL != matrix)
  {
    for (size_t i = 0; i < size; ++i)
    {
      matrix[i] = malloc(size * sizeof *matrix[i]);
      if (NULL == matrix[i])
      {  /* Clean up. */
        while (0 < i)
        {
          --i;
          free(matrix[i]);
        }

        free(matrix);
        matrix = NULL;

        break;
      }
    }
  }

  return matrix;
}


text:
Q: How can I use HTML5 in all browsers including IE7,8? I want to use HTML5 because it supports in Iphone also and I really liked its capabilities but what can I do if it is not fully compatible with all browsers? Specially IE family. So is there a way by adding some js script e.t.c. so that HTML5 and its js api work normally in IE also as it works on other browsers like chrome, firefox and opera e.t.c.? So that I can use it without thinking of browser compatibility issues. There are also many game engines in html5 but what if this is not supported major IE browsers. Or can some one tell that how much advantage can I take of html5 without thinking of compatibility issues?
Thanks in advance

A: Polyfills let you use new HTML5 apis on older browsers. The Modernizr project keeps a list of good ones: https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills

A: You can use http://html5boilerplate.com/ together with http://code.google.com/p/html5shiv/ and you're good to go.
For some other cool features, like video in old IE, you need to use workarounds like Flash for video and Javascript libs for canvas.

A: Simply put, if the markup is valid in HTML 4, change the Doctype and it will work as HTML 5.
If you want to use the new elements like <article> or <footer>, you will need to include a small javascript snippet in order to register those new types.
document.createElement("article");
document.createElement("footer");

This will make these new elements usable and stylable like an ordinary <div> element


text:
Q: how to know if file is still open for writing
i have a function that writes to a file , how can i using another script check if the file is being used for writing or it is closed ?
Edit : this file might be opened for writing by other script/application/system ...
thank you .

A: You should use flock in both scripts.  This puts a flag on the file so that other scripts are informed that the file is in use.  The flag is turned off either intentionally using fclose or implicitly by the end of the script.

A: If you're on Unix, your system might have the lsof ("LiSt Open Files") command installed.
The "FD" column in the output indicates whether the file was opened for reading,
writing, or both.
I'd like to point out that any process of the form "check to see if file X is open for writing, if so do something..." is subject to a race condition.  Some other process
could open the file after you've checked, but before the action was started.

A: I'd say just use the file open function, if it returns false, then the file's obviously still open.


text:
Q: Multiple file upload for one parameter inside model nodejs I want to make a gallery to an artist. I got mostly everything done but I want to upload multiple imageFiles to one artist without making 1 model for 1 painting hand coded. Inside my Model i got paintings: {type: String} but i dont want paintings2, paintings3. Is there a way to count automatically and display any of them seperate to delete one. My file input is<input type="file" class="filepond " name="paintings" value="<%= post.paintings %>" multiple>
router
If you need more code I can send

A: You can have the model schematype as array
change this
paintings: {type: String}

into
paintings:  [ { type: String} ]

reference : https://mongoosejs.com/docs/schematypes.html#arrays
please provide more detail / code if you are still having issue


text:
Q: How to write to KDE's OSD or notification from console? How can I write, from a bash script, to KDE's OSD or notification area? I am using KDE 4.5, and basically what I want is my script to report some stuff when it is run. Since I run the script by a shortcut, I have no console output, but I would like to write to OSD on notification area.
I know about, and use, "osd_cat" but that just puts some ugly text on the screen.
Thanks.

A: notify-send 'why hello there'

notify-send is part of the package libnotify-tools.

perl -MDesktop::Notify -e'Desktop::Notify->new->create(body => q{why hello there})->show'

Desktop::Notify is available on CPAN.

A: As an alternative:
kdialog --passivepopup 'why hello there' 5

5 is the number of seconds it will last.
Run kdialog --help for other options, like title.


text:
Q: sql joins to fetch data from different tables how to write a query to fetch the data (provider name, service name,location name) from appointment table which has foreign key sechedule_id(f.k) of schedule table.
schedule table in turn has foreign key Provider_id (f.k),Serviceid(f.k),Location id (f.k)
**appointment table**
Appointment_id char(23)
schedule id char(23) (f.k)

**schedule table**
Schedule id (p.k)
Provider_id (f.k)
Service id (f.k)
Location id (f.k)
Availability

**service table**
Service_id(p.k)
Name

**provider table**
Provider_id(p.k)
Provider name

**location table**
Location_id(p.k)
Location_name

A: You should not post your assignment here. If you are facing any problem in code then post your code and we will provide your ans.
but i give you the ans for this queation.
select p.provider_name,s.name,l.location_name from appointment a,schedule sc,service s,provider p,location l where
sc.schedule_id=a.schedule_id and
sc.provider_id=p.provider_id and
sc.service_id=s.service_id and
sc.location_id=l.location_id and
a.appointment_id = 'Your id'

Hope it will help.


text:
Q: How to animate a social sharing buttons div on mouseover using jquery I am trying to make social button animation for my website,
Take this as an example animation of sharing round div on top right side : http://www.dubbelfrisss.nl
How can I make this type of mouse hover animation?

A: YOu can check here DEMOs http://tympanus.net/Development/IconHoverEffects/
Website http://tympanus.net/codrops/2013/05/30/simple-icon-hover-effects/

A: draw a cicle with css. you can also use css3 instead of jquery to animate it, if u dont want to support old browsers. if you want to make it with jquery read about set width/heigt and maybe use animate function. learn jquery.
here an examplke with css3
div.test {
    border-radius: 50%;
    height: 200px;
    width: 200px;
    -webkit-transition-property: height, width;
    -webkit-transition-duration: 1s;
    background: red;
}

div.test:hover {
    width: 500px;
    height: 500px;
    -webkit-transition-property: height, width;
    -webkit-transition-duration: 1s;
    background: red;
}


text:
Q: How to call `findOne` function in an array which is stored in a collection in Mongoose? The model of the collection is
const clientInfo = {
  uniqueID: {
    type: String,
    required: true,
  },
  firstName: {
    type: String,
    required: true,
  },
  lastName: String,
  email: {
    type: String,
    required: true,
  },
  countryCode: String,
  phone: String,
  status: {
    type: String,
    required: true,
  },
  addedOn: {
    date: String,
    time: String,
  },
};

And this model is stored in another model
const userClient = {
  userID: {
    type: String,
    required: true,
  },
  clients: [clientInfo],
};

Now, I want to compare the email of the client with the request body i  have received.
I am currently doing it like this:
 await UserClient.findOne(
    { userID: validUser.userID },
    async (err, clientList) => {
      if (clientList) {
        //Check for duplicate client
        await clientList.findOne(
          { email: req.body.email },
          (err, duplicateClient) => {
            if (duplicateClient) {
              return res.status(400).send(`Client already exists!`);
            } else {
              clientList.clients.push(client);
              clientList.save();
              const response = {
                statusCode: 200,
                message: "Client added!",
                client: client,
              };
              res.send(response);
            }
          }
        );
      } else {
        const newList = new UserClient({
          userID: validUser.userID,
          clients: client,
        });
        newList.save();
        const response = {
          statusCode: 200,
          message: "Client added!",
          client: client,
        };
        res.send(response);
      }
    }
  );
});

But I am getting an error UnhandledPromiseRejectionWarning: TypeError: clientList.findOne is not a function.
What I am doing now is, finding a collection with a specific userID, and If I hot a match, i want to compare all the objects inside the array with the email, i have received on my request body.
Currently, If It does not find any match in the UserClient.findOne, everything goes well, but if I have match in UserFind.findOne and i want to call the similar method in the array, I am getting the error.
How to do I get rid of this error?
Thanks in advance.

A: Try this
await UserClient.findOne(
    { userID: validUser.userID,'clients.email': req.body.email },
    async (err, clientList) => {
    if(err){
      //throw error here
    }
    console.log(clientList)
})

A: Corrected some issues,

*

*find user by id, check if user is found then find client on the base of email in loop if found then return client exists otherwise save to User document,

*if client not found then add new user and client

await UserClient.findOne(
    { userID: validUser.userID },
    async (err, User) => {
        // FIND CLIENT
        if (User) {
            let clientExists = false;
            for (let c in User.clients) {
                if (User.clients[c].email == req.body.email ) clientExists = true;
            }
            // ADD CLIENT
            if (clientExists) {
                User.clients.push(client);
                User.save();
                return res.send({
                    statusCode: 200,
                    message: "Client added!",
                    client: client,
                });
            }
            // CLIENT EXISTS
            else {
                return res.status(400).send(`Client already exists!`);
            }
        }
        // ADD NEW USER AND CLIENTS
        else {
            const newList = new UserClient({
                userID: validUser.userID,
                clients: client,
            });
            await newList.save();
            return res.send({
                statusCode: 200,
                message: "Client added!",
                client: client
            });
        }
    }
);

I have not tested this code, let me know if you are getting any issues.


text:
Q: How to remove space between TextField and Text on HStack in SwiftUI? I have a TextField and Text next in HStack Sections.
There is a large empty space between them and I can not figure out how to remove it.
VStack{

    Section {
        HStack {
            TextField("Kohalik raha", text: $localMoney)
                .multilineTextAlignment(.center)
            Text("GEL")
                .multilineTextAlignment(.leading)
        }
    }
    Section {
        Text("\(money, specifier: "%.2f") EUR")
    }
    Section {
        HStack {
            TextField("Kurss", text: $rate )
                .multilineTextAlignment(.center)
            Text("Kurss")
                .multilineTextAlignment(.leading)
        }
    }
}

A: Make the textField have fixedSize to bring them near in center:
HStack {
    TextField("Kohalik raha", text: $localMoney)
        .background(Color.blue)
        .multilineTextAlignment(.center)
        .fixedSize()

    Text("GEL")
        .multilineTextAlignment(.leading)
        .background(Color.yellow)
}

I have added some colors to see better ;)

A: Add a Spacer() after the TextField and Text views.


text:
Q: Replacement for Java ByteBuffer in this case? Working with the Android Profiler tool, I've discovered that I'm using lots of ByteBuffers in a performance critical area of my code. I've worked on optimizing as much as possible of the largest performance hits (haven't been forced to go to stuff like loop optimization yet) and the ByteBuffer code looks like it could easily be replaced with another/a better solution.
The Problem: Getting an int from 4 consecutive bytes located in the ByteBuffer stream, which could be of any length, currently done (seen below, specifically //<<< parts) with a temp ByteBuffer and grabbing needed bytes to form an int. Is there any simpler process?
private int peekStreamData(ByteBuffer stream, int count) {
    int data = 0;
    int stream_field = streamField;
    int stream_field_bit_index = streamFieldBitIndex;
    byte[] streamArr = stream.array();
    ByteBuffer bb = ByteBuffer.allocate(4);
    while (count > (32 - stream_field_bit_index) && streamIndex < (imageStream.capacity() >> 2)) {
        data = (data << (32 - stream_field_bit_index)) | ( stream_field >>> stream_field_bit_index);
        count -= 32 - stream_field_bit_index;

        bb.put(0,streamArr[streamIndex * 4 + 3]);  //<<<
        bb.put(1,streamArr[streamIndex * 4 + 2]);  //<<<
        bb.put(2,streamArr[streamIndex * 4 + 1]);  //<<<
        bb.put(3,streamArr[streamIndex * 4 + 0]);  //<<<
        stream_field = bb.getInt();                //<<<
        stream_field_bit_index = 0;
    }
    if (count > 0)
        data = (data << count) | (stream_field >>> (32 - count));
    return data;//data;
}

Please feel free to point out any mistakes. I've never worked with ByteBuffers until quite recently and would love to learn.

A: These lines
    bb.put(0,streamArr[streamIndex * 4 + 3]);  //<<<
    bb.put(1,streamArr[streamIndex * 4 + 2]);  //<<<
    bb.put(2,streamArr[streamIndex * 4 + 1]);  //<<<
    bb.put(3,streamArr[streamIndex * 4 + 0]);  //<<<
    stream_field = bb.getInt();                //<<<

can be replaced with the following with a second ByteBuffer.
    stream_field = stream.getInt(streamIndex * 4);

I suspect much of the other code can be simplified, but its not clear to me what it does or why there is even a loop to do it.

A: Have you tried:
stream_field = (streamArr[streamIndex * 4 + 0] & 0xFF) | ((streamArr[streamIndex * 4 + 1] & 0xFF) << 8) | ((streamArr[streamIndex * 4 + 2] & 0xFF) << 16) | ((streamArr[streamIndex * 4 + 3] & 0xFF) << 24);

or:
stream_field = ((streamArr[streamIndex * 4 + 0] & 0xFF) << 24) | ((streamArr[streamIndex * 4 + 1] & 0xFF) << 16) | ((streamArr[streamIndex * 4 + 2] & 0xFF) << 8) | (streamArr[streamIndex * 4 + 3] & 0xFF);

depending on endiannes.
EDIT: In Java byte is signed, so they need masking. Corrected.

A: You can just combine the four bytes into an int instead of using a temporary ByteBuffer.  By default, the four bytes are in big-endian byte order.  Also, you don't have to calculate "streamIndex * 4" four times in a row.


text:
Q: How are these two ways of typecasting in ActionScript 3 different? In the Lynda.com title "ActionScript 3.0 in Flash CS3 Professional - Beyond the Basics" Todd Perkins shows how one way of typecasting
var xml: XML;
xml = event.target.data as XML

doesn't work, while
var xml: XML;
xml = XML(event.target.data)

does. Shouldn't both forms act the same way? How are they different?
TIA
Steven
edit
declarations added to the code

A: Basically they are different by XML(event.target.data) meaning "cast this to that type" where event.target.data as XML means "pretend it is XML".
The former is the same casting that you would expect in other languages like Java. It's a useful way to have code not need to have a try-catch block around a cast. Using as will either return the the first operand if it is the correct type or null otherwise.
You should take a look at the as operator if you need more information.

A: The as operator returns null if the left operand (event.target.data) is not an instance of the right operand (expected type = XML), whereas the typecast results in an exception in this case.


text:
Q: Creating random points using QGIS? Has anyone else had any issues using the random points tool in QGIS?
When I try using it I'm selecting the option to use a value input field. The tool starts but then freezes once it gets to the 10% processing level as indicated by the status bar. Is this a known bug?


text:
Q: ViewScoped managed bean recreated on every request I've managed to get a plain ViewScoped page going. I don't know if I don't understand something or this page isn't working as it should.
Every request it creates a new Test object even though it is ViewScoped and I can never get back the theString variable that I set.
Plain template with a input field, a button to set the value and a button to refresh the value displayed:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.org/ui" xmlns:c="http://xmlns.jcp.org/jsp/jstl/core">

    <f:view contentType="text/html">
        <h:head>
        </h:head>

        <h:body>
            <h:form>
                <p:commandButton process="theInput" value="Set value" />
                <p:inputText id="theInput" value="#{test.theString}" /> --
            </h:form>

            <h:form>
                <p:commandButton process="theArea" update="theArea" value="Display value" />
            </h:form>

            <h:panelGroup id="theArea">
                #{test.theString}
            </h:panelGroup>
        </h:body>
    </f:view>
</html>

Bean:
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.view.ViewScoped;

@ManagedBean(name = "test")
@ViewScoped
public class Test implements Serializable {

    private String theString = "initial";

    public String getTheString() {
        return theString;
    }

    public void setTheString(String theString) {
        this.theString = theString;
    }
}

I'm using Mojarra 2.2.7, Primefaces 5.2 and Glassfish 4.1
Shouldn't the Test object hold its state? Is there something I'm missing here?


text:
Q: How to get android widget sizes programmatically if they were expressed as percentages Is it possible to retrieve the dimensions of a widget if they were expressed as percentages of their parents' dimensions in the xml file? Take for example, I have an image view set in a linear layout. The image view's height is set to 0dp, then its weight is set to 0.5. Is it possible to programmatically get the actual height at runtime in dp? If yes, how is it done. Thank you very much.

A: Yes.  You call getHeight after the view has been laid out.  At that time the actual data should be in there.


text:
Q: Avoid code duplication on child classes of an abstract class I'm working on an old Struts application which has an abstract action to create Excel exports by filling Excel template files.
Each Excel export action extends this parent class and adds its own implementation for filling the Excel template and defines its own template and output filename.
public abstract class ExcelExportAction extends BaseAction {
    protected abstract String getInputFilename();
    protected abstract String getOutputFilename();
    protected abstract HSSFWorkbook modifyWorkbook(HSSFWorkbook workbook, HttpServletRequest request);

    @Override
    protected final ActionForward run(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    throws Exception {

        Workbook workbook = new Workbook(getInputFilename());
        workbook = modifyWorkbook(workbook, request);
        addWorkBookToResponse(workbook, getOutputFilename());

        return null;
    }
...
}

Implementations are looking like this and this is where the code duplication is "warned" by SonarQube:
public class BudgetReportExcelAction extends ExcelExportAction {
    private static final String INPUT_FILENAME = "Report-Budget-Template.xls";
    private static final String OUTPUT_FILENAME = "Report-Customerbudget.xls";

    @Override
    protected String getInputFilename() {
        return INPUT_FILENAME;
    }
    @Override
    protected String getOutputFilename() {
        return OUTPUT_FILENAME;
    }
    @Override
    protected HSSFWorkbook modifyWorkbook(HSSFWorkbook workbook, HttpServletRequest request) {
        /* modify the workbook */
        return workbook;
    }
}

Any ideas how to avoid the duplication?

A: There is hardly any code duplication in the code that I see here, but if you really want to "squeeze water from a stone", you can add a constructor to the base class, which accepts the input-filename and output-filename, and make each derived class pass its input-filename and output-filename to the constructor of the base class.

A: A non-answer here: there is no "code duplication" in your examples.
The point is: your abstract class drives a certain "layout" for your child class; but that is the essence of using an abstract class.
In other words: nothing to worry about here.
You are following well known, "approved" patterns; for example by nicely using the @Override annotation in your child class.
All fine, have a nice day!


text:
Q: Creating a scrollable game map in Android Studio I'm trying to make a TBS game app. The basic premise is that each player has a bunch of stars that are laid out on a 2D map and your goal is to conquer half the total stars.
I'm trying to figure out the best way to set up this game board. I want the board to be bigger than the device's screen (meaning the user will scroll around the map and maybe be able to zoom in/out) and be populated with "star" objects.
Anyone know where I should get started? I've looked at Grid View but that seems to be more fit for populating a limitless list of pictures or something.


text:
Q: How to create a specific date in the distant past, the BC era I'm trying to create a date in the BC era, but failing pretty hard. The following returns '4713' as the year, instead of '-4712':
  NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  NSDateComponents *components = [NSDateComponents new];
  [components setYear: -4712];
  NSDate *date = [calendar dateFromComponents:components];
  NSLog(@"%d", [[calendar components:NSYearCalendarUnit fromDate: date] year]);

Any idea what I'm doing wrong?
UPDATE: Working code
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [NSDateComponents new];
    [components setYear: -4712];
    NSDate *date = [calendar dateFromComponents:components];
    NSDateComponents *newComponents = [calendar components:NSEraCalendarUnit|NSYearCalendarUnit fromDate:date];
    NSLog(@"Era: %d, year %d", [newComponents era], [newComponents year]);

This prints 0 for the era, just as Ben explained.

A: Your code is actually working fine. Since there's no year zero, -4712 is the year 4713 BC. If you check the era component you'll see that it's zero, which in the Gregorian calendar indicates BC. Flip that negative sign and you'll see 4712 AD (era 1).


text:
Q: MYSQL will not return more than 1 category I've tried to find an answer to this problem, but I can't.
I have a 3 table format mqsql database.
I use 1 table to add all of the product information, CarpetInfo,
1 Table to list my categories, CarpetCategories,
and 1 Table to add categories to the products, CarpetCategorySort.
My CarpetCategorySort table has 3 columns, Manufacturer, Style, CategoryID.
Example would be Manufacturer = Aladdin, Style = Alma Mater, CategoryID = 14/ 15/ 18/ 19/ 20/ 21/ 67/
My CarpetCategories Table has 2 Columns CategoryID and Category.
2 Examples would be CategoryID = 14, Category = Commercial &
CategoryID = 15, Category = Commercial Loop
I can only get the code to work when I type in Commercial into the $category variable below. The code will not work if I type Commercial Loop into the $category variable. It's like it will only pull in the first number 14 and all of the others are ignored. The pricing order and everything else works right, just not the CategoryID part.
Here is my code.
<?php $mill = "Aladdin"; $category = "Commercial Loop";
$order = mysqli_query($con, "
SELECT * FROM CarpetInfo JOIN CarpetCategorySort USING (Manufacturer, Style)
JOIN CarpetCategories USING (CategoryID)
WHERE Manufacturer='$mill' AND Category LIKE '%$category%'
order by Price = 0, Price asc,
Style asc");
include($_SERVER['DOCUMENT_ROOT'].'/includes/pricing/carpet-order-test.htm');?>

Any help is greatly appreciated!

A: That's a backward way of handling things, a field with several datapoints smooshed together like that really never has any justification for existence.  I'd list the carpets in one table, list the categories in another, and finally list cross-references of both in another table, where you get a many-to-one relationship at both ends.
You need an actual category table only if you think it's going to take so much room to give duplicate info for each category and/or you can't control user input for categories (like you aren't just using a pulldown to give a name choice).
Something like:
CREATE TABLE IF NOT EXISTS `carpets` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `abbrev` varchar(10),
  `description` varchar(250),
  [...]
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `carpet_categories` (
`id` int(11) NOT NULL,
  `carpet_id` int(11) NOT NULL,
  `category_id` int(11) NOT NULL,
[...]
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `carpet_category_info` (
  `id` int(11) NOT NULL,
  `price-per-sqf` int(11) NOT NULL,
  `name` varchar(50),
   [...]
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

then all your joins become simple, and fast..  And accurate.


text:
Q: Find how an element's css has changed after jQuery "toggle" function has been used I am using toggle() in my Javascript function to change the CSS class of an element. When the element is clicked on, the class is removed, when it is clicked on again the class is added again. How can I find out whether the toggle() function is adding or removing the class from the element so that I can perform some other operations based on that?

A: You can use hasClass() to check if the element has that class, if true it was just added if false it was removed.

A: You can use the jQuery is method to determine whether the element meets the appropriate selector (in this instance a class selector):
if (element.is('.class'))...

A: here is raw example
  $('#test').click(function() {
        $(this).toggleClass('red');
        $(this).toggleClass('blue');

        if($(this).hasClass('red')) {alert('red');}
        if($(this).hasClass('blue')) {alert('blue');}
    });


text:
Q: How to reload window when someone is not on the screen of the site.But on the screen window should not be reload I am using this code to reload the window. I want that when someone is on the screen it should not be reloaded.But if someone is not on the screen it should be auto-reload again and again.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,

A: This will work:

var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") {
  hidden = "hidden";
  visibilityChange = "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
  hidden = "msHidden";
  visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
  hidden = "webkitHidden";
  visibilityChange = "webkitvisibilitychange";
}

function handleVisibilityChange() {
  if (document[hidden]) {
    // do something when inactive
  } else {
    // do something when active
  }
}

document.addEventListener(visibilityChange, handleVisibilityChange, false);