text:
Q: AFNetworking tutorial of raywenderlich not displaying data on table cell I am learning AFNetworking using,
https://www.raywenderlich.com/59255/afnetworking-2-0-tutorial
But, For json part I am not getting data displayed on cell that displyed in this tutorial.
I am getting response in json format but after that nothing is displayed in cells.
    static NSString * const BaseURLString = @"http://www.raywenderlich.com/demos/weather_sample/";

    @interface WTTableViewController ()
    @property(strong) NSDictionary *weather;
    @end

    @implementation WTTableViewController

    - (id)initWithStyle:(UITableViewStyle)style
    {
        self = [super initWithStyle:style];
        if (self) {
            // Custom initialization
        }
        return self;
    }

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        self.navigationController.toolbarHidden = NO;

        [self.tableView setDelegate:self];
        self.tableView.dataSource=self;
        // Uncomment the following line to preserve selection between presentations.
        // self.clearsSelectionOnViewWillAppear = NO;

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    }

    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
        if([segue.identifier isEqualToString:@"WeatherDetailSegue"]){
            UITableViewCell *cell = (UITableViewCell *)sender;
            NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

            WeatherAnimationViewController *wac = (WeatherAnimationViewController *)segue.destinationViewController;

            NSDictionary *w;
            switch (indexPath.section) {
                case 0: {
                    w = self.weather.currentCondition;
                    break;
                }
                case 1: {
                    w = [self.weather upcomingWeather][indexPath.row];
                    break;
                }
                default: {
                    break;
                }
            }
            wac.weatherDictionary = w;
        }
    }

    #pragma mark - Actions

    - (IBAction)clear:(id)sender
    {
        self.title = @"";
        self.weather = nil;
        [self.tableView reloadData];
    }

    - (IBAction)jsonTapped:(id)sender
    {
        NSString *string = [NSString stringWithFormat:@"%@weather.php?format=json", BaseURLString];
        NSURL *url = [NSURL URLWithString:string];
        //NSURLRequest *request = [NSURLRequest requestWithURL:url];

        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager GET:string parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
            NSLog(@"JSON: %@", responseObject);
        } failure:^(NSURLSessionTask *operation, NSError *error) {
            NSLog(@"Error: %@", error);

            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                                message:[error localizedDescription]
                                                               delegate:nil
                                                      cancelButtonTitle:@"Ok"
                                                      otherButtonTitles:nil];
            [alertView show];

        }];

    }
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(!self.weather)
        return 1;

    switch (section) {
        case 0: {
            NSLog(@"return 1");
            return 1;
        }
        case 1: {
            NSArray *upcomingWeather = [self.weather upcomingWeather];
            NSLog(@"return upcomingWeather");
            return [upcomingWeather count];
        }
        default:
            return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{NSLog(@"tableView");
    static NSString *CellIdentifier = @"WeatherCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    NSDictionary *daysWeather = nil;

    switch (indexPath.section) {
        case 0: {
            daysWeather = [self.weather currentCondition];
            NSLog(@"currentCondition");
            break;
        }

        case 1: {
            NSArray *upcomingWeather = [self.weather upcomingWeather];
            daysWeather = upcomingWeather[indexPath.row];
            NSLog(@"upcomingWeather");
            break;
        }

        default:
            break;
    }

    cell.textLabel.text = [daysWeather weatherDescription];
    NSLog(@"textLabel = %@", cell.textLabel.text);
    // Configure the cell...

    return cell;
}

I have this code in my table view controller.
This methods are used in delegate method in above code :
- (NSDictionary *)currentCondition
{
    NSDictionary *dict = self[@"data"];
    NSArray *ar = dict[@"current_condition"];
    return ar[0];
}

- (NSArray *)upcomingWeather
{
    NSDictionary *dict = self[@"data"];
    return dict[@"weather"];
}

I am getting response in json formate but cells are empty.
Please refer tutorial if anything is missing here.
Thank you.

A: In success of data received you just printing data.
you have to store that data in dictionary and reload tableview.
Use below code:
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:string parameters:nil progress:nil
    success:^(NSURLSessionTask *task, id responseObject) {

        self.weather = (NSDictionary *)responseObject; //add this line
        [self.tableView reloadData];                   //add this line

    } failure:^(NSURLSessionTask *operation, NSError *error) {
        NSLog(@"Error: %@", error);

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                            message:[error localizedDescription]
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];

    }];

A: You are missing following code from success block
    self.weather = (NSDictionary *)responseObject;
    self.title = @"JSON Retrieved";
    [self.tableView reloadData];

A: Just check the data existence inside weather dict once before you loaded into tableview and after completion of getting data from server just call reloadData method of uitableView so it will load data received by your code later.


text:
Q: Run some jQuery when any option group option is selected How can you run jQuery when any option group option is selected. In this case I want to make inputs show and hide based on when any option in one of the two option groups is selected.
HTML
<select>
    <option>Select</option>
    <optgroup label="One">
        <option value="1">Value 1.1</option>
        <option value="2">Value 1.2</option>
        <option value="3">Value 1.3</option>
    </optgroup>
    <optgroup label="Two">
        <option value="4">Value 2.1</option>
        <option value="5">Value 2.2</option>
        <option value="6">Value 2.3</option>
    </optgroup>
</select>

<input id="inputOne" type="text" placeholder="Input one"/>
<input id="inputTwo" type="text" placeholder="Input two"/>

A: JSFiddle
http://jsfiddle.net/u76eynap/2/
HTML
<select>
    <option>Select</option>
    <optgroup label="One">
        <option value="1">Value 1.1</option>
        <option value="2">Value 1.2</option>
        <option value="3">Value 1.3</option>
    </optgroup>
    <optgroup label="Two">
        <option value="4">Value 2.1</option>
        <option value="5">Value 2.2</option>
        <option value="6">Value 2.3</option>
    </optgroup>
</select>

JS
$("#inputOne, #inputTwo").hide();

$('select').change(function () {
    if ($("select option:selected").parent()[0].label == "One") {
        $("#inputOne").show();
        $("#inputTwo").hide();
    } else if ($("select option:selected").parent()[0].label == "Two") {
        $("#inputTwo").show();
        $("#inputOne").hide();
    } else {
        $("#inputOne, #inputTwo").hide();
    }
});

A: Try this :Initially hide input fields. Then get the parent of selected option and read its label. Using that label identify the input and make it visible
HTML:
<input id="inputOne" type="text" placeholder="Input one" style="display:none;"/>
<input id="inputTwo" type="text" placeholder="Input two" style="display:none;"/>

jQuery:
$(function(){
    $('select').change(function(){
        var $optionGroup = $(this).find('option:selected').closest('optgroup');
        //use jquery start attribute selector to hide all inputs
        $('input[id^=input]').hide();
        //select input respective to selected optgroup and show it.
        $('input[id=input' + $optionGroup.attr('label') + ']').show();
    });
});

JSFiddle Demo

redpajama_set_name: RedPajamaStackExchange


text:
Q: SCNPhysicsBody is not matching in SceneKit I have am trying to stop the moving man when it hit with a plane but it is not stopping as it pass away from plane.According to apple documentation i apply simple shape as capsule to moving man and also setup collisions category but it is not working.Anybody help me please...
Here is my code
//Following SceneKit fox example make my character shape
node = SCNNode()
characterScene = SCNScene(named: "game.scnassets/Logan.dae")!

characterNode = characterScene.rootNode.childNodeWithName("Logan", recursively: true)!
node.addChildNode(characterNode)

let (min, max) = node.boundingBox
let collisionCapsuleRadius = CGFloat(max.x - min.x) * 0.4
let collisionCapsuleHeight = CGFloat(max.y - min.y)

let characterCollisionNode = SCNNode()
characterCollisionNode.name = "Logan"
characterCollisionNode.position = SCNVector3(0.0, collisionCapsuleHeight * 0.51, 0.0)
characterCollisionNode.physicsBody = SCNPhysicsBody(type: .Kinematic, shape:SCNPhysicsShape(geometry: SCNCapsule(capRadius: collisionCapsuleRadius, height: collisionCapsuleHeight), options:nil))
characterCollisionNode.physicsBody!.contactTestBitMask = collisionHero | collsionTarget
node.addChildNode(characterCollisionNode)

Here is code for a plane:
let plane = SCNPlane(width:20.0,height:20.0)
var planeNode = SCNNode(geometry: plane)
planeNode.position = SCNVector3(4.0,0.0,-5.0)
planeNode.physicsBody = SCNPhysicsBody.staticBody()
planeNode.physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.Static,
                                      shape: SCNPhysicsShape(geometry: plane, options: nil))

characterNode.physicsBody?.contactTestBitMask = collisionHero | collsionTarget
characterNode.physicsBody?.categoryBitMask = collisionHero
characterNode.physicsBody?.collisionBitMask = collsionTarget
planeNode.physicsBody?.contactTestBitMask =   collsionTarget
planeNode.physicsBody?.categoryBitMask = collsionTarget
planeNode.physicsBody?.collisionBitMask = collisionHero

Can some one please point out me where is my mistake in code?
Thanks.


text:
Q: Qt Qml tree model menu with translations I am trying to make an app with live translation of text in a large tree model menu structure, in the same manner as: https://code.qt.io/cgit/qt/qtbase.git/tree/examples/widgets/itemviews/simpletreemodel?h=5.15
The item's "data" is a QString that is translated like
root = new MenuObject(tr("Main menu"));

And children are appended like:
root->appendChild(new MenuObject(tr("Test 1")))
    .appendChild(new MenuObject(tr("Test 2")))

I am using QML to show these, with a qmllistpoprerty to show these menus like:
Q_PROPERTY(QQmlListProperty<MenuObject> list READ getList NOTIFY listChanged);

The QML is a simple ListView with a delegate Label showing the MenuObjects's description with the q_property:
Q_PROPERTY(QString description READ getDescription CONSTANT);

To change language i am using a function getting the translation file into the translator, followed by:
installTranslator(translator);
engine.retranslate();

Now this does work for simple q_properties like:
Q_PROPERTY(QString header READ getHeader NOTIFY listChanged);

Where
QString MainMenu::getHeader(){
    return tr("Header");
}

But I CANNOT get the translations to work for the items in the treemodel. Any help is appreciated.

A: If your description prop never fires an updated signal, then your UI will never refresh it.
The reason it works for Q_PROPERTY(QString header READ getHeader NOTIFY listChanged); is because presumably the listChanged() signal is fired whenever header is supposed to change also.
To fix it, you need to declare an appropriate NOTIFY signal for your description, and of course it is no longer a CONSTANT.


text:
Q: Android Bluetooth Pairing: How to make sure to get bluetooth pairing request in the front dialog instead of a notification? Also, If I get a notification, is there a way to click it programmatically and bring the pairing request to to front?

A: for reference to explain why and what, please have a look here:
Bluetooth pairing request on notification bar?
The solution is quite easy if you know it and if it fits into your application:
private void feintBluetoothDeviceDiscovery() {
    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
    btAdapter.startDiscovery();
    btAdapter.cancelDiscovery();
}

Call feintBluetoothDeviceDiscovery() before you try to pair or connect your bluetooth device. The popup should appear in the front.
We also had this issue in our automated tests. A pairing request only showing as notifications are a pain there. Thank to a colleague for sharing the code.

A: Use uuid cache followed by uuid in the following order.
private void SOKETHAZIRLA() {

    Log.i("ZZZZZZ", String.valueOf(btDevice.getBondState()));

    Thread connectThread = new Thread(() -> {
        try {
            if (btDevice != null) {

                Log.i("BTDevice", "Cihaz Name: " + btDevice.getName());
                Log.i("BTDevice", "Cihaz UUID: " + btDevice.getUuids()[0].getUuid());
                mbtSocket = btDevice.createRfcommSocketToServiceRecord(btDevice.getUuids()[0].getUuid());
                Log.d("BTDevice", "1. connect.");
                mbtSocket.connect();

            } else {
                Log.d("BTDevice", "Device is null.");
            }
        } catch (Exception ex) {
            try {

                mBluetoothAdapter.startDiscovery();

                if (btDevice != null) {
                    mbtSocket = btDevice.createRfcommSocketToServiceRecord(uuid);
                    Log.d("BTDevice", "2. connect.");
                    mbtSocket.connect();
                }

            } catch (IOException e) {
                e.printStackTrace();
                try {
                    mbtSocket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

                runOnUiThread(socketErrorRunnable);
                mbtSocket = null;
            }
        } finally {
            runOnUiThread(this::finish);
        }
    });
    connectThread.start();

}


text:
Q: How do you perform queries without specifying shard key in mongodbapi and how do you query across partitions? How do you perform queries without specifying shard key in mongodb api and how do you query across partitions?
In sql api the latter is enabled by setting EnableCrossPartitionQuery to true on the request but I'm not able to find anything like that for the mongodb api. And my queries that work on an unsharded collection now fails(queries that specify the shard key works as expected).
The queries fail indiscriminately of whether I use the AsQueryable extension syntax or the aggregation framework.

A: As I know, no such property similar to EnableCrossPartitionQuery in CosmosDB Mongo API. In fact, CosmosDB is an independent server implementation that does not directly align with MongoDB server versions and features.
CosmosDB supports a subset of the MongoDB API and translates requests into the CosmosDB SQL equivalent. CosmosDB has some different behaviours and results, particularly with their implementation of partitioning as compared to MongoDB's sharding. But the onus is on CosmosDB to improve their emulation of MongoDB.
Certainly, you could add feedback here to get official assistance or consider using MongoDB Atlas on Azure if you'd like full MongoDB feature support.
Hope it helps you.

A: Was confirmed a bug by the Product Group team! Will be fixed in first two weeks of september in case anyone runs into the same problems in the mean time.


text:
Q: Django, Forbidden (CSRF cookie not set.) How to catch when a form submitted and redirect to GET How do you control over CSRF token error when a client submits the form with POST and if CSRF token error occurs, I'd like to redirect the client to def get which has a form.
I found only CSRF_FAILURE_VIEW can be set to an error page but there is nothing I can control over redirection for CSRF error.
When the error occurs, Django make an internal server error.
So I cannot catch the error in the view.


text:
Q: My disable submit if input empty is not working my disable submit button if input is empty is not working. When i put an input, the submit button still not able to click, it is still disabled.
what is wrong here? btw, Im still learning..

    <input type="search" id="" placeholder="North Borneo.." name="valueToSearch" class="form-control" />

  <button type="submit" class="btn btn-primary" name="caribtn" disabled="disabled">

  </button>

$(function () {
  $('.button[type="submit"]').keyup(function () {
    var empty = false;

    $('.input[type="search"]').each(function () {
      if ($(this).val().length == 0) {
        empty = true;
      }
    });

    if (empty) {
      $('.button[type="submit"]').attr("disabled", "disabled");
    } else {
      $('.input[type="search"]').removeAttr("disabled");
    }
  });
});

A: Try it.
$(function() {

    var btnSubmit = $('button[type="submit"]');
    btnSubmit.attr('disabled', 'disabled');

    $('input[name="valueToSearch"]').on('keyup', function() {
        if ($(this).val() !== '') {
            btnSubmit.removeAttr('disabled');
        } else {
            btnSubmit.attr('disabled', 'disabled');
        }
    })

});

A: .button or .input class doesn't exist in your context.
Attach a handler to all your search inputs; and inside check if any of them are empty.

$(function() {
 $('input[type="search"]').keyup(function() {
      var empty = false;
      $('input[type="search"]').each(function() {
         if($(this).val().length === 0) {
             empty = true;
         }
      });

      if (empty) {
        $('button[type="submit"]').attr('disabled', 'disabled');
      } else {
        $('button[type="submit"]').removeAttr('disabled');
      }
  });
});
.mdi-magnify::before {content: "magnify-icon";display:inline-block;}

    <input type="search" id="" placeholder="North Borneo.." name="valueToSearch" class="form-control" />

  <button type="submit" class="btn btn-primary" name="caribtn" disabled="disabled">

  </button>


text:
Q: API response is always "null" I created an API and a Login Form and I need to authorize access to my API using Username and Password properties, which I get from two textboxes in my Login Form. However, the response from the API is always null. Here's my original code:
    public async Task<AuthenticatedUser> Authenticate(string username, string password)
    {
        var data = new List<KeyValuePair<string, string>>()
        {
            new KeyValuePair<string, string>("grant_type", "password"),
            new KeyValuePair<string, string>("username", username), //I made sure that both username and password
            new KeyValuePair<string, string>("password", password)  //are passed correctly to the Authenticate() void
        };
        var content = new FormUrlEncodedContent(data); //var data is not null but "content" is
        using (HttpResponseMessage response = await apiClient.PostAsync("/token", content))
        {
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsAsync<AuthenticatedUser>(); //response is always "null"
                return result;
            }
            else
            {
                throw new Exception(response.ReasonPhrase);
            }
        }
    }

I tried replacing the List<> with an array of KeyValuePair<>s, I also tried using a Dictionary<string, string>. Neither of these options worked. After some research on the net, I saw an alternative using StringContent or MediaFolder but I didn't know how to make it work with them.
I am also using https in my domain, so there seems to be no mistake there. For now, it looks as if FormUrlEncodedContent doesn't encode correctly.
Also, requests from Swagger and Postman return values.

A: I see you did the tutorial from Tim Corey's youtube channel, Retail Manager. I also had the same issue with PostAsync returning null.
You can check exception details when you set breakpoint to line throw new Exception(response.ReasonPhrase);
In my case it was SSL endabled set to True in DataManager project properties, therefore it opens url with secure protocol - https. In Tim's tutorial you see http protocol.

*

*Select DataManager in VS Solution Explorer -> Properties -> SSL Enabled: False

*Right Click on DataManager -> select Web tab -> change project url to: http://... or select Override application root URL: http://...

*Check App.config file in project: DesktopUI in VS Solution Explorer -> find tag and change key="api" value="http://...

A: First of all password grant type only accepts form encoding application/x-www-form-urlencoded and not JSON encoding application/JSON.
You can read more about it here and also try to change the content as follows:
Replace this:
var data = new List<KeyValuePair<string, string>>()
{
     new KeyValuePair<string, string>("grant_type", "password"),
     new KeyValuePair<string, string>("username", username), //I made sure that both username and password
     new KeyValuePair<string, string>("password", password)  //are passed correctly to the Authenticate() void
};
var content = new FormUrlEncodedContent(data);

with this:
var content = new FormUrlEncodedContent(
    new KeyValuePair<string, string>[] {
        new KeyValuePair<string, string>("grant_type", "password"),
        new KeyValuePair<string, string>("username", username),
        new KeyValuePair<string, string>("password", password)
   }
);


text:
Q: one sphere and many line segments intersection I am familiar with BSP, KD-tree and BVH for the general ray-primitive intersection finding problem. Are there any more efficient algorithms and data structures for finding intersections between only one sphere and many line segments? Please note that the sphere is query object.

A: One solution would be:

*

*Determine the line segments' bounding boxes and create a BVH or kd-tree from them.

*Determine the query sphere's bounding box.

*In your intersection algorithm, walk the sphere through the tree by checking for overlap between the sphere's BB and the current node.

*

*If there is no overlap, the sphere's BB doesn't intersect any line segment in the given node, and you can skip the node's children.

*If there is overlap, walk the node's children.

*At the leaf nodes, you have to perform a ray-intersection test for each line segment in the node and the sphere (it's not clear from your question, but I assume multiple segments can intersect the sphere and that you're interested in all such intersections). You can optimize the actual intersection test a bit like so:

Suppose that

*

*The sphere has radius R and its center is at point C,

*the line segment has ends at points P0 and P1,

*D0 is the distance between C and P0, and

*D1 is the distance between C and P1.

Then:

*

*If D0 < R and D1 < R, the line segment is contained entirely inside the sphere and does not intersect the surface.

*If D0 < R xor D1 < R, the line segment intersects the sphere's surface.

*Otherwise, the points are outside the sphere, but the line might intersect the surface, so run a regular ray-sphere intersection test.
A further optimization would be to compare squared distances with the squared radius, to avoid taking the roots.


text:
Q: Get date object from UTC string without changing the timezone I have a UTC date string "Sat, 24 Jun 2017 06:26:56 GMT". I am unable to get a Date object from the string. I want the Date object without any change in the timezone. I have tried these things

*

*new Date("Sat, 24 Jun 2017 06:26:56 GMT"). This gives me my machine's timezone.

*new Date(Date.parse("Sat, 24 Jun 2017 06:26:56 GMT")). Same result as above.
Is it possible to get the date without timezone change and without using Moment.js

A: If you set your date to a variable then check for the timezone it should be yours, so the date is kept at UTC, try the following :
var d = new Date("Sat, 24 Jun 2017 06:26:56 GMT");
console.log(d.getTimezoneOffset());

It should display your timezone in minutes so in your case (considering India) -550.
If you want to redisplay as UTC date, simply use the toUTCString(), like this:
 d.toUTCString()


text:
Q: Determing if $f(x,y)$ is continuous at $(0,0)$ I would really appreciate if someone could help me figure out where to start on this problem.
The question is to determine if $f$ is continuous at the origin.
$$\begin{equation}
  f(x,y)=\begin{cases}
    \dfrac{\sin(x-y)}{|x| + |y|}, & \text{if $(x,y) \neq (0,0)$}.\\
    0, & (x,y) = (0,0).
  \end{cases}
\end{equation}
$$
I'm really struggling with these concepts and would appreciate if someone could help me out

A: A necessary condition for that function to be continuous at the origin is that the limit of the function along any path to the origin must equal $f(0,0) = 0$.
See what happens if you approach along an axis.

A: You can use L'hopital's rule to show that $\lim_{x-y \to 0} \sin(x-y)/(x-y) = 1$. Thus your limit is equivalent to $\lim_{x,y \to 0} \frac{x-y}{|x| + |y|}$. If you consider any line $y = ax$ and take the limit as $x \to 0$, you will get that the limit is not $0$. So the function is not continuous at $0$.

A: $$\lim_{x \to 0^+} f(x,0) = \lim_{x \to 0^+} \frac{\sin(x)}{x} = 1 \neq 0=f(0,0)$$
It follows that $f$ is not continuous at $(0,0)$.


text:
Q: Filter based on root document property This is the documents structure:
{
    '_id' : ObjectId('56be1b51a0f4c8591f37f62a'),
    'name': 'Bob',
    'sub_users': [{'_id' : ObjectId('56be1b51a0f4c8591f37f62a')}]
}
{
    '_id' : ObjectId('56be1b51a0f4c8591f37f62b'),
    'name': 'Alice',
    'sub_users': [{'_id' : ObjectId('56be1b51a0f4c8591f37f62a')}]
}

The sub_users array is used basically to link accounts, in the example Alice is Bob's manager since she has him as a sub_user. Bob has his own id in the sub_users array and this is wrong (no one really is his own boss).
I want to find all the Bobs, it feels like a simple query but I can't find the way to do it, or to even to google it properly, tried this (probably knowing it wouldn't work);
db.users.aggregate([
    { $group: { _id: '_id' } },
    { $match: { sub_users: { $elemMatch: { _id: '$$ROOT._id' } } } }
])

And it didn't worked, so the question is; how to find a document whose nested documents have the same value as the root element (for a certain field)?

A: To get there I'm using compare expression - please see example below:
db.users.aggregate([{
            $unwind : "$sub_users"
        }, //have all ids on same level
        {
            $project : {
                _id : 1,
                name : 1,
                sameId : {
                    $cmp : ["$_id", "$sub_users._id"]
                },
            }
        }, {
            $match : {
                sameId : 0
            }
        }
    ])


text:
Q: Converting Int latitude and longitude to double (like Geopoint) I have this two int values (w 25456819, s 12088051).
I need to know how can i convert them to latitude and longitude values in double.
The final result of this should be something like this:

*

*w 25456819 = -33,xxxxxx

*s 12088051 = -70,xxxxxx

But i can't find any clue for this, the accurate answer then i have found it's something about google's Geopoint, this one recives two int values in his constructor. Then when you use the geopoint object you can get the lat and long values.
I have tried to find any library or class for c sharp, but i haven't had any luck on that.
I'll really apreciate any help.
Best regards.


text:
Q: Deleted Fedora partition, can't boot into Ubuntu I have installed Windows 7, Windows 10 TP, Fedora and Ubuntu in my computer. I have logged into Windows 7 and deleted the Fedora partition and since then I can't boot into any OS. I am struck at grub rescue window and ls lists few partitions but all of then do not contain /boot/grub.

A: Probably your Fedora partition contained the information related to GRUB.
Nothing to worry, just reinstall GRUB using some method.
For reinstalling it using Ubuntu live CD, follow this.
For more details check How to Repair, Restore, or Reinstall Grub 2 with a Ubuntu Live CD or USB.


text:
Q: integer values for onbindviewholder recycler view I just want to show my int values of this (price), how to write code that int values can be shown. For your information on my model name is a string and price is an integer
 @Override
 public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i)

{
   myViewHolder.name.setText(milk.get(i).getname_milk());
   myViewHolder.price.setText(milk.get(i).getprice());
}

A: textView.setText() support only string as parameter.
Write like this
myViewHolder.price.setText(String.valueOf(milk.get(i).getprice()));

hope it helps you.

A: Most Easy way
myViewHolder.price.setText(milk.get(i).getprice()+"")

A: You can try
myViewHolder.price.setText(milk.get(i).getprice().toString());

A: Simply
myViewHolder.price.setText(String.valueOf(milk.get(i).getprice()));


text:
Q: Akka.NET - Is it possible to mix AtLeastOnceDeliveryReceiveActor with Publish/Subscribe pattern? I'd like to ask whether it's possible to implement publish/subscribe pattern (http://getakka.net/articles/clustering/distributed-publish-subscribe.html) where subscriber is an AtLeastOnceDeliveryReceiveActor (http://getakka.net/articles/persistence/at-least-once-delivery.html)
I cannot make it working due to fact that AtLeastOnceDeliveryReceiveActor  doesn't have Receive method, but just Command. When I get reference to an actor and using Tell method send a message then Command receive it, but if I'd like to use mediator with Publish method then Command doesn't receive that message.
Thanks in advance.

A: ReceivePersistentActor's Command works just like Receive handler (the only distinction is acknowledgement of persistence/recovery lifecycle of an actor). That being said, you could potentially build an at-least-once-delivery publish/subscribe bus... however I'd advise to simply integrate your actors logic with an existing persistent queue/log (like Kafka, RabbitMQ, Azure Service Bus, whatever) instead of trying to recreate it in Akka. I guess it will be less painful for most of the people.


text:
Q: How to validate file except image in yii2 framework I want to upload a apk file with yii2 framework.
In Model
public function rules()
{
    return [
        [['apkFile'], 'file', 'skipOnEmpty' => true, 'extensions' => 'apk','mimeTypes'=>'application/*'],
    ];
}

public function upload()
{
    if ($this->validate()) {
        $this->apkFile->saveAs('affiliate/apkuploads/' . $this->apkFile->baseName . '.' . $this->apkFile->extension);
        return true;
    } else {
        return false;
    }
}

In Controller
public function actionCreate()
{
    $model = new ManageLinks();
    $post = Yii::$app->request->post();

    if(!empty($post)){
        $model->apkFile = UploadedFile::getInstance($model, 'apkFile');

        if ($model->upload()) {
            echo 'True';
        }else{
            echo 'False';
        }
    }
    return;
    return $this->render('create', [
        'model' => $model,
        'data' => $data,
    ]);

}

In form
<?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'apkFile')->fileInput() ?>

<div class="form-group">
    <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>

After executing this i get a false return. Please help me with this.
In my localhost i host yii2 framework under affiliate folder. My full url is:
http://localhost/affiliate/web/index.php

A: Pass
['enctype' => 'multipart/form-data']

in your form begin i.e
<?= Html::beginForm(['order/update', 'id' => $id], 'post', ['enctype' => 'multipart/form-data']) ?>

http://www.yiiframework.com/doc-2.0/guide-helper-html.html#creating-forms


text:
Q: Non-standard HTTP methods and Apache Http Components I'm writing an HTTP server using the HttpCore library of Apache HTTPComponents 4.3 (Java).  My server must be able to receive requests that have non-standard HTTP methods (methods other than GET, POST, DELETE, etc).
But when my server receives such a request, it returns a "method not supported" response.  Is there a way to force HTTPComponents to accept non-standard HTTP methods?
Background: I'm working on implementing a WebDAV server, which uses non-standard methods (like MKCOL and PROPFIND).

A: I found the solution, so I will answer my own question. xD
You have to create your own HttpRequestFactory implementation, and pass it up the chain.
HttpRequestFactory reqFact = new HttpRequestFactory() {
  public HttpRequest newHttpRequest(final RequestLine requestline) throws MethodNotSupportedException {
    return new BasicHttpEntityEnclosingRequest(requestline);
  }

  public HttpRequest newHttpRequest(final String method, final String uri) throws MethodNotSupportedException {
    return new BasicHttpEntityEnclosingRequest(method, uri);
  }
};
HttpMessageParserFactory<HttpRequest> parserFact = new DefaultHttpRequestParserFactory(null, reqFact);
HttpConnectionFactory<DefaultBHttpServerConnection> connFact = new DefaultBHttpServerConnectionFactory(null, parserFact, null)

The implementation that HttpComponents uses by default throws a MethodNotSupportedException if a non-standard HTTP method is found.  The source code for the default implementation can be found here:
http://hc.apache.org/httpcomponents-core-4.3.x/httpcore/xref/org/apache/http/impl/DefaultHttpRequestFactory.html


text:
Q: Split string into string arrays of X characters I have a string "thisisanexample". I want to split this into for example 4 char arrays like this:
group[0]="this"
group[1]="isan"
group[2]="exam"
group[3]="ple"

How can I do this?
Edit:
String str = "thisisanexample";
String[] arr = str.split("(?<=\\G.{4})");
c.drawText(arr[0], 100, 100, textPaint);
c.drawText(arr[1], 100, 200, textPaint);
c.drawText(arr[2], 100, 300, textPaint);

A: You've to split on empty character after every 4 characters. The following code will do that:
String str = "thisisanexample";
String[] arr = str.split("(?<=\\G.{4})");

Basically, it splits on empty space, which is preceded by - which is governed by look-behind (?<=...), any 4 characters. The \\G tells regex to start matching where the previous match ended.
If you feel a bit uncomfortable with regex, you can write a loop, that will iterate str.length() / 4 times. On each iteration, take the 4 characters starting from current index, using String#substring() method.


text:
Q: Is it possible to left-justify (rather than centre-justify) successive lines in a WinForms message box? Hopefully the question says it all.  We have some longish messages, separated by CrLf characters, and the lines come out centre-justified.
Can the lines be left-justified?
I can create a form and show it modally if I have to, but it would be nice not to have to.

Edit...
Apologies, people.  My bad... my damn fool question.
Turns out that the message box shown everywhere in my application is a custom one, and it inherits from a form, not from MessageBox.
Worse still, it was built with a label on it to display the text of the message... and, you guessed it, its TextAlign property was set to MiddleCenter.
I shall now go and bang my head on a spike as penance for troubling you good people...

A: The message box is left-aligned for me:
Option Strict On
Option Explicit On

Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        MessageBox.Show("It was the best of times, it was the worst of times." & vbNewLine & "The end.")
    End Sub
End Class


text:
Q: Python List - "reserving" space ( ~ resizing) I am given a list l and I want to do assignment:
l[index] = val

But there might be a case when the list is too small.
So, I want to ensure I have space for the new value.
Sometimes I need to fill the new space with empty strings '', and sometimes with other objects (like empty lists [], False or None).
For this task I use the following procedure:
def ResizeList(l, size, fill_with=None):
    l += [fill_with]*(size-len(l))

(note: it works even if size-len(l)<=0)
(note: as I am interested in reserving space, I intentionally DO NOT truncate it to a shorter list)
Like that:
ResizeList(l, index+1)
l[index] = val

(When filling with other object, it's like : ResizeList(l, index+1, []) )
Are there more pythonic ways of doing that? Are there some built-ins or library functions for doing this?
I am using mostly Python-3.x, but know-how about Python-2x is useful and welcome.
Clarification: Please, do not tell me about dict , cause I need list
For those who would like me to be more specific:
The problem statement states it's about list type. Using dict here is not an option or solution. There are reasons for that, specifically related to the domain (I am doing a prototype of an experiment that has to show some asymptotic behaviour, not - as probably you're used to - a prototype of a program. If it would be "just a prototype of a program", then I agree with using a dict and the other comments). I have the following assumptions:

*

*I have many many lists (need to care about memory and performance overhead)

*due to workflow and need of prototype, I cannot call a handcoded C/C++ extension

*during computation the final list size is unknown

*we know that in the and the lists will be dense

*list cells are written and overwritten in an unknown order

Those are just a few reasons why I have stressed that I need a list and not a dict.
For those interested in more details or who would like to discuss about dict, checkout how we discuss in comments HERE

A: If you're sure that a list -- and not, say, a dict -- is the best data structure for your use case, I propose the following class:
class rlist(list):
  def __init__(self, default):
    self._default = default
  def __setitem__(self, key, value):
    if key >= len(self):
      self += [self._default] * (key - len(self) + 1)
    super(rlist, self).__setitem__(key, value)

l = rlist(0)
print(l)
l[10] = 20
print(l)
l[5] = 14
print(l)

This class checks whether the index being assigned to is beyond the current length of the list, and automatically expands the list as required.
The code is compatible with both Python 2 and 3 (tested with 2.6.5 and 3.1.2).
This class could be handy if the structure is dense and you need to find the element by index as quickly as possible. If the structure is sparse, you should probably consider using a dictionary.

A: I came up with something that uses itertool.repeat().
import itertools

def assign(lst, idx, value, fill=None):
    diff = len(lst) - idx
    if diff >= 0:
        lst[idx] = value
    else:
        lst.extend(itertools.repeat(fill, -diff))
        lst.append(value)

That have the following behaviour:
>>> l = [0, 1, 2, 3, 4]
>>> assign(l, 2, 'new')
>>> l
[0, 1, 'new', 3, 4]
>>> assign(l, 8, 'new')
>>> l
[0, 1, 'new', 3, 4, None, None, None, 'new']
>>> assign(l, 10, 'new', fill=[])
>>> l
[0, 1, 'new', 3, 4, None, None, None, 'new', [], 'new']

Does this work for you?
Edit: Since the question was updated I've updated the answer.

A: Perhaps this does what you want:
def resize(l, newsize, filling=None):
    if newsize > len(l):
        l.extend([filling for x in xrange(len(l), newsize)])
    else:
        del l[newsize:]

A: Try this:
def ResizeList(some_list, length, null_item = None):
    return some_list + [null_item
                        for item in range(length - len(lst))]


text:
Q: How to edit XPS files? XPS files are Microsoft's rival to Adobe's PDF format.
How to edit or create new XPS files in Ubuntu?!

A: Master PDF Editor provides you advanced functions for working with PDF and XPS formats:

*

*Create new PDF and XPS files or edit existing ones.

*Add and/or edit bookmarks in PDF files.

*Encrypt and/or protect PDF files using 128 bit encryption.

*Convert XPS files into PDF.

*Add PDF controls (like buttons, checkboxes, lists, etc.) into your
PDFs.

*Import/export PDF pages into common graphical formats including
BMP, JPG, PNG, and TIFF.

*Free PDF Editor on Linux ( for non-commercial use)

Ubuntu users can install Master PDF Editor by using Ubuntu Software Center(Old versions)
sudo apt-get install master-pdf-editor

Official source

A: The only solution that I'm aware of isn't great... Through Google Drive (Docs).
http://googledocs.blogspot.be/2011/02/12-new-file-formats-in-google-docs.html

A: This is how I modify an XPS file :

*

*open the XPS using the document viewer.

*print the XPS in a file and choose SVG format.

*open it with Inkscape (https://inkscape.org/en/).

You can then modify it, render a high-resolution PNG, etc.
To create one, I would print in a file and choose PostScript format, I think this is the closest to XPS.

A: Converting from XPS
The package libgxps-utils includes tools that can be used to convert XPS files to JPG, PNG, PDF, PS, and SVG.
Editing
At this point, users may use any method they are aware of to edit the converted files.
Converting (via PS) to XPS
There is an output driver xpswrite that comes with Ghostscript.  In principle, it should be able to convert from any format gs can read, but the fonts of files I tested tended to become unreadable.
To get fonts to render properly in XPS, files need to first be converted to PS, independently of gs.  For instance, PDF files can be converted to PS with pdftops.  However, pdf2ps will not work because it is simply a script that calls gs.
pdftops input.pdf    # convert to ps first
gs -dNOPAUSE -dBATCH -sDEVICE=xpswrite -sOutputFile=output.xps input.ps

Viewing
Common PS/PDF viewers, such as Evince and Okular, can render XPS files for viewing.


text:
Q: How can I size table nodes in graphviz that contain bold text? I'm rendering a pipeline diagram with graphviz. Each node is a step in the pipeline and uses a table for layout. The top row is in bold and shows the name of the step. The other rows show the outputs of the step. Arrows between steps show dependencies.
digraph {
  node[shape=plaintext]

  A [
    label=<

FirstVeryLongVeryBoldStepName

→ out.txt

    >];

  B [
    label=<

SecondVeryLongVeryBoldStepName

→ out2.txt

→ out3.json

    >];

  A -> B
}

Here's how it renders:

The width of each box seems to be set based on the non-bold width of the text. If I remove the  tag, the layout looks just right:

How can I get the tight layout with the bold text? If it's helpful, here's a link to the example in Graphviz Online

A: It's interesting, that on on my machine your code renders fine (on both Mac with graphviz 2.41 and Ubundtu with graphviz 2.40: rendered.png). Maybe it depends on the font engine used during graphviz build.
In your situation you may just add three spaces at the end of each bold text node: link to fixed example
If the spaces are being eaten up by HTML parser (may occur especially if you are rendering svg), you can replace them with   symbol (non-breakable space).


text:
Q: How do make 500 Error redirect? I am trying to make 500, 404, etc. errors redirect. If you go to http://www.yoursite.com/934834984 it should redirect to http://www.yoursite.com/404. How do I make it do that? I tried using this code:
<meta http-equiv="refresh" content="0; url=http://yoursite.com/404" />

Keep in mind that I changed the domain to yoursite.com just for this question.

A: In Apache you can use ErrorDocument. So in your .htaccess file in the root of your domain you can add this to the end of the file.
ErrorDocument 404 /404.html

The files have to exist. Here is some more info as well.
http://support.hostgator.com/articles/custom-error-pages

A: You need to edit the .htacess file (with notepad) in your domain's root folder. Here are some common ones that you would add or change in the file.  Obviously change the directory and locations (the part in italics).  And don't include the numbers.  Or you can change them from your cpanel without having to mess with the .htacess file

*

*ErrorDocument 400 /errors/badrequest.html

*ErrorDocument 401 /errors/authreqd.html

*ErrorDocument 403 /errors/forbid.html

*ErrorDocument 404 /errors/notfound.html

*ErrorDocument 500 /errors/server.html

A: ErrorDocument 500 /errors/server.html not work for me
show in browser HTTP ERROR 500


text:
Q: Hourly cron job to save json data I would like to create a cron job which saves json data from an external url, hourly, to a mysql database. (http://dvcticker.bugs3.com/json-data.php)
I'm new to cron, so this is pretty much all I have:
0 * * * *
Sorry for my limited knowledge and thanks in advance for answering.

A: 0 * * * * your-script.php
You will need to set up an internal script to call the outbound URL for processing.
PHP example:
<?php
// your-script.php
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, 'http://dvcticker.bugs3.com/json-data.php');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);

    // connect to database and save $data to your table
?>

Bookmark this url. It is a cron tab generator. very useful.
http://cron.nmonitoring.com/cron-generator.html

A: It should be:
0 * * * * * /path/to/yourprogram

where yourprogram is the program (which could be a script in any language you like) that downloads the JSON data and puts it into your database.


text:
Q: read email messages from inbox with php every 15 seconds or so I'm trying to figure out a way to do the following with php:
Have a website (index.php) check an e-mail inbox every 15 seconds or so, read the subject line, and the contents of the message, and then display that message on the screen. The idea being it will display all the messages in the inbox on the index.php page as they get sent in. And I guess the index.php page will also have to refresh whenever there is a new message to display the content.
Thanks!

A: I think an interval of less than a minute is rather difficult to realize and/or rather expensive to run. If you need that high a frequency, you should be better off by writing a hook for your mail handler that gets triggered whenever new mail arrives. How to do that depends on your mail handler.

A: Bad idea.  If your page refreshes every 15 seconds, nobody will ever be able to click on anything because as soon as the page refreshes, it will start refreshing again.
What you probably want is something more ajaxy, like gmail uses.  This does the refresh in the background so the page itself doesn't refresh.  There are lots of tutorials on how to do this.  For example This, which you can extrapolate out to what you want.

A: Dump the email contents into a database or some kind of flat file and use its contents to display.
If your using gmail:
http://framework.zend.com/download/gdata

A: *

*Create a script that hooks or polls the mail server inbox for changes.

*Store new emails using memcached

*Create a RESTful web service that simply checks the memcached for new emails, returning as JSON

*Use jQuery or another javascript framework's AJAX functionality to retrieve new emails in JSON format from the RESTful web service and bind the results to the DOM of the current page.  Use javascript fade-in animation for better usability.


text:
Q: How to convert this map/flatMap into a for comprehension in Clojure? Given this Scala code:
def compute2(maybeFoo: Option[Foo]): Option[Int] =
  maybeFoo.flatMap { foo =>
    foo.bar.flatMap { bar =>
      bar.baz.map { baz =>
        baz.compute
      }
    }
  }

Which is then translated to this for comprehension:
def compute2(maybeFoo: Option[Foo]): Option[Int] =
  for {
    foo <- maybeFoo
    bar <- foo.bar
    baz <- bar.baz
  } yield baz.compute

My question is How to convert this map/flatMap into a for comprehension in Clojure?
Assumptions:

*

*If possible I'd like to use idiomatic Clojure (ie mapcat) to represent this rather than the algo.monads / fluokitten libraries. But if that is the best way to do it (I'm open to learning) then use that.

A: You probably wouldn't use Option in Clojure, but if the objects are inside collections something like this should work:
(let [maybe-foo [{:bar [{:baz [(fn [] 42)]}]}]]
  (for [foo maybe-foo
        bar (:bar foo)
        baz (:baz bar)]
    (baz)))
 ;=> '(42)

(let [maybe-foo [{:bar nil}]]
  (for [foo maybe-foo
        bar (:bar foo)
        baz (:baz bar)]
    (baz)))
;=> '()

(let [maybe-foo nil]
  (for [foo maybe-foo
        bar (:bar foo)
        baz (:baz bar)]
    (baz)))
  ;=> '()


text:
Q: How to prevent SSHFS mount freeze after changing connection after suspend? I am using SSHFS with reconnect attribute. It works fine, when I suspend notebook and start it again. But problem is when I take notebook somewhere - meaning different IP and different connection (might be Wifi or Ethernet).
Mounted SSHFS folder just freezes and also freezes all the applications which were using it. And the only solution to it I have so far is to use
sudo umount -f /mnt/sshfs_folder

Which is nowhere near to beeing good solution, but so far the only which works. Is there a way how to make SSHFS seemlessly take care of this problem so changing network connection after suspend will not cause any problems ?
Oh and I have Ubuntu 14.04, but I suppose that this is SSHFS specific.

A: I wrote a shell script called sshfs-reconnect with the following:
while true
do
    sshfs -f -o ConnectTimeout=3,ConnectionAttempts=1,ServerAliveInterval=5,ServerAliveCountMax=3 $@
    echo "disconnected from $@"
    sleep 3
    echo "retry $@ ..."
done

If I leave this running in the background, it has most of the desired behaviors:

*

*If the server disappears briefly, processes accessing the mount will hang until the server comes back

*If the server disappears for too long (about 15 seconds in this case) then waiting processes will get an I/O error

*If we try to access the mount again while the server is gone, we either get a "transport endpoint is not connected" error or file-not-found (I would prefer to get only the transport error, but haven't figured out how to achieve that)

*Once the server comes back, we can access the mount again with no intervention

Details about this solution:

*

*I do not use -o reconnect here because I do not want sshfs to attempt to reconnect indefinitely, since this causes any process waiting on the mounted filesystem to hang forever. Instead, I let sshfs disconnect after a certain timeout and let those waiting processes fail gracefully.

*The options ServerAliveInterval=5,ServerAliveCountMax=3 say that ssh checks every 5 seconds to see whether the remote server is still responding. If it does not receive a response after 3 of these checks, then it disconnects automatically. Thus any process waiting on this mount should hang about 15 seconds max.

*The options ConnectTimeout=3,ConnectionAttempts=1 are necessary because otherwise ssh will wait a very long time when attempting to reestablish connections, which again causes other processes to hang if they try to access the mount during this time.

A: More thorough answer here: SSHFS - auto reconnect.
In short, use:
# create local folder to mount into
mkdir -p ~/mnt/my_server

# now mount your SSH File System
sshfs -o reconnect,ServerAliveInterval=15,ServerAliveCountMax=3 \
username@server_hostname:/path/on/server/to/mount ~/mnt/my_server

To unmount the file system:
sudo umount ~/mnt/my_server

Added July 2022:
I am not sure, but it may be important to ensure that both sides have the same version of sshfs installed. That means that both the computer you are running sshfs on and the computer you are connecting to should have the same version. Check the version with sshfs -V. Here is an example run of that command on my Ubuntu 20.04 computer, for example, showing both the command and the output:
$ sshfs -V
SSHFS version 3.7.1
FUSE library version 3.9.0
using FUSE kernel interface version 7.31
fusermount3 version: 3.9.0

You can see that the last line above is the output from the command fusermount -V, which for me shows this:
$ fusermount -V
fusermount3 version: 3.9.0

I have used the above command on Ubuntu 14.04, 16.04, 18.04, and 20.04. I did not verify the sshfs versions prior to now (July 2022), so I cannot state what versions I had at the time I originally wrote this answer (Aug. 2017).


text:
Q: Monitor all network traffic going in and out a specific computer/ip address I'm looking for a tool under windows or mac that allows me to monitor (possibly in a simple way) the traffic going in and out of a computer of my network.
Long story short the residence where I live allows themselves to monitor the internet connection (and doesn't allow us to switch to another provider).
This annoys me on a personal level (I don't like the possibility of people checkin what I do without my knowledge as a general rule regardless of what I do) but also on a professional level (I sometimes work form home).
I'm using/trying out vpn providers (JAP, VyperVPN...) to avoid all this. it works fine with the http connections (if I run iptraces I end up in germany or US or UK ...) but I'm not sure for other applications such as online games, instant messaging softwares that use different ports.
So my question is how can I make sure that my internet traffic is using my vpn connection or not ?

A: Wireshark would do that for you on Windows and linux (Not sure about Mac). It uses WinPCap library and wraps in a nice UI for you to monitor the packets that you are interested. It allows you to listen to specific or all interfaces , so you can make sure your packets are going via the right interface

A: if you don't want them monitoring your internet usage, a vpn is a good solution, a vpn will encrypt all of your net traffic between your computer and the vpn gateway -- essentially you'd be surfing the web via a proxy and your landlords wouldnt be able to determine what you are doing.
assuming you are using a real vpn, and not just a browser based proxy solution, then the vpn should encrypt and tunnel all of your network traffic, this includes anything coming out of any port on your computer, not just http traffic.
when you install a vpn on your computer, the vpn creates a fake network device, and all of the vpn traffic gets tunneled to the vpn gateway. you can verify this by looking at your computer's routing tables. there are some vpns which allow for split traffic (split tunneling), e.g. traffic to certain domains gets tunneled through the vpn and others goes in the clear, but this is the rarity, most vpns will tunnel all of your traffic, which seems to be what you are looking for.
just make sure that your vpn uses an encryption protocol, there are some that don't -- this would defeat the whole purpose of your vpn.


text: Q: Folder Mirroring onto NAS I have a Win7 setup where I need to mirror, a local folder onto a NAS. I've tried Microsoft SyncToy but that is entirely too slow and produces inaccurate results. A requirement is that open files must be copied so Robocopy will not work. I believe the only way this will work is something that is built using VSS.


text:
Q: Change Domain VirtualHost paths in Plesk (Apache) I have a domain that'll be using Zend Framework and I need to modify the documentroot for this particular domain to resolve to Zend's path.
Anyone know how to update the virtualhost on a particular domain?

A: Typically, you don't have to modify the document root.
Put your application files one level above your document root, and put the contents of the zend public folder in whatever your document root is (e.g. public_html or htdocs).


text:
Q: How can I modify the default locale in android? By default, the android system's default location is US and language is en.
But I want to set the default location to another country. So, the users will see their mother language when the first time startup android.
I have tried to modify the code(/dalvik/libcore/luni/src/main/java/java/util/Locale.java), changed the locale's default value. But no effect.
Can you tell me how to set the default location?
*I want to make an android image, then burn it to the device, when the android starts up the first time,  I want its os language is not English but another language.

A: thanks for all you reply.
i have found the method to change the default language.
just modify the file(build/core/Makefile).
set PRODUCT_DEFAULT_LANGUAGE and PRODUCT_DEFAULT_REGION to what you want to set.

A: I make customer build via build/target/product/core.mkSamples:PRODUCT_PROPERTY_OVERRIDES := \
    ro.config.notification_sound=OnTheHunt.ogg \
    ro.config.alarm_alert=Alarm_Classic.ogg \
    ro.config.ringtone=BirdLoop.ogg \
    persist.sys.language=zh \
    persist.sys.country=CN \
    persist.sys.timezone=Asia/ShanghaiThis is what i do to make a simplified-chinese customer build.

A: Use java.util.locale
and use method getISOcounty, getISOLanguage etc...
to know more in detail go through
http://developer.android.com/reference/java/util/Locale.html

A: Have you already checked out this part?
 private Locale() {
   languageCode = "en"; //$NON-NLS-1$
   countryCode = "US"; //$NON-NLS-1$
   variantCode = ""; //$NON-NLS-1$
 }

It starts at line 212 in Locale.java. Is this the part where you've set your default values? If so then please post that bit up so I can check it out.
EDIT: Actually if you can post your whole Locale.java up on Pastebin. http://pastebin.com/

A: The easiest way might be to insert a local SIM before boot. But in my case the timezone wouldn't be set automagically not even then.
For lineage 18, first boot setup, custom build:
Add base locale as top on PRODUCT_LOCALES in build/target/product/full_base.mk like
PRODUCT_LOCALES := de_DE
To set the default timezone via makefiles didn't work for me, but it worked to hardcode it in the SetupWizard.
So change line 84 in packages/apps/SetupWizard/src/org/lineageos/setupwizard/DateTimeActivity.java from
mCurrentTimeZone = TimeZone.getDefault();
to:
mCurrentTimeZone = TimeZone.getTimeZone("Europe/Amsterdam");
Check first which timezones are at hand by browsing the list!


text:
Q: VB.NET: Clearing a picturebox None of the code that I have seen so far to clear a picturebox achieved what I needed.
I wanted to clear a picturebox so that I can draw something new over a "blank" background.
Here is my code:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    PictureBoxClear(Me.PictureBox1)

    m_i = m_i + 1
    Dim nPT As New Point(0, 0)
    Me.ImageList1.Draw(Me.PictureBox1.CreateGraphics, nPT, m_i)

End Sub
Public Sub PictureBoxClear(ByRef pb As PictureBox)

    pb.Image = Nothing

End Sub

Saying
 .Image = Nothing

seems to completely remove the image so that I can not really draw something over it afterwards.
I just wanted to clear my picturebox so that it would then ready be get some drawing again.
Thank you!

A: You can try replacing it with a brand new image:
pb.Image =  New Bitmap(pb.ClientSize.Width, pb.ClientSize.Height)


text:
Q: Rewriting code for affiliate links Let me preface this by saying that writing .htaccess files drives me completely insane...
I've got a sales website with a bunch of affiliates that should redirect to a shop site and then send the user back to the original sales site.
So what I want to do is have something like:
www.example.com/item/randomaffiliatenumber

(the "promo" directory doesn't actually exist).
redirect to:
subdomain.shop.com/item/randomaffiliatenumber

I mean I suppose I could MAKE an "item" directory with the same contents as "/" but that shouldn't be necessary.  The main thing I want to do is have the affiliate code be passed to the shop site.
I tried:
RewriteRule ^item/(.*)$ http://subdomain.shop.com/item/$1

...but that didn't work.(Gave me a 404 saying "promo" wasn't found).

A: Meh... it was easier than I thought:
RewriteEngine on
RewriteRule ^item/(.*) https://subdomain.shop.com/item/$1 [NC,QSA]

Just needed to make those few adjustments and it worked. So I was actually closer than I thought.
In case anyone is wondering (.*) turns into the variable $1 in the second half. That should be enough to get you to where you want to go.


text:
Q: RailsTutorial: diff-lcs-1.1.3 can not be found http://ruby.railstutorial.org/chapters/static-pages#top
i was playing around with that tutorial and when executing:
rails generate rspec:install

i get this:
Could not find diff-lcs-1.1.3 in any of the sources
Run 'bundle install' to install missing gems.

when running bundle show:
...
* builder (3.0.0)
* bundler (1.1.rc)
* diff-lcs (1.1.3)
* erubis (2.7.0)
* hike (1.2.1)
...

and i made sure its installed....
i can find it in the system etc....
any ideas? never really looked into ruby so that might be why i am failing already, haha

A: You should run bundle install first as mentioned in the error message above
Run bundle install or bundle install --without production first
and then run rails g rspec:install
I highly recommend you check:
http://ruby.railstutorial.org/chapters/static-pages#code-gemfile_rspec
and run bundle install.
I also wonder if you installed RVM successfully.
If you fail to install gems, I think you should go over the previous part again.


text:
Q: .NET Core dynamic shared files between projects I am using .NET Core 3.1. Let's say that I have the following solution structure:
MySolution
    ClassLibrary
        Files
            a.txt
            b.txt
        GetFile.cs
    Project1
    Project2
    ...

And let's say that GetFile.cs has a function ReadFile which reads the file from Files and returns its content.
public class FileReaderService : IFileReaderService
{
    private readonly IHostEnvironment _env;

    public FileReaderService(IHostEnvironment env)
    {
        _env = env;
    }

    public string ReadFile(string fileName)
    {
        var currentPath = _env.ContentRootPath; // not correct
        return "";
    }
}

However, when I try to get the current directory in ReadFile with _env.ContentRootPath, it returns the directory of calling project. I don't want it to be dependent on calling project.
How can I achieve that each project will be able to call ReadFile and that correct file from Files will be returned? I need to be able to add, remove and change these files while the app is running.
I have found some questions on SO but they all seem to be outdated. I need a solution which will work on .NET Core.

A: Instead of using the environment to determine the root file path, set it at the configuration level (ex appSettings.json ) and inject that path into the service itself.  Either project can set its own path, use the same one, or both retrieve from some external configuration instead of appSettings.
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1


text:
Q: How do I extract Portal 2 sound effects? Okay, so I have Portal 2 on my PC. I would like to use one of its sound effects for a little project, so I started searching the installed files. Well, eventually I found a bunch of "sound" files. I tried to run them, but apparently I can't.
When I go to properties, the file type says: Sound on format AU (.snd)
I don't get it (is the file .au or .snd?), how can I use such file? How could I convert it to, say, .mp3?

A: Your best bet is using VLC. Not only can it play all the waves, but it can convert them as well.
It has a convert option in the File menu.

A: All the sound files in the game are in the WAV format, stored within the VPK (Valve Package) files.
Use GCFScape and open up the Portal 2 content file, found at \steamapps\common\portal 2\portal2\pak01_dir.vpk (for some reason it's unlike TF2 and HL2 which use .gcf's)
There will be a directory structure visible in the program, browse to \root\sound\ and look through the subdirectories for sound effects.  Some sound like throwbacks to Portal 1, and others seem like total cruft from HL2, but everything should be in there, though with perhaps confusing names.


text:
Q: Horizontal Scroll on IE8 + half black section Below website is showing horizontal scroll bar with black-half portion. On chrome and FF its ok, but on IE8 it have design issue.
www.aftermoonsolar.com is the website.

A: Setting the row width to 100% makes the black section go away. You end up with some unused space along the right side, but you might be able to fix that.
.row {
    width: 100%
}

If it's only a problem in IE 8, you'll probably want to put that in an IE8-specific stylesheet (or in conditional comments.)


text:
Q: Namespace naming convention when [CompanyName] starts with a lower case "i" My company name starts with a lower case "i".  For example: iWare (this is not the real company name, but it demonstrates the purposes).
Because of this I find that I am constantly having to fight StyleCop and Resharper due to the namespace naming rules / conventions.
Does anyone have any ideas how should I be naming my namespaces (and sometimes classes).
EG.
namespace iWare.Product.X
{
    ...
}

As you can imagine, most of the tools shown above do not like this.  Are there any suggestions as to what an alternative should be? I have tried suppressing the error using the following:
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Reviewed. Suppression is OK here.")]
namespace iWare.Product.X
{
    ...
}

But, this results in the following error: A namespace declaration cannot have modifiers or attributes
Any ideas?

A: Brett's answer addresses the issue with tools, but to answer the question in the title (what namespace-naming convention should be used when a company's name begins with a lowercase letter):
This MSDN article, linked to from this other answer, states,

If your brand employs nontraditional casing, you should follow the casing defined by your brand, even if it deviates from normal namespace casing.

So according to Microsoft the correct namespace name in your example would in fact be iWare.Product.X, with a lowercase "i".

A: it seems like you're using iWare, or your company name, as your root namespace.
On my projects, I generally specify my root namespace in/using the property window of MyProject, or MenuItem 'Project' > 'Properties' > 'Application' - 'root namespace' textbox on right.
Thus, I don't specify it in my coding at all, unless I'm referencing it from another component/project as an import.


text:
Q: How can I hack a background image into Google Chart Tools' dynamic (JavaScript/SVG) chart? I'm updating an older data visualization module which used the Google Image Chart API. Now, we're switching to the new(er) Visualization API, which uses JavaScript to generate dynamic charts in the browser, within a specified
 container.
We have a need to present the chart with a background image (for branding purposes). However, the only thing I've been able to accomplish, given the configuration options in API reference, is to change the background colour.
If I embed a background image into the
 the Chart is drawn into, the chart (obviously) just overlays it.
Is there a JavaScript or HTML5 solution to my problem that I'm totally unaware of?
(I'm somewhat new to JavaScript, to thank you for bearing with what may actually be a trivial -- or clearly impossible -- problem!)

A: You might want to wrap your chart's target element with another one and change the parent's background to the image you want, while removing the background of the child.
for example, HTML

and CSS
#brand_div{
    background: url(<SOME-URL>) no-repeat;
}

And of course in your chart options in JavaScript
var options = {
    ...
    backgroundColor: 'none'
};

I put an example here http://jsfiddle.net/jaimem/jaxfz/

A: Just in case someone has the same problem as me, you can also fix the background to the chart only, and not the entire div (which will add background to the title, axis, etc.)
You can do this doing something like this:
In Html, as jaime suggested:

In css, as jaime suggested:
#brand_div{
    background: url(<SOME-URL>) no-repeat;
}

In javascript:
google.charts.load("current", {packages:["corechart"]});

google.charts.setOnLoadCallback(drawChart);

function drawChart() {
   var data = google.visualization.arrayToDataTable([
     ['ID', 'X', 'Y', 'Temperature'],
     ['',   80,  167,      120],
     ['',   79,  136,      130],
     ['',   78,  184,      50],
     ['',   72,  278,      230],
     ['',   81,  200,      210],
     ['',   72,  170,      100],
     ['',   68,  477,      80]
   ]);

   var options = {
     colorAxis: {colors: ['yellow', 'red']},
     width: 450,
     height: 300,
     title: 'My Daily Activities',
     backgroundColor: 'none' // this is important!
   };

   var chart = new google.visualization.BubbleChart(document.getElementById('chart_div'));
   chart.draw(data, options);

   // this two lines are the ones that do the magic
   var boundingBox = chart.getChartLayoutInterface().getChartAreaBoundingBox();
   $('#brand_div').css('background-position', boundingBox.left + "px " + boundingBox.top + "px").css('background-size', boundingBox.width + "px " + boundingBox.height + "px");
}

All this code was written using jaime's suggestion, google chart's documentation and the comments on this stack overflow question


text:
Q: Safe removal of a node in a concurrent linked list I'm currently reading the book APUE. When I read the chapter about pthread reader/writer-lock, I have a question about its implementation of concurrent queue using reader/writer-lock.
struct queue {
    struct job *q_head;
    struct job *q_tail;
    pthread_rwlock_t q_lock;
};

/*
* Remove the given job from a queue.
*/
void
job_remove(struct queue *qp, struct job *jp)
{
    pthread_rwlock_wrlock(&qp->q_lock);
    if (jp == qp->q_head) {
        qp->q_head = jp->j_next;
        if (qp->q_tail == jp)
            qp->q_tail = NULL;
        else
            jp->j_next->j_prev = jp->j_prev;
    } else if (jp == qp->q_tail) {
        qp->q_tail = jp->j_prev;
        jp->j_prev->j_next = jp->j_next;
    } else {
        jp->j_prev->j_next = jp->j_next;
        jp->j_next->j_prev = jp->j_prev;
    }
    pthread_rwlock_unlock(&qp->q_lock);
}

My question is that how this implementation can ensure that a struct job is removed from the linked list only once. From my understanding, two threads can be scheduled so that they are just before the line pthread_rwlock_wrlock. Then the struct job *jp might be freed twice. If struct job * is a dynamically allocated data structure, this might lead to a double-free bug. Any advice?

A: Your code has a race condition in it.  Other changes can potentially happen to the queue between two threads obtaining a write lock on the queue and then trying to remove the same node.  Other nodes can be removed, other nodes can be added.  So if thread A removes a node, changes happen, and then thread B tries to remove the same node again, your queue can be corrupted.
The code needs information to let it know that the node has already been removed.
See the added comments, and the code to fix the race condition:
struct queue {
    struct job *q_head;
    struct job *q_tail;
    pthread_rwlock_t q_lock;
};

/*
* Remove the given job from a queue.
*/
void
job_remove(struct queue *qp, struct job *jp)
{
    // we assume here that jp is actually in the queue
    pthread_rwlock_wrlock(&qp->q_lock);

    // at this point, jp may no longer be in the queue,
    // and in fact, the queue may be completely different.
    // thus, any modification to the queue based on the
    // assumption that jp is still part of the queue
    // can lead to corruption of the queue

    // so check if jp has been removed - we'll later set
    // both j_next and j_prev to NULL after jp is
    // removed from the queue - and if they're both
    // NULL here that means another thread already
    // removed jp from the queue
    if ( !(jp->j_next) && !(jp->j_prev) ) {
        // empty statement - jp is already removed
        ;
    }
    else if (jp == qp->q_head) {
        qp->q_head = jp->j_next;
        if (qp->q_tail == jp)
            qp->q_tail = NULL;
        else
            jp->j_next->j_prev = jp->j_prev;
    } // and this brace was missing in your posted code...
    else if (jp == qp->q_tail) {
        qp->q_tail = jp->j_prev;
        jp->j_prev->j_next = jp->j_next;
    } else {
        jp->j_prev->j_next = jp->j_next;
        jp->j_next->j_prev = jp->j_prev;
    }

    // make sure data in jp no longer refers to
    // the queue - this will also tell any other
    // thread that accesses jp that it's already
    // been removed
    jp->j_next = NULL;
    jp->j_prev = NULL;

    pthread_rwlock_unlock(&qp->q_lock);
}

You also need to check how jp gets free()d or deleted.  Multiple threads can't be allowed to do that.


text:
Q: How to influence code-completion suggestions in Eclipse? I like the time-saving convenience of using code completion with Ctrl-Space in Eclipse.  (I'm currently using Eclipse Oxygen.)  However, sometimes I wish I could change the order of suggestions within the drop-down menu.  In particular, I get frustrated with the suggestions when I use completions with Apache's Logger class:

The suggestion at the top of the list is a debug variant with nine arguments.  Because Eclipse usually provides me the best choice first, I often accidentally choose the nine-argument variant, instead of the single-argument variant that is almost always what I want.  Then I have to undo the selection I made, and do it over.  This may waste several seconds of my life.
Is there any way to get Eclipse to put the one-argument variant at the top of the list?  I can't imagine that too many people prefer calling debug with nine arguments.

A: As far as I know, it's not possible.
But there are few option you could try.
Go to Window -> Preferences -> Java -> Editor -> Content Assist.
There you'll find 2 sorting and filtering options - 'by relevance' and 'alphabetically'.


text:
Q: Composer install doesn't install packages when running in Dockerfile I cannot seem to run composer install in Dockerfile but I can in the container after building an image and running the container.
Here's the command from Dockerfile:
RUN composer require drupal/video_embed_field:1.5
RUN composer install --no-autoloader --no-scripts --no-progress

The output is:
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Nothing to install or update

But after running the container with docker-compose:
...
drupal:
    image: docker_image
    container_name: container
    ports:
      - 8081:80
    volumes:
      - ./container/modules:/var/www/html/web/modules

    links:
      # Link the DB container:
      - db

running docker exec composer install will install the packages correctly:
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Package operations: 1 installs, 0 updates, 0 removals
...
Generating autoload files

I am assuming that the composer.json and composer.lock files are correct because I can run the composer install command in the container without any further effort, but only after the container is running.
Update
Tried combining the composer commands with:
RUN composer require drupal/video_embed_field:1.5 && composer install

Same issue, "Nothing to install or update". Ultimately I would like to continue using seperate RUN statements in Dockerfile to take advantage of docker caching.

A: Your issue is coming from the fact that, docker-compose is meant to orchestrate multiple docker container build and run at the same time and it somehow is not really showing easily what it does behind the scene to people starting with docker.
Behind a docker-compose up there are four steps:

*

*docker-compose build if needed, and if there is no existing image(s) yet, create the image(s)

*docker-compose create if needed, and if there is no container(s) existing yet, create the container(s)

*docker-compose start start existing container(s)

*docker-compose logs logs stderr and stdout of the containers

So what you have to spot on there, is the fact that action contained into you Dockerfile are executed at the image creation step.
When mounting folders is executed at start of containers step.
So when you try to use a RUN command, part of the image creation step, on files like composer.lock and composer.json that are mounted on starting step, you end up having nothing to install via composer because your files are not mounted anywhere yet.
If you do a COPY of those files that may actual get you somewhere, because you will then have the composer files as part of your image.
This said, be careful that the mounted source folder will totally override the mounting point so you could end up expecting a vendor folder and not have it.
What you should ideally do is to have it as the ENTRYPOINT, this one happens at the last step of the container booting.
Here is for a little developing comparison: a docker image is to a docker container what a class is to an instance of an class — an object.
Your container are all created from images built possibly long time before.
Most of the steps in your Dockerfile happens at image creation and not at container boot time.
While most of the instruction of docker-compose are aimed at the automatisation of the container build, which include the mounting of folders.

A: Just noting a docker-compose.yml approach to the issue when the volume mount overwrites the composer files inside the container:
docker-compose.yml
environment:
  PROJECT_DIR: /var/www/html
volumes:
  - ./php/docker/entrypoint/90-composer-install.sh:/docker-entrypoint-init.d/90-composer-install.sh

composer-install.sh
#!/usr/bin/env bash

cd ${PROJECT_DIR}
composer install

This runs composer install after the build, using the docker-entrypoint-init.d shell script


text:
Q: HTML images conditional downloading I have something like this:

    ...

The div should only be shown if the width of the viewport is greater than 300px.
Since the images are very large, I dont want them to be downloaded when the width is lower than 300px. But when the width is greater than 300px I need to start downloading them as soon as possible.
Also, this should work on a lot of browsers on a lot of devices so I want to make it as robust as possible.
I was thinking in using https://github.com/sebarmeli/JAIL and call the jail function on $(document).ready, but I don't know if there is a better solution.
Any recommendations?

A: I recommend taking a look at Scott Jehl's picturefill solution. It takes a somewhat similar approach to JAIL in terms of implementing a no-js solution using the noscript tag to provide the fallback image, but it avoids the initial http request made for the placeholder .gif.

A: You can try use CSS @media (min-width: 300px) { … }

A: Put a $(document).ready function, test the viewport (or the render area available for the image, accounting for body and other element's margin, paddings, etc) width with a conditional statement, and call the jail function if it passes.
You could place a width-greedy-zero height (with css) empty element where the images are supposed to be loaded, and test how much width it can get by selecting him via jquery. If its width is greater than 300, call the JAIL.


text:
Q: how to increase current in this given circuit I am am a beginner to this not having background from this feild  n i I have a transformer less circuit which gives out 12vdc and 30 mamp  how to increase the current to 2 amp

A: First, and most important, this circuit is not safe. A mistake putting it together can kill you or someone else. Do not use it for anything.
It definitely will not work well at 2 amps. Zener diode regulators work by converting the extra current capacity of the power supply to heat. 2 amps at 12 volts is a huge amount of power to waste.
Passerby's answer is the right one. Buy an AC-DC converter. Don't try to build your own if you don't have the knowledge.

A: Easiest solution, cut that circuit out, and use a commercial 120/240V mains to 12V 2 Amp power supply. Its not feasible to modify the existing circuit.

A: Not using that circuit!
At the moment it is the 0.47 uF capacitor that is dropping about 220V AC across it (due to its reactance). Using a bit of handwaving you could argue that the current taken from the AC is ~30mA AC therefore the reactance of the capacitor is 220/0.03 = 7333 ohms. This would be a capacitance of 0.434 uF at 50 Hz.
To take 2A, you need a capacitor that has a value that is 2/0.03 times higher i.e. about 30uF and rated at 450V. How big is one of these?
Here's one: -

I suggest you go researching on on ebay to get it's large dimensions. Please not that it cannot be an electrolytic type.
Then you need to consider that off-load the 2A is flowing into the zener diode - you'll need a zener diode rated at about 30 watts. The one below is rated at 25 watts and will require a sizable heatsink: -


text:
Q: EntityManagerFactory is closed after application restarted with spring-boot-devtools I was looking into many Q&A in StackOverflow, none of them solved my issue or not matching my case. For example the following questions.

*

*EntityManagerFactory is closed when page is reloaded

*EntityManagerFactory is closed

*EntityManagerFactory is closed
What my issue is,
I am working on SpringBoot v2.2.5.RELEASE and MariaDB. I have added the spring-boot-devtools in my pom as below.
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>

My DataSource configuration in application.properties as below
spring.jpa.generate-ddl=false
spring.jpa.hibernate.ddl-auto = validate
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.datasource.url=jdbc:mysql://xxx.xxx.xxx.xxx/db_name_here?useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=xxx
spring.datasource.password=xxx
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver

I am running the application with following command via command line
mvn spring-boot:run

as expected whenever any files change in the classpath, applications using this spring-boot-devtools cause the application to restart. Once after the application is restarted, if I am trying to relogin to the application, I am getting the below error.
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.IllegalStateException
: EntityManagerFactory is closed
// truncated
Caused by: java.lang.IllegalStateException: EntityManagerFactory is closed
        at org.hibernate.internal.SessionFactoryImpl.validateNotClosed(SessionFactoryImpl.java:507) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]

Only after stopping the process with CTRL+C and re-run the command, the application is working without entity manager issue. Please advice.

A: Encountered this exception when EnableJpaRepositories attribute was missing in the main application class from Spring Boot:
@SpringBootApplication
@EnableJpaRepositories
public class FooApplication {

    public static void main(String[] args) {
        SpringApplication.run(FooApplication.class, args);
    }

}

A: Check the stacktrace. It will probably give a service method. This service method must have a @Transactional annotation.


text:
Q: Missing Gateway in Azure Classic Virtual Network Our Gateway in our Virtual Network (classic) seems to have disappeared.

There is also GatewaySubnet defined as in below....

, so when I attempt to re-create the gateway it looks like this..

Notice how in the above screenshot the subnet name appears grayed out. When I try to enter the address range for the "Gateway Subnet" from the 2nd screenshot, it is rejected, because the range is already in use. I tried to delete the "Gateway Subnet" and re-create it, but that did not work either..
Somethings seems corrupted here.. any idea what is going on?


text:
Q: Parser XML Windows Phone C# I am trying to parse xml for windows phone web in C # and failed to find the result to obtain the data, the problem is in how I ask
var rssFeed = XElement.Parse(response);
var channel = rssFeed.Descendants("feed");
var items = (from item in channel.Elements("entry") select new ItemsLoad

I can not find a way to get results, any ideas? Help please!
public class ItemsLoad
{
    public string Title { get; set; }
    public string Link { get; set; }
    public string Description { get; set; }
    public string PubDate { get; set; }

    public static List<ItemsLoad> GetElements(string response)
    {
        var rssFeed = XElement.Parse(response);
        var channel = rssFeed.Descendants("feed");
        var items = (from item in channel.Elements("entry")
            select new ItemsLoad
            {
                Title = item.Element("title").Value,
                Link = item.Element("link").Value,
                Description = item.Element("summary").Value,
                PubDate = item.Element("published").Value
            });
    return items.ToList();
}

my full code
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
      xmlns:media="http://search.yahoo.com/mrss/"
      xmlns:dc="http://purl.org/dc/elements/1.1/"
      xmlns:dcterms="http://purl.org/dc/terms/">
   <id>index.xml</id>
   <title>Last</title>
   <updated>2014-10-13T06:17:44+00:00</updated>
   <author>
      <name>John</name>
      <email>John dot com</email>
      <uri>this-is-test.com</uri>
   </author>
   <entry>
      <id>213213</id>
      <published>2014-09-17T10:45:36+00:00</published>
      <title xml:lang="en">Test</title>
      Test xml windows phone
      <link rel="alternate"
            type="text/html"
            href="http://www"
            title="story">
         <media:content>
            <media:thumbnail url="tese.jpg"
                             width="106"
                             height="60">

            </media:thumbnail>
            <media:thumbnail url="test.jpg"
                             width="144"
                             height="81">

            </media:thumbnail>
         </media:content>
      </link>
   </entry>
</feed>

this is the xml file
Thankyou

A: There's two issues on your code:

*

*After parsing the XML, feed is already the current node, so rssFeed.Descendants("feed") won't find anything

*The elements have a namespace (the xmlns="..." on feed), you need to provide it when parsing the nodes:
public static List<ItemsLoad> GetElements(string response)
{
    const string Namespace = "http://www.w3.org/2005/Atom";

    var rssFeed = XElement.Parse(response);

    var items = (from item in rssFeed.Elements(XName.Get("entry", Namespace))
        select new ItemsLoad
        {
            Title = item.Element(XName.Get("title", Namespace)).Value,
            Link = item.Element(XName.Get("link", Namespace)).Value,
            Description = item.Element(XName.Get("summary", Namespace)).Value,
            PubDate = item.Element(XName.Get("published", Namespace)).Value
        });
    return items.ToList();
}


text:
Q: Hibernate query cache applicable for native queries? I have below code snippet  where I am using hibernate query. It works fine. when I fire execute this code second
time query is not fired as it is picked from query cache
   Session session = hibernateFactory.openSession();
    Query employeeQuery=session.createQuery("from Employee where employeeId=1");//line 1
    employeeQuery.setCacheable(true);
    Employee employee1=(Employee)employeeQuery.uniqueResult();
    session.close();

But as soon as I replace line1 in above code snippet with below line I get exception
Query employeeQuery=session.createSQLQuery("select * from Employee where employeeId=1");

Execption is
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at org.hibernate.type.TypeHelper.disassemble(TypeHelper.java:146)
at org.hibernate.cache.StandardQueryCache.put(StandardQueryCache.java:106)
at org.hibernate.loader.Loader.putResultInQueryCache(Loader.java:2434)
at org.hibernate.loader.Loader.listUsingQueryCache(Loader.java:2321)
at org.hibernate.loader.Loader.list(Loader.java:2268)

Is query cache is not applicable for native queries?
Update:- I think Query cache is applicable for HQL not for Native SQL. But in hibernate documentation its not written anywhere. So just wondering am I missing anything here

A: SQLQuery not support cache. It could help you.
http://www.tutorialspoint.com/hibernate/hibernate_caching.htm
It's better use the hibernate SQL sintaxis.


text:
Q: how can I loop for every GerritInfo['GerritInfo'] I have the following code where I want to loop over every GerritInfo['GerritInfo'][0...n] and add logic based on that,currently am doing it only for first item,i.e.,
GerritInfo['GerritInfo'][0] ,how can loop for every GerritInfo['GerritInfo'] assuming we dont know how many items are in GerritInfo['GerritInfo']
#!/usr/bin/python
GerritInfo = {'Assignee': 'username', 'RCAInfo': 'Provided', 'PLProductLine': 'LNX.LA.0.0', 'GerritInfo': [{'Url': 'https://review-android.company.com/761190', 'Status': 'MERGED', 'kw_ran': 'kw running', 'Info': 'ALREADY INTEGRATED', 'lookahead_ran': 'lookahead running'}, {'Url': 'https://review-android.company.com/777849', 'Status': 'NEW', 'kw_ran': 'kw did not run', 'Info': 'Available', 'lookahead_ran': 'lookahead running'}], 'CRId': '664310', 'CRStatus': 'Fix', 'RNotesStatus': 'Yes', 'TargetName': 'MSM8916', 'IsDevComplete': 'True'}

if (('Not Provided' in GerritInfo['GerritInfo'][0]['Url'] or 'Wrong Gerrit Provided' in GerritInfo['GerritInfo'][0]['Url']) or ('NEW' in GerritInfo['GerritInfo'][0]['Status'] or 'ABANDONED' in GerritInfo['GerritInfo'][0]['Status'] or 'Yes' not in GerritInfo['RNotesStatus'] or 'Provided' not in GerritInfo['RCAInfo'] or 'False' in str(GerritInfo['IsDevComplete']))):
    print "Inside if"
else:
    print "in else"

A: The data in GerritInfo['GerritInfo'] is just a list, so you can loop over it with the normal idiom.
for gerrit in GerritInfo['GerritInfo']:
    print gerrit

Edit:
Just wrap your existing logic in the for loop.  For example
for gerrit in GerritInfo['GerritInfo']:
    if (('Not Provided' in gerrit['Url'] or 'Wrong Gerrit..))
        print "inside if"


text:
Q: Reverse proxy nginx docker container and ELB I'm trying to set up multiple apps listening on different ports on the same machine. All apps are based on docker containers. And I want each app to have different subdomain names.
I have configured multiple subdomains to point to the same elb.
I have the following setup:
ELB with SSL forwarding to specific CNAME which will forward eventually to an EC2 instance traffic to port 80. On the EC2 instance i have an nginx container running taken from here . I have a docker container which exposes port 3001 and setts a virtual host with the sub domain configured, as mentioned in the link.
I'm trying to redirect every http request to a subdomain sub.example.com to the container in the instance.
I keep getting 502 from the nginx and the following error log:
2018/07/14 08:45:58 [error] 137#137: *20 connect() failed (111: Connection refused)
while connecting to upstream, client: 111.111.111.11, server: sub.example.com,
request: "GET / HTTP/1.1", upstream: "http://172.17.0.2:3001/", host: "sub.example.com"

Where the 172.17.0.2 is my container i'm trying to reach to.
This is the default conf of the nginx take from the container:
# If we receive X-Forwarded-Proto, pass it through; otherwise, pass along the
# scheme used to connect to this server
map $http_x_forwarded_proto $proxy_x_forwarded_proto {
  default $http_x_forwarded_proto;
  ''      $scheme;
}
# If we receive X-Forwarded-Port, pass it through; otherwise, pass along the
# server port the client connected to
map $http_x_forwarded_port $proxy_x_forwarded_port {
  default $http_x_forwarded_port;
  ''      $server_port;
}
# If we receive Upgrade, set Connection to "upgrade"; otherwise, delete any
# Connection header that may have been passed to this server
map $http_upgrade $proxy_connection {
  default upgrade;
  '' close;
}
# Apply fix for very long server names
server_names_hash_bucket_size 128;
# Default dhparam
ssl_dhparam /etc/nginx/dhparam/dhparam.pem;
# Set appropriate X-Forwarded-Ssl header
map $scheme $proxy_x_forwarded_ssl {
  default off;
  https on;
}
gzip_types text/plain text/css application/javascript application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
log_format vhost '$host $remote_addr - $remote_user [$time_local] '
                 '"$request" $status $body_bytes_sent '
                 '"$http_referer" "$http_user_agent"';
access_log off;
resolver 172.31.0.2;
# HTTP 1.1 support
proxy_http_version 1.1;
proxy_buffering off;
proxy_set_header Host $http_host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $proxy_connection;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $proxy_x_forwarded_proto;
proxy_set_header X-Forwarded-Ssl $proxy_x_forwarded_ssl;
proxy_set_header X-Forwarded-Port $proxy_x_forwarded_port;
# Mitigate httpoxy attack (see README for details)
proxy_set_header Proxy "";
server {
    server_name _; # This is just an invalid value which will never trigger on a real hostname.
    listen 80;
    access_log /var/log/nginx/access.log vhost;
    return 503;
}
# ssrv.talking-ads.com
upstream ssrv.talking-ads.com {
                ## Can be connected with "bridge" network
            # display
            server 172.17.0.2:3001;
}
server {
    server_name ssrv.talking-ads.com;
    listen 80 ;
access_log /var/log/nginx/access.log vhost;
    location / {
        proxy_pass http://ssrv.talking-ads.com;
    }
}


text:
Q: i++ still working for immutable Integer in Java? I know Integer is immutable in Java. But I tried this:
Integer i = 4;
i++;
System.out.println(i); // output is 5

Why the self-increment is still working? Did Java create a new Integer object?

A: i++;

is equivalent to:
i = i + 1;

which i now refers to a different Integer object (5).


text:
Q: Formula to look up cell in a list I'm trying to write a simple formula that looks up a cell's value in a list. If value is in list then return "4512 Marked Up". If not, return blank.
For example, IF(A1=VENDORS,"4512 Marked Up","")
Where VENDORS is the list
But I can't get it to work properly.
Thanks


text:
Q: problem to show progress bar i want to show spinning wheel progress but it doesn't show anything.
final ProgressDialog dialog = ProgressDialog.show(AppListActivity.this,
            "", "Loding...", true);
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            dialog.dismiss();
        }
    };
    Thread checkUpdate = new Thread() {
        public void run() {

            // Set our custom array adapter as the ListView's adapter.
            listAdapter = new AppArrayAdapter(AppListActivity.this,
                    appsList);
            mainListView.setAdapter(listAdapter);

            handler.sendEmptyMessage(0);
        }
    };
    checkUpdate.start();

please figure out this one..
thanks..

A: you haven't written dialog.show()..
refer to this code
ProgressDialog UpdateDialog = new ProgressDialog(ClassContext);

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub

            UpdateDialog.setTitle("MyApp");
            UpdateDialog.setMessage("Processing data...");
            UpdateDialog.show();
            super.onPreExecute();
        }
        @Override
        protected Object doInBackground(Object... params) {
        //your code
            }
        @Override
        protected void onPostExecute(Object result) {
            // TODO Auto-generated method stub
                //your code
                UpdateDialog.dismiss();
            }

A:  ProgressDialog mPrograss=new ProgressDialog(location.this);
            mPrograss.setTitle("loading....");
            mPrograss.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mPrograss.setMax(1);
            mPrograss.setProgress(2000);
            mPrograss.setButton("save", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            mPrograss.setButton2("cancel", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            mPrograss.show();

A: i think u can use the code below.
private ProgressDialog pd;
pd = ProgressDialog.show(context, "Please wait...", "Saving to database...", true,false);
.
pd.dismiss();


text:
Q: PHP output tag is not working I installed a new WAMP on my computer (before I used XAMPP - everything was good as I remember). My problem is the php output tag (<?= ?>) which is not working (in the browser when I click on show sourcecode it is appears exactly in the file - so it is not processed...)
Am I wrong something? Is there an option in php.ini to turn on this tag? I need this tag.
Code how I tried:
<?php
 $examples = "Some text...";
?>
<!DOCTYPE html>

        <title>Examples</title>

Examples

            <?= $examples ?>

A: You can turn it on updating the php.ini to allow short tags. Mouseover the PHP menu option in WAMP and look for settings. Set short_open_tag to on.

A: You can update your php.ini. But i think it's better to use the classic tags to avoid problem with xml tag