text:
Q: add AsyncTask onPreExecute to fragment I want to add a onPreExecute AsyncTask to a SherlockFragment but it cause error. My code is below. What is my problem on this code to add a dialog on preExecute AsyncTask?
public class customlist extends SherlockFragment  {
static final String URL = "esample";
static final String KEY_SONG = "song"; // parent node
private static final String KEY_TAB_NUM = "key.tab.num";
 private ProgressDialog pDialog;

ListView list;
LazyAdapterbeth adapter;
XMLParser parser = new XMLParser();
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

}

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    new getFeed().execute();

}

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState)

{
    View thisfragment = inflater.inflate(R.layout.dovomi, container, false);

    return thisfragment;
}

private class getFeed extends AsyncTask<Void, Void, Document> {
  @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(customlist.this);
        pDialog.setTitle("Connect to Server");
        pDialog.setMessage("This process can take a few seconds to a few minutes, depending on your Internet Connection Speed.");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    protected Document doInBackground(Void... params) {

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // getting XML from URL
        Document doc = parser.getDomElement(xml); // getting DOM element

        return doc;
    }

It causes an error in the line
pDialog = new ProgressDialog(customlist.this);

How  can I add a dialoge or progressbar in this fragment?

A: ProgressDialog takes a Context as a parameter. Since you are using it in a Fragment you can use getActivity() instead.


text:
Q: User added text to annotation [XCode] I am a beginner with XCode and I am trying to find a way for the User to input information inside a callbox of a pin they had placed on the map.
So if the User drops a pin and they tap on the pin, I want them to be able to type in a title and a subtitle of that location.
So far, I have created a map using MKMapView and I have implemented UILongPressGestureRecognizer and a void method that fires the moment a pin is created.
I am not sure what to do next? Thank you for your help.
Edit1: I don't have the required reputation to post an image, so here is a link of what I am trying to accomplish: http://imgur.com/gixFxpI
If it is possible to type in the title and subtitle without the use of a disclosure button, that would be swell. Later on I will develop the disclosure button.
Edit2: I have three new questions: 1. Why isn't my disclosure button appearing in my callout? 2. What is reuseidentifier for? Here is what I have so far.
I have embedded a navigation controller to my initial view controller that has the MKMapView in it. I created a second View Controller and I connected the MKMapView to the second View Controller and made my identifier for the second View Controller as 'heylisten' (good old Zelda).
My third question is in the prepareForSegue method, what information needs to go after the dot? destinationViewController.???? = sender.annotation;
// This is your callout box
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    MKAnnotationView *annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"overhere"];
    annotationView.canShowCallout = YES;

    UIButton *rightDisclosureButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

    annotationView.rightCalloutAccessoryView = rightDisclosureButton;

    return annotationView;
}

// This is a segue when you tap the right disclosure button
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    [self performSegueWithIdentifier:@"heylisten" sender:view];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(MKAnnotationView *)sender
{
    if ([segue.identifier isEqualToString:@"heylisten"])
    {
        ViewController *destinationViewController = segue.destinationViewController;

        // grab the annotation from the sender

        destinationViewController = sender.annotation;
    }
}

A: If you're targeting iOS 8, use a UIAlertController:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIAlertController_class/
If you're targeting iOS 7 or earlier, use a UIAlertView:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIAlertView_Class/index.html#//apple_ref/occ/cl/UIAlertView
Both of these types have mechanisms to add an input text field and specify a callback to be executed with the text the user typed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find the corresponding subtriangle of a position inside a rectangle I have a dynamic rectangle in which 4 subtriangles (t0-t3) are created (by adding the diagonals from the vertices). When given a certain x|y coordinate what is the fastest way to find the corresponding triangle?. The rectangle has a specific position and dimension. I only need the right "id" so not the vertices of the triangle, so for example in the graphic when p1 is given as position 0 should be returned, 3 at p2 and 2 at p3, ...
One possible solution of course would be to create the triangles and query if the point is contained in one of them, but it feels like a very complicated solution for something that simple.
I also thought about creating a vector from the center and measuring the angle but it also seems complicated in a rectangle with varying dimensions.
Example Rectangle

A: Consider the following:
Let the bottom left corner of the rectangle be (0,0) and the top right corner be (1,1).  Now, the two lines that form the triangles are defined as:
y = x and y = 1-x

For every point except (.5,.5) we have a ternary conditional for a given x or y.  For example, given that x = .2, we know that:
if y < .2, we're in the bottom triangle (t2),
elif  .2 < y < .8, we're in the left triangle (t3),
else, we're in the top triangle (t0).
Hopefully this helps without explicitly giving you the code.


text:
Q: Custom progressive sequence (per year) with a column as prefix I need to create a custom sequence based on a specific column, added as a prefix. I know it is possible to customize the sequence as well as the nextval, but I'm not sure if it is possible to use the column of a specific table.
This is the structure of the table with the essential information:
create table tab
(
    id serial not null
        constraint tab_pkey primary key,
    year varchar(4) not null,
    seq  varchar(20) not null
);

create sequence tab_id_seq as integer;

I would like to automatically populate the "seq" column, as happens for normal sequences, according to this format:
{year}_{sequence}

where {year}_ is the prefix, while {sequence} is a progressive that starts again from 1 every year.
DESIRED RESULT
|--------|----------|---------|
|   id   |   year   |   seq   |
|--------|----------|---------|
|   10   |   2019   | 2019_1  |
|--------|----------|---------|
|   11   |   2019   | 2019_2  |
|--------|----------|---------|
|   12   |   2019   | 2019_3  |
|--------|----------|---------|
|   13   |   2019   | 2019_4  |
|--------|----------|---------|
|   14   |   2020   | 2020_1  | <--- sequence restarting
|--------|----------|---------|
|   15   |   2020   | 2020_2  |
|--------|----------|---------|
|   16   |   2020   | 2020_3  |
|--------|----------|---------|

N.B. there is no direct relationship between the id column and {sequence} element

A: For the following test structure :
create table test
(
    id serial primary key
    , year_val int
    , seq varchar (10)
);

create or replace function fn_test () returns trigger language plpgsql as $$
declare
    res_name varchar;
begin
    drop table if exists tmp_test;
    create temporary table tmp_test as select * from test;
    insert into tmp_test values (new.id, new.year_val);

    with cte as
    (
        select *
            , year_val::varchar||'_'||(count(*) over (partition by year_val order by id))::varchar as built_res_name
        from tmp_test
    )
    select built_res_name into res_name
    from cte
    where id = new.id;

    new.seq := res_name;
    return new;
end;
$$;

CREATE TRIGGER tg_test BEFORE INSERT ON test
    FOR EACH ROW EXECUTE FUNCTION fn_test();

insert into test (year_val)
values (2019),(2019),(2019),(2019),(2020),(2020),(2020);

A: In the end I found a solution by using multiple sequences (one per year), created dynamically when entering the record.
A trigger, before the insertion invoke a procedure that creates the sequence (if it does not exist) and assigns the value to the seq column (if not assigned).
WORKFLOW

*

*record insertion

*sequence creation 'tab_ {year} _seq_id' if it does not exist

*if the column seq is empty the value nextval is assigned (tab_ {year} _seq_id)

*test insertions and deletions to verify that the column is populated in the correct way

TABLE STRUCTURE
CREATE TABLE tab (
    id serial not null constraint tab_pkey primary key,
    year varchar(4) not null,
    seq  varchar(20)
);

FUNCTION
CREATE FUNCTION tab_sequence_trigger_function() RETURNS trigger AS $$
  BEGIN
    IF NEW.seq IS NULL OR NEW.seq = '''' THEN
      EXECUTE ('CREATE SEQUENCE IF NOT EXISTS tab_' || NEW.year || '_id_seq AS INTEGER');
      NEW.seq = NEW.year || '_' || nextval('tab_' || NEW.year || '_id_seq');
    END IF;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

TRIGGER
CREATE TRIGGER tab_sequence_trigger
  BEFORE INSERT ON tab
  FOR EACH ROW
EXECUTE PROCEDURE tab_sequence_trigger_function();

TEST
INSERT INTO tab (year) VALUES (2019);
INSERT INTO tab (year) VALUES (2019);
INSERT INTO tab (year) VALUES (2019);
INSERT INTO tab (year) VALUES (2019);
INSERT INTO tab (year) VALUES (2019);
DELETE FROM tab WHERE id=5;
INSERT INTO tab (year) VALUES (2019);
INSERT INTO tab (year) VALUES (2019);
INSERT INTO tab (year) VALUES (2020);
INSERT INTO tab (year) VALUES (2020);
INSERT INTO tab (year) VALUES (2021);
DELETE FROM tab WHERE id=8;
DELETE FROM tab WHERE id=9;
INSERT INTO tab (year) VALUES (2021);
INSERT INTO tab (year) VALUES (2020);

RESULT
SELECT * FROM tab;

----------------------
| id | year |  seq   |
----------------------
|  1 | 2019 | 2019_1 |
----------------------
|  2 | 2019 | 2019_2 |
----------------------
|  3 | 2019 | 2019_3 |
----------------------
|  4 | 2019 | 2019_4 |
----------------------
|  6 | 2019 | 2019_6 |
----------------------
|  7 | 2019 | 2019_7 |
----------------------
| 10 | 2021 | 2021_3 |
----------------------
| 11 | 2021 | 2021_4 |
----------------------
| 12 | 2020 | 2020_3 |
----------------------


text:
Q: Laravel 5 Undefined variable Controller 2 View Im Going crazy with the undefined variable error in laravel , Hope someone could point out what im doing wrong, already tried several ways to pass variable from my controller to my view but nothings seems to work.
Thanks in advance
Controller:
   public function busquedaGet()
{
   return view('frontend.user.busquedaBoxeadores',compact('posts'));

}

public function busquedaPost(Request $request, BusquedaRepository $userRepo)

{
     $validator = Validator::make($request->all(), [
        'gender' => 'required|not_in:null',
        'weight' => 'required|not_in:null',
        'country' => 'required|not_in:null'
    ]);

    if ($validator->fails()) {
        return redirect(route('busquedaPostA'))->withErrors($validator);
    }

     $posts=$userRepo->busquedaBoxers($request->all());
      //dd($posts);
    return view('frontend.user.busquedaBoxeadores',compact('posts'));

}

view:
@extends('frontend.layouts.app')

@section('title')
    {{{ trans('app.contrataBoxeadores') }}}
@endsection

{{{ trans('app.red') }}}

                     {!! Form::open(['url' => route('busquedaPostA')]) !!}

has('gender') ? ' has-error' : '' }}">
                                    {!! Form::label('gender', trans('app.gender')); !!}
                                    {!! Form::select('gender', ['null' => trans(''),'F' => trans('app.female'), 'M' => trans('app.male')], null, ['class' => 'form-control']) !!}
                                    @if ($errors->has('gender'))

                                            {{ $errors->first('gender') }}

                                    @endif

has('weight') ? ' has-error' : '' }}">
                                   {!! Form::label('weight', trans('app.weight')); !!}
                                   {!! Form::select('weight', ['null' => trans(''),
                                   ' 1' => trans('Mini flyweight'),
                                   ' 2' => trans('Fyweight'),
                                   ' 3' => trans('Super flyweight'),
                                   ' 4' => trans('Bantamweight'),
                                   ' 5' => trans('Super bantamweight'),
                                   ' 6' => trans('Featherweight'),
                                   ' 7' => trans('Super featherweight'),
                                   ' 8' => trans('Lightweight'),
                                   ' 9' => trans('Super lightweight'),
                                   '10' => trans('Welterweight'),
                                   '11' => trans('Super welterweight'),
                                   '12' => trans('Middleweight'),
                                   '13' => trans('Super middleweight'),
                                   '14' => trans('Light heavyweight'),
                                   '15' => trans('Cruiserweight'),
                                   '16' => trans('Heavyweight')],
                                    null, ['class' => 'form-control']) !!}
                                    @if ($errors->has('country'))

                                            {{ $errors->first('weight') }}

                                    @endif

has('country') ? ' has-error' : '' }}">
                                    {!! Form::label('country', trans('country.countries')); !!}
                                    {!! Form::select('country', ['null' => trans(''),
                                    'us' => trans('country.united'), 'bz' => trans('country.brazil'), 'mx' => trans('country.mexico'), 'cl' => trans('country.colombia'),'ar' => trans('country.argentina'), 'ca' => trans('country.canada'), 'pu' => trans('country.peru'), 'vz' => trans('country.venezuela'), 'cl' => trans('country.chile'), 'ec' => trans('country.ecuador'), 'gt' => trans('country.guatemala'), 'cb' => trans('country.cuba'), 'hi' => trans('country.haiti'),  'bl' => trans('country.bolivia'), 'dr' => trans('country.dominican'), 'hnd' => trans('country.honduras'), 'pa' => trans('country.paraguay'), 'nic' => trans('country.nicaragua'),'slv' => trans('country.salvador'), 'cr' => trans('country.costa'), 'pnm' => trans('country.panama'), 'pr' => trans('country.puerto'), 'urg' => trans('country.uruguay'),'jam' => trans('country.jamaica'), 'tt' => trans('country.trinidad'), 'blz' => trans('country.belize'), 'brb' => trans('country.barbados'), 'ot' => trans('country.other')],
                                    null, ['class' => 'form-control']) !!}
                                    @if ($errors->has('country'))

                                            {{ $errors->first('country') }}

                                    @endif

                                 {!! Form::submit(trans('app.buscar'), ['class' => 'btn btn-lg btn-primary btn-block signup-btn']); !!}

            {!! Form::close() !!}

 Hello, {{ $posts }}

routes
    Route::post('/profile/busquedaBoxeadores',['as' => 'busquedaPostA', 'uses' => 'UserController@busquedaPost']);
    Route::get('/profile/busquedaBoxeadores', ['as' => 'busquedaGetA', 'uses' => 'UserController@busquedaGet']);

repository
    public function busquedaBoxers(array $data, $source = 'site')
{
 $query = DB::table('users')
        ->join('user_profiles', 'users.id', '=', 'user_profiles.user_id')
        ->join('boxings', 'users.id', '=', 'boxings.user_id')
        ->join('countries', 'users.id', '=', 'countries.user_id')
        ->select('users.name', 'users.username', 'users.id')
        ->where('boxings.weight_id', '=', $data['weight'])
        ->where('user_profiles.gender', '=', $data['gender'])
        ->where('countries.country', '=', $data['country'])
        ->get();

        return $query;
}

A: You are using same view for both methods: busquedaGet and busquedaPost but in busquedaGet you're compact-ing variable posts that is not defined. So you can add empty string if you're not using them in get-method:
public function busquedaGet()
{
    $posts = [];
    return view('frontend.user.busquedaBoxeadores',compact('posts'));
}

And modify view. Replace:

 Hello, {{ $posts }}

With:

 Hello,
@foreach($posts as $post)
    {{ $post->username }}
@endforeach

A: You're trying to display the posts as string in the blade, but it's not defined in busquedaGet and in busquedaPost it's a collection.
 Hello, {{ $posts }}
First you need to define a default value for it in busquedaGet and then try to loop through the collection to display it's content.


text:
Q: componentsSeparatedByString:@"\r\n" does not work on NSString - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
NSString *URLString = [[url absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSArray *temp = [URLString componentsSeparatedByString:@"\r\n"];
return YES;}

that does not split the string, though preview shows \r\n are still in the string.
Any suggestions?
input URL sample- myapp://bla\r\nbla
here is string after replacing % esc and splitting by '\r\n':

here is url before replacing % esc:

I suspect replacing percent escapes has got to do something with it.

A: As per Eduardo but closer to your code, the following:
NSString *URLString = @"myapp://bla\r\nbla";
NSArray *temp = [URLString componentsSeparatedByString:@"\r\n"];
NSLog(@"%@", temp);

Outputs:
2014-03-20 12:05:17.247 Untitled 3[437:507] (
    "myapp://bla",
    bla
)

Is it possible your incoming string contains the literal four-character sequence \r\n, which would be written as @"\\r\\n" rather than the sequence of two control codes, \r\n?

A: Try the following
NSArray *temp = [URLString componentsSeparatedByString:@"\\r\\n"];

Your initial URLString can't contain CR LF. It simply contain two-symbol literals '\r' and '\n'

A: Does it shows "\r\n" in preview? This works:
NSLog(@"%@", [@"abc\r\ndef" componentsSeparatedByString:@"\r\n"]);

If your code does not work, are you sure your string doesn't contains "\\r\\n" instead of "\r\n"?
EDIT: SO "unescaped" my double-slashes


text:
Q: Pin Python minor version in Ubuntu 18.04.4 LTS I am running software which depends on the installed minor Python version.
I was surprised to see that something changed my Python3 version from Python3.6.8 to Python3.6.9, which has caused some software to break.
What is the recommended way of pinning a minor Python version in Ubuntu? Can I install Python from source and have 3.6.8 live alongside 3.6.9?
All guides and questions that I see talk about either going from Python2 to Python3 or from Python3.X to Python3.Y.

A: Instead of pinning the version, I'd strongly suggest to fix your program.
Python uses semantic versioning, that means an updated number in the 3rd position as in 3.6.8 to 3.6.9 is only a minor update or in other words a bug fix.
Fixing your problem should not be a big problem. I am happy to offer my help.
If you really need 3.6.8, you should probably download the source and compile it.


text:
Q: Swift viewWillTransitionToSize Not Called With Split Screen I am implementing the split screen feature for the iPad Air 2 and iPad Mini 4. I'm trying to detect when the size of the split screen changes. When running as the primary app, either the viewWillTransitionToSize or willTransitionToTraitCollection will be executed. If my app is running as the secondary app, the viewWillTransitionToSize function is called when opening the secondary app or while in landscape mode, changing from 1/4 to 1/2 of the screen. When I change the secondary app from using 1/2 to 1/4 of the screen, no functions are called to help indicate that change. Is there supposed to be a function called?

A: UPDATE
If you're using UICollectionView you need to draw attention to UICollectionViewLayout method which is called shouldInvalidateLayoutForBoundsChange: Basically this method is called every-time bounds (not size) of your collection view is changed and if you answer YES your collection view relayouts.
To experiment you may (e.g. by subclassing UICollectionViewFlowLayout) override this method like this:
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
}

If it works for you may try some more efficient way to return YES only when actual size is changed. Something like this
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    BOOL should = !CGSizeEqualToSize(self.collectionView.frame.size, newBounds.size);
    return should;
}

that would be more natural than using viewWillTransitionToSize


text:
Q: Line Numbers, Code Highlighting in TextView I'm working on an 'IDE' for Android - it could be useful for editing short scripts / making quick adjustments to files. At the moment I'm just using a simple EditText, but I am wanting to add several features, for example Line Numbering down the left hand side of the EditText and Code Highlighting.
Does anyone have any suggestions about how to approach this? For the code highlighting, I'm guessing I'll need to write my own subclass of EditText. For the line numbering, could I have a thin vertical TextView that has the same text size as the EditText??
Yes, I'm aware editing code on a mobile sized screen is painful.
Thanks!

A: The stock Email application uses an html view (android.webkit.WebView) to wrap even text emails in html.  Perhaps rendering the code into html and displaying in a WebView would be a good way to get syntax highlighting.
For line numbering, the thin TextView beside the EditText seems reasonable.  You might want to encapsulate it into your own View class that handles both subviews - and allows line numbers to be turned on and off (and perhaps does other good things like keep text size of both equal)
I think an ide for Android is a good idea. Would be nice to be able to code on an airplane without having to get the tray table involved =)


text:
Q: AngularJS Binding and &pound symbol I'm able to display pound successfully in the following example if I use the pound symbol directly in the JSON data. How can I tell angular that I want to display Misko got £?

(function(angular) {
  'use strict';
angular.module('oneTimeBidingExampleApp', []).
  controller('EventController', ['$scope', function($scope) {
    var counter = 0;
    var names = ['Igor got �', 'Misko got £', 'Chirayu got £'];
    /*
     * expose the event object to the scope
     */
    $scope.clickMe = function(clickEvent) {
      $scope.name = names[counter % names.length];
      counter++;
    };
  }]);
})(window.angular);
<!doctype html>

  <meta charset="UTF-8">
  <title>Example - example-example28-production</title>

  <button ng-click="clickMe($event)">Click Me</button>

One time binding: {{::name}}

Normal binding: {{name}}

A: Angular is escaping / sanitizing by default but you can use the ng-bind-html directive with sth like this to display html:

or

more info: https://docs.angularjs.org/api/ngSanitize/service/$sanitize

A: Add ngSanitize as a dependency to your module. Also include the below script in your HTML.

angular.module('oneTimeBidingExampleApp', ['ngSanitize'])
In your html use the ng-bind-html so that angular will display it as HTML instead of plain text

Normal binding:


text:
Q: UITableViewHeaderFooterView in iOS 8 I have a UITableViewHeaderFooterView in which I change the textLabel font and the background color
UITableViewHeaderFooterView* header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
if(!header)
{
    header = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"header"];
    [header.textLabel setFont:[UIFont boldSystemFontOfSize:15]];
    [header.contentView setBackgroundColor:[UIColor colorWithRed:213/255.0 green:213/255.0 blue:213/255.0 alpha:1]];
}

Here is how iOS 7 shows it:

Here is how iOS 8 shows it:

The setFont: doesn't seems to take effect here, or the 15pt font is bigger on iOS 8 that on iOS 7
Here is how iOS 8 shows it when I remove the setFont: call

As you can see, setFont has no effect on the font, but it has on the textColor.
Am I missing something or those are "beta bugs" (I'm using simulators from XCode6 GM seed, and I have the same issue on a iPhone 5 with iOS 8 beta 5) ?
Edit: iOS 8 release and XCode 6.0.1 doesn't seems to fix the problem

A: [SWIFT version] Just had the same problem in UITableView UITableViewStylePlain , i.e. Header font setting in
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) {...}

has no effect. Here is code from my subclass of UITableViewController what worked for me [tested with XCode 6.4, iOS 8.4], see http://www.elicere.com/mobile/swift-blog-2-uitableview-section-header-color/
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    let header = view as? UITableViewHeaderFooterView //recast your view as a UITableViewHeaderFooterView
    if (header == nil) {
      return;
    }
    if (myHeaderFont != nil) {
      header!.textLabel.font = myHeaderFont;
    }
  }

The header height needs to be "manually" adjusted:
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if (myHeaderFont == nil) {
  return  20; //DEFAULT_HEADER_HEIGHT_IN_POINTS;
}
return myHeaderFont.pointSize * 2; //HEIGHT_REL_TO_FONT;

}
The rest was standard, but showing here for completeness:
override func viewDidLoad() {
//...
//https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewHeaderFooterView_class/index.html#//apple_ref/doc/uid/TP40012241
    self.tableView.registerClass(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "HEADER_REUSE_ID")
 //...
}
      override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        var header = tableView.dequeueReusableHeaderFooterViewWithIdentifier("HEADER_REUSE_ID") as? UITableViewHeaderFooterView;
        if (header == nil) {
          header = UITableViewHeaderFooterView(reuseIdentifier: "HEADER_REUSE_ID");
        }
        header!.textLabel.text = myTitle;
        return header!;
      }

A: I was having the same problem and ended up with subclassing UITableViewHeaderFooterView.
Here's a small reference implementation: Just set header.headerLabel.text = @"myString";.
@interface BHRSectionHeaderView : UITableViewHeaderFooterView

@property (nonatomic, strong) UILabel *headerLabel;

@end

@implementation BHRSectionHeaderView

- (UILabel *)headerLabel
{
    if (!_headerLabel)
    {
        _headerLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _headerLabel.font = [UIFont boldSystemFontOfSize:13.f];
        _headerLabel.textColor = [UIColor redColor];

        _headerLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview:_headerLabel];

        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(16)-[header]-(>=0)-|"
                                                                 options:0
                                                                 metrics:nil
                                                                   views:@{ @"header": _headerLabel }]];

        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(>=0)-[header]-(>=0)-|"
                                                                 options:0
                                                                 metrics:nil
                                                                   views:@{ @"header": _headerLabel }]];

        [self addConstraint:[NSLayoutConstraint constraintWithItem:_headerLabel
                                                     attribute:NSLayoutAttributeCenterY
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self
                                                     attribute:NSLayoutAttributeCenterY
                                                    multiplier:1.0f
                                                      constant:0.0f]];
    }

    return _headerLabel;
}

@end

A: You can modify the textLabel font by overriding the  -layoutSubviews method:
- (void)layoutSubviews
{
    self.textLabel.font = [UIFont boldSystemFontOfSize:15.0f];
    self.textLabel.textAlignment = NSTextAlignmentCenter;
    self.textLabel.textColor = [UIColor grayColor];

    [super layoutSubviews];
}

A: Based on tubtub's answer, I made a UITableViewHeaderFooterView subclass:
@interface CompatibilityTableViewHeaderFooterView : UITableViewHeaderFooterView
@property (nonatomic,readonly) UILabel* compabilityTextLabel;
@end

@implementation CompatibilityTableViewHeaderFooterView
{
    UILabel* iOS8TextLabel;
    NSLayoutConstraint* iOS8TextLabelLeftMarginConstraint;
}

-(instancetype) initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithReuseIdentifier:reuseIdentifier])
    {
        self.contentView.backgroundColor = GRIS_213;
        self.compabilityTextLabel.font = [UIFont boldSystemFontOfSize:15];
    }
    return self;
}

-(UILabel*) compabilityTextLabel
{
    if ([UIDevice currentDevice].systemVersion.floatValue < 8.0)
    {
        return self.textLabel;
    }
    else
    {
        if (!iOS8TextLabel)
        {
            iOS8TextLabel = [[UILabel alloc] init];
            iOS8TextLabel.translatesAutoresizingMaskIntoConstraints = NO;

            [self addSubview:iOS8TextLabel];

            iOS8TextLabelLeftMarginConstraint = [NSLayoutConstraint constraintWithItem:iOS8TextLabel attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1 constant:0];

            [self addConstraint:iOS8TextLabelLeftMarginConstraint];
            [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[iOS8TextLabel]-(>=0)-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(iOS8TextLabel)]];
            [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[iOS8TextLabel]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(iOS8TextLabel)]];
        }
        return iOS8TextLabel;
    }
}

-(UITableView*) searchForTableView
{
    UIView* currentView = self;
    while (currentView)
    {
        currentView = currentView.superview;
        if ([currentView isKindOfClass:[UITableView class]])
        {
            return (UITableView*)currentView;
        }
    }
    return nil;
}

-(void) layoutSubviews
{
    [super layoutSubviews];

    UITableView* tableView = [self searchForTableView];
    if (tableView)
    {
        iOS8TextLabelLeftMarginConstraint.constant = tableView.separatorInset.left;
    }
}

So basically I now only use the compabilityTextLabelproperty instead of textLabel.
Note that the left space constraint is automatically updated to match the tableView separator inset.
Feel free to comment/improve my code ;)


text:
Q: How to link a Google Domain to a Google Cloud Wordpress site We just launch our first Google Cloud WordPress site. We have a domain through Google. How do we link our domain to our newly created site? Also, how do we add SSL to the domain?
Unable to link the site to the domain.


text:
Q: Ideal way of creating a JFace dialog considering different screen resolutions and fonts I have used grid layout in my dialog and I have several widgets wherein I'm not setting the height or width. But I'm setting the initial size of the dialog by overriding the getInitialSize() method.
@Override
protected Point getInitialSize()
{
    return new Point(400, 400);
}

Will this cause the widgets inside the dialog to appear improperly (like partially hidden) ?
If yes , Would this issue be solved by using a ScrolledComposite inside the main composite?
(so that even if the widgets are not proper, the scrolling would help viewing the complete widgets.)

A: If you are worried that not all of your content will fit on the screen on all resolutions, here are a couple of things to consider:

*

*Wrap your whole content in a ScrolledComposite (as you already mentioned).

*Try splitting your content into several parts and either use a wizard type of GUI or tabs, depending on your requirements.

*Try avoiding setting a fixed size for the window. Either let it compute its optimal size or at least set the size to a percentage of the screen.


text:
Q: Prove:$x^2+2xy+3y^2-6x-2y\ge-11\;\;\forall(x,y)\in\Bbb{R}$
Problem Statement:-
Prove that for all real values of $x$ and $y$
  $$x^2+2xy+3y^2-6x-2y\ge-11$$

I have no idea how to approach this question all I could think on seeing it was tryin to find the linear factors, turns out that the determinant
$$\begin{vmatrix}
a & h & g\\
h & b & f\\
g & f & c\\
\end{vmatrix}\neq0$$
So finding linear factor just flew out of the window, so I plotted the equation $x^2+2xy+3y^2-6x-2y=0$ turns out it is an ellipse. I could conclude no further as to how to approach this problem.

A: Consider $f(x,y) = x^2 + 2xy + 3y^2 -6x -2y + 11 = x^2 + (2y -6)x + (3y^2-2y -11)$ as quadratic polynomial on $x$ variable, then the classic discriminant is
$$ \Delta =-8y^2 -16y -8 < 0 \quad\forall y\in \mathbb{R}/\{-1\}  $$
Thus $f(x,y) > 0 $ for each $y \in \mathbb{R}/\{ -1\}$, now the only case that you should work is for $y=-1$ and this is easy.

A: Once you can use derivatives this is straightforward:
$$
f_x = 2x+2y-6=0\\
f_y = 2x+6y-2=0
$$
These give you a critical point $(x_0,y_0)=(4,-1)$. You can verify that $f(4,-1)=-11$. It remains to show that this is indeed the minimum (here is where the second derivatives come):
$$
f_{xx} = 2,f_{xy} = 2,f_{yy} = 6
$$
So you have
$$
f_{xx}f_{yy} -f_{xy}^2 = 12-4=8 > 0, f_{xx}>0
$$
and by the Second Derivative Test it is sufficient to conclude that $f(4,-1)=-11$ is indeed the minimum.

A: Let $f(x,y)=x^2+2xy+3y^2-6x-2y$
$$\frac{\partial  f(x,y)}{\partial x}=2x+2y-6=0\\\frac{\partial  f(x,y)}{\partial y}=6y+2x-2=0$$ It is clear that $f(x,y)$ has no maximum. Then the solution of this system $(x,y)=(4,-1)$ gives a minimum. This minimum is precisely
$$f(4,-1)=-11$$

A: We have
$$\begin{align}x^2+2xy+3y^2-6x-2y+11&=x^2+(2y-6)x+3y^2-2y+11\\\\&=(x+y-3)^2-(y-3)^2+3y^2-2y+11\\\\&=(x+y-3)^2+2y^2+4y+2\\\\&=(x+y-3)^2+2(y+1)^2\end{align}$$

A: The matrix for the quadratic form is
$$
A=\begin{bmatrix}
1 & 1 & -3 \\
1 & 3 & -1 \\
-3 & -1 & 11
\end{bmatrix}
$$
A sufficient condition for the quadratic form to be positive semidefinite is that the leading principal minors but the last (that ought to be nonnegative) are positive. If also the full determinant is positive, the matrix is positive definite.
The leading principal minors are
$$
\det[1]=1,
\qquad
\det\begin{bmatrix}1 & 1 \\ 1 & 3\end{bmatrix}=2,
\qquad
\det A=0
$$
Thus $A$ is a positive semidefinite symmetric matrix and thus $v^TAv\ge0$ for all $v\in\mathbb{R}^3$, in particular for $v=[x\;y\;1]^T$, which proves the thesis.
The null space can be determined by Gaussian elimination:
\begin{align}
\begin{bmatrix}
1 & 1 & -3 \\
1 & 3 & -1 \\
-3 & -1 & 11
\end{bmatrix}
&\to
\begin{bmatrix}
1 & 1 & -3 \\
0 & 2 & 2 \\
0 & 2 & 2
\end{bmatrix}&&R_2\gets R_2-R_1, R_3\gets R_3+3R_1
\\&\to
\begin{bmatrix}
1 & 1 & -3 \\
0 & 1 & 1 \\
0 & 2 & 2
\end{bmatrix}&&R_2\gets \tfrac{1}{2}R_2
\\&\to
\begin{bmatrix}
1 & 1 & -3 \\
0 & 1 & 1 \\
0 & 0 & 0
\end{bmatrix}&&R_3\gets R_3-2R_2
\\&\to
\begin{bmatrix}
1 & 0 & -4 \\
0 & 1 & 1 \\
0 & 0 & 0
\end{bmatrix}&&R_1\gets R_1-R_2
\end{align}
So an eigenvector for the zero eigenvalue is
$$
\begin{bmatrix}4 \\ -1 \\ 1\end{bmatrix}
$$
and, indeed, the point with coordinates $(4,-1)$ is the only one where the form vanishes.


text:
Q: The least value of $f(x)$=$\sqrt{x^2-2x+2}+\sqrt{x^2-4x+29}$ If $m$ is the least value of $f(x)$=$\sqrt{x^2-2x+2}+\sqrt{x^2-4x+29}$, occur at $x = α$ , then $[m]+[α]$ is equal to (where [.] denotes greatest integer function)
(A)6
(B)7
(C)5
(D)4
My approach is as follow
$f(x)=\sqrt{(x-1)^2+1}+\sqrt{(x-2)^2+5^2}$
$\alpha$ lies between 1&2 and $m$ lies between 6 and 7 hence the answer is 7. I checked it and ur us correct. But solution is required

A:
In the figure, let $X(x,0)$ be any point on the $x$-axis.
Note that $AX=\sqrt{(x-1)^2+1}$ and $BX=\sqrt{(x-2)^2+5^2}$.
Therefore our job is to minimize $AX+BX$ where $X$ is an arbitrary point on the $x$-axis
Let $A'(1,-1)$ be the mirror image of $A(1,1)$ with respect to the $x$-axis.
From perpendicular bisector theorem,
$AX+XB=A'X+XB \ge A'B=AC+CB$
Thus the least value of $AX+XB$ is $A'B$. It is attained when $X=C$.
Since $A'B=\sqrt{(2-1)^2+(5+1)^2}=\sqrt{37}$
The least value of $f(x)$ is $\sqrt{37}$
Finally let $C=(\alpha, 0)$, then $\frac{0+1}{\alpha-1}=\frac{5+1}{2-1} \implies \alpha = \frac{7}{6}$

A: By using the Cauchy Schwarz inequality, you can easily obtain:
$$\sqrt {a^2+b^2}+\sqrt{c^2+d^2}\ge \sqrt {(a+c)^2+(b+d)^2};$$
and equality holds if $\frac{a}{b}=\frac {c}{d}$. Now, take $a=x-1$, $c=2-x$, $b=1$, $d=5$. We get:
$$\sqrt {(x-1)^2+1^2}+\sqrt{(2-x)^2+5^2}\ge \sqrt {1^2+6^2}=\sqrt {37}\implies m=\sqrt {37}.$$
And,
$$\frac {x-1}{1}=\frac {2-x}{5}\implies a=\frac {7}{6}.$$


text:
Q: Effective way to change a single value in repa array I try to use Gloss.Raster.Array to effectively plot a set of points on a screen. It uses an Array D DIM2 Color as a container of points to plot. Currently it is a 500x500 array, representing a 'bitmap'.
Suppose that each frame I generate 1 new point to display.
I didn't find another way to adjust an existing repa array to contain a single new point rather than doing repa's traverse which looks approximately like this:
{-# INLINE traverseFn #-}
traverseFn px py = (\lookupfn i@(Z :. x :. y) ->
    if x == px && y == py then red else lookupfn i)

newarr px py = R.traverse oldarr id (traverseFn px py)

I suspected this could turn to be rather inefficient: traversing whole 500x500 array for the sake of one point. But I thought maybe ghc will do some optimization magic and it won't.
Turns out it is. I tried to profile and it says that newarr takes 97.2% of time. And it works very slow too.
I'm kinda new to the whole haskell and repa ecosystem, taking my first steps, so I might not know something or do something wrong (either in my repo code or in my profiling attempts) - hence asking for help :)
Is there some performant way to change single value in repa array on each frame? Or if I want to add 500 points on each frame - what would be the answer then?


text:
Q: How to upload conDB.php to Hostinger? I really don't know how to upload conDB.php file to hostinger.
I wonder if I upload that file to File Manager 2 (that the only one I have, not File Manager and File Manager 3), will this be ok?
Could I post data what I want to send to server?
Answer me please...

A: you can upload your PHP files in filemanger2
find the below image.First click on filemanger2.then Click Public Html.as show in image.Image 1
Then upload your DBconn file in that.as show in image.
image2
thanks :)


text:
Q: Unexpected Token `}` I am using javascript and react and for some reason I am getting a strange token error.
Here is the code where the error is occurring:
renderNavBar() {
        if (!this.userHash) {
            return server_1.default.renderToString(React.createElement(navComponent.navBarNoUser, null));
        }
    }

The typescript:
renderNavBar() {
        if (!this.userHash) {
            return ReactDOMServer.renderToString(<navComponent.navBarNoUser />);
        }
    }

If I comment out the return ReactDOMServer line then there is no error. Why is this error occurring?
I also passed the function through jslint and I did not get this issue.
Thanks!

A: Because React Component's name must be in uppercase.
try
renderNavBar() {
        if (!this.userHash) {
            return ReactDOMServer.renderToString(<NavComponent.NavBarNoUser />);
        }
    }

navComponent change the name to NavComponent, navBarNoUser => NavBarNoUser

A: So I found out that my tsx markup for the element was wrong.
Essentially, I kept an empty on click handler like this onClick={}.
This is what caused my errors.
Thanks


text:
Q: Jenkins Freestyle Job : Invoke email notification from Evaluated Groovy script I am using a Groovy script to get an email on a list of offline slaves from a Jenkins freestyle job. I have the following code under Jenkins freestyle Job > Build Environment > Evaluated Groovy script :
import hudson.model.Node
import hudson.model.Slave
import jenkins.model.Jenkins

String[] slaves = []
Jenkins jenkins = Jenkins.instance

for (Node node in jenkins.nodes) {
  if (!node.toComputer().online) {
    slaves += node.name
    }
}

 println "[OFFLINE SLAVES]: "+slaves

try{
 emailext body: "${slaves}",
    subject: "test subject",
    to: "abc@xyz.com"
}
catch (Throwable t) {
  println(t)
  throw t;
}

The slave list is printing out fine but while calling emailext, the following ERROR is returned :

groovy.lang.MissingMethodException: No signature of method: Script1.emailext() is applicable for argument types: (java.util.LinkedHashMap) values: [[body:${slaves}, to:abc@xyz.com, subject:test subject]]
08:17:48 [EnvInject] - [ERROR] - Problems occurs on injecting env vars defined in the build wrapper: org.jenkinsci.lib.envinject.EnvInjectException: Failed to evaluate the script.

I am new to this and would appreciate some guidance on making this work.
Thanks in advance.

A: Try like this:
try {
    emailext (
         subject: "test subject",
         to: "abc@xyz.com",
         body: "Offline Slaves : '${slaves}'"
     )
}


text:
Q: How to execute dotnet core restore and publish commands in Gitlab-ci.yml I've got a project where we have a quickpublish.cmd file that contains the following code:
"C:\Program Files\dotnet\dotnet.exe" restore
::"C:\Program Files\dotnet\dotnet.exe" build

"C:\Program Files\dotnet\dotnet.exe" publish "./src/Web/Web.csproj" --output "../../../quickpublish/Web" --configuration release
::"C:\Program Files\dotnet\dotnet.exe" test "./tests/Tests.Web/Tests.Web.csproj"
::"D:\Apps\nodejs\node.exe" npm install

I am unfamiliar with what this language/syntax is. all the same, I am tasked with setting up Continuous Integration with Gitlab, and I'm equally uncertain what the the equivalent yaml should look like.
How can I execute dotnet restore and dotnet publish within Gitlab


text:
Q: Rails, Sidekiq and systemd are on a debian 8 ship The situation: I have a rails app, with sidekiq, working very well, under debian8.
I want an easier control of my sidekiq, so instead of daemonize it with the -d option, I want to create a sidekiq.service file in /etc/systemd/system/sidekiq.service.
( So I'll able to sudo systemctl restart sidekiq.service )
I saw how gitlab do on github, but it's not working for me, because I use rvm to install ruby.
If I do the same with /path/to/rvm/bin/bundle, It returns me an error as "Can't locate Gemfile". ( And I also have run gem install bundler, previously )
I can launch sidekiq from another directory than my rails app with :
BUNDLE_GEMFILE=/home/me/myapp/Gemfile bundle exec sidekiq --config /home/me/myapp/config/sidekiq.yml --require /home/me/myapp/config/environment.rb
But in my /etc/systemd/system/sidekiq.service at the ExecStart line, I have an error : Executable path is not absolute
Any clue on how I can do it?
Or, maybe it'll be more efficient / simpler, to run sidekiq in a docker container?

A: I just tried this with systemd on Ubuntu 15.04. (This also works for Upstart on Ubuntu 14.x.) I use RVM's alias command for an absolute path for bundle. I think that it will help to also tell it which directory to be in at the start, as well.
To make a RVM wrapper/alias. From the Rails directory:
rvm current                      # grab gemset name
rvm alias create NAME GEMSET_NAME

so if your gemset name was ruby-2.2.2@awesome_app, and you want your wrapper/alias to be called 'awesome_app', it'd be:
rvm alias create awesome_app ruby-2.2.2@awesome_app

Then in systemd, the full path is something like PATH=/usr/local/rvm/wrappers/awesome_app/ which makes the ExecStart command this:
ExecStart=/usr/local/rvm/wrappers/awesome_app/bundle exec sidekiq ...

Edit: I've confirmed that my sidekiq worker is now working properly. Here's my full sidekiq.service file.
Description=Sidekiq Background Worker

[Service]
Type=forking
User=rails
Group=rails
WorkingDirectory=/home/deployer/app
Environment=RAILS_ENV=production
GuessMainPID=true
ExecStart=/usr/local/rvm/wrappers/awesome_app/bundle exec "sidekiq -d -L log/sidekiq.log -q mailer,5 -q default -e production  >> log/sidekiq.log 2>&1"
ExecStop=/usr/local/rvm/wrappers/awesome_app/bundle exec "sidekiqctl stop /home/deployer/app/tmp/pids/sidekiq.pid >> /home/deployer/app/log/sidekiq.log 2>&1"

[Install]
WantedBy=multi-user.target

Currently I have it monitored with monit. I personally prefer Upstart, since systemd requires password every. single. time. but, like I said, can confirm that this works for me.

A: Sidekiq provides a sample systemd service file.
https://github.com/mperham/sidekiq/blob/master/examples/systemd/sidekiq.service


text:
Q: Pass JavaScript into PHP using Ajax I'm attempting to pass a JavaScript function into a php file using Ajax, as far as I can see my Ajax syntax is right but it doesn't seem to work. This is the first time I've tried to use Ajax so any help would be much appreciated.
I made some test files just to test if the Ajax code passes the variable and I'll put it below -
script.js -
var number1 = Math.round(Math.random() * 6) + 1;
var number2 = Math.round(Math.random() * 6) + 1;
var randomAnswer = number1 + number2;

$ (document).ready(function() {
return $.ajax({
    url: 'index.php',
    type: 'POST',
    data: randomAnswer,
    });
});

index.php -

<?php
$answer = $_POST ['randomAnswer'];
echo $answer;
?>

A: There is small issues i can see is - dataType is missing and wrong data formatting, see code below -
$ (document).ready(function() {
 $.ajax({
    url: 'index.php',
    type: 'POST',
    dataType:'json',
    data: ({randomAnswer: randomAnswer}),
    success: function(data) {
       console.log(data);
    }
  });
});

Hope this will help you in some way (y).

A: You should have a complete interface in order to display the returned data, or just have some debug function calls like console.log to view the returned data. Here is a sample script page based on your code that has a button to do the ajax call, and have the result displayed inside a div:
HTML

0

<button id="getOutput">Get AJAX Random Answer</button>

PHP At the beggining of the PHP file, before the <!DOCTYPE html> tag
<?php
if(isset($_POST['randomAnswer'])) {
    $answer = $_POST['randomAnswer'];
    die($answer);
}
?>

jQuery Javascript
$(document).ready(function() {
    $('#getOutput').on('click', function() {
        var number1 = Math.round(Math.random() * 6) + 1;
        var number2 = Math.round(Math.random() * 6) + 1;
        var randomAnswer = number1 + number2;

        $.ajax({
            url: 'numecho.php',
            type: 'POST',
            data: {
                randomAnswer: randomAnswer
            },
            complete: function(data) {
                $('#output').text(data.responseText);
            }
        });
    });
});

Now you have your random generated number sending to your server side PHP script and then returning the value back displaying it to an html div element.

A: There are many ways to solve this.
1.- First let's make sure we were able to post data to PHP by doing this in Ajax:
success: function (result) {
    alert("result: " + result);
}

2.- I have tested your code and made some changes to the PHP code as well.
3.- Now everything seems to be working fine :).
Just copy and paste this entire code below and you will see the results (create a file and called it index.php).
 <?php

   $data = array();
   if(isset($_POST['randomAnswer']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH'])) {
   $data = 'You number is: ' . $_POST['randomAnswer'];
   echo json_encode($data);
   die();
    }
 ?>


text:
Q: Rails superclass mismatch for class on migrations I am junior Ruby on Rails dev.
I have this problem: I've updated my rails from 5.1 to 6. If I try to run
rails db:migrate

there are errors:

TypeError: superclass mismatch for class CreateVacancyFields

Looking inside my migration file:
class CreateVacancyFields < ActiveRecord::Migration[ 5.1 ]

Ok, I've changed 5.1 to 6.0 like this:
class CreateVacancyFields < ActiveRecord::Migration[ 6.0 ]

But it doesn't help. What I do wrong?

A: Possibly you're having the same named class CreateVacancyFields twice. If so, rename it to some different name to resolve this issue.

A: If someone else is looking into this, you must probably have made a previous migration with the same name, if you haven't used it will look empty
`class NameOfModel < ActiveRecord::Migration[6.1]
end`

just delete the file from db folder, just make sure it is not active then rails db:migrate


text:
Q: Make Search Function include subdomain (blog.ourwebsite.com) Wondering if there's a way to edit our search.php or .htaccess or function.php (or anything else...) so that our search function on our main site (www.oursite.com) includes the subdomain of blog.ourwebsite.com?
Any thoughts or suggestions are appreciated it..

A: If you transform your main website's Wordpress into a multi-site environment, you can move blog.yourdomain.com to be a network site.
Once you do this, you could use the Multisite Global Search plugin to add a widget that searches all network sites.
It would be easy to move your standalone blog.yourwebsite.com to a network site:

*

*export the content from blog.yourdomain.com,

*create a subdomain Wordpress network on your main website,

*edit your blog.subdomain.com settings (Settings > General) to change the site and Wordpress URL to blog2.subdomain.com,

*rename your subdomain blog to blog2 in cPanel,

*create a network site called blog.yourdomain.com

*import the content you exported earlier.

Done.
PS - You'd need to copy any themes and plugins you have on blog2.yourdomain.com into the main Wordpress installation.


text:
Q: Convolution neural network predicts the probability of a class For this example, I tried to print out "tf.argmax(pred, 1)", and result is [1 3 4 1 2].
How to know the probability of the forecast category?
Does Tensorflow provide any API?

A: What you can do is get the argmax of the prediction, and get the prediction at this index.
This is all easier in numpy (for example, using the amax function: https://docs.scipy.org/doc/numpy/reference/generated/numpy.amax.html)
tfpredicted,loss, acc = sess.run([pred,cost, accuracy], feed_dict={x: batch_x,y: batch_y,keep_prob: 1.})
print(np.amax(tfpredicted))

I did not test the code, but hope it works. Otherwise you might have to look at the max functions numpy offers.
Good luck!


text:
Q: Django import from csv(update_or_create) my program loads data from csv (customoer, item, total), here is my data model:
from django.db import models

class Member(models.Model):
    customer = models.CharField(max_length=50)
    item = models.JSONField(max_length=50)
    total = models.IntegerField()

def __str__(self):
    return self.customer

My view:
def upload(request):
    template = 'upload.html'

    promt = {
        'member': 'Member of CSV should be customer, item, total'
    }

    if request.method == 'GET':
        return render(request, template, promt)

    csv_file = request.FILES['file']

    if not csv_file.name.endswith('.csv'):
        messages.error(request, 'This is not a csv file')

    data_set = csv_file.read().decode('UTF-8')
    io_string = io.StringIO(data_set)
    next(io_string)
    for column in csv.reader(io_string, delimiter=','):
        _, created = Member.objects.update_or_create(
            customer=column[0],
            item=column[1],
            total=column[2]
        )
    context = {}
    return render(request, template, context)

In general, the download works, but instead of updating the user data, a new object is created with the same customer, how can I make it so that a new customer is not created, but only the total and item are updated in it?
Example CSV data:
customer,item,total
bellwether,Cavorit,6126
resplendent,Saphire,8502
bellwether,Ruby,342

Instead of not creating two or more objects with the bellwether customer, there was only one object with customer bellwether an item ("Kavorit", "Ruby"), total (6468).
Thank you for your time

A: The problem here is that when you pass all 3 fields in and django looks up the database, if there is a query that matches all 3 fields at the same time, obviously if one of them is different then the existing one, it does not match and creates a new one. The documentation says docs

The update_or_create method tries to fetch an object from database
based on the given kwargs. If a match is found, it updates the fields
passed in the defaults dictionary.

So try this:
 _, created = Member.objects.update_or_create(
            customer=column[0]
            defaults={ "item":column[1], "total":column[2] }
        )


text:
Q: How to set list item class to active Navbar I have the following navbar code. I try to set a class of list item using jQuery doesn't work. What do I do wrong ? Please help! The following are my html code and jQuery code :

                 Home

                Add

                Search

                Setting

jQuery code :

A: Please find below mentioned solution.

$('.navbar-nav li a').click(function(e){
  e.preventDefault();
  $('.navbar-nav li').removeClass('active').addClass('inactive');
  $(this).parent('li').addClass('active');
})
.active {background:red;color:white;}
.active a{color:white}

                 Home

                Add

                Search

                Setting

Let me know if it not works.


text:
Q: coq What tactics should I use forall A : Prop, A -> ~~A I do not know what tactics I have to use for prove the formule.
I tried two methods but I'm stuck in the two.
Lemma Exo17 : forall A : Prop, ~~(A \/ ~A).
Proof.

Methode 1
intro.
unfold not.
intro.

Methode 2
intro.
intro.
case H.

A: The best tactic for this case is called "pen and paper". Indeed, you should try first to build the proof by hand [intuitionistic sequent calculus LJ should work fine for this purpose].
Once you have a clear picture of how the proof works, coding it in Coq will be trivial.

A: Try using intuition to solve the problem, then Print Exo17 to find out what the solution was.


text:
Q: What is the second value of quartz.net configuration job-type parameter? I'm trying to use Quartz.net in my web project. I configured my application like this:
<job>

  <name>CRMMoreThanOneJob</name>
  <group>jobGroup1</group>
  <job-type>ReportingPortalBLL.Jobs.CRMCalledMoreThanOneJob, ReportingPortalBLL.Jobs</job-type>

  <durable>true</durable>
  <recover>false</recover>
  <job-data-map>
    <entry>
      <key>MessageToLog</key>
      <value>Hello from MyJob</value>
    </entry>
  </job-data-map>
</job>

But it did not work because of the job-type statement. My Job class' is defined like below and its namespace is ReportingPortalBll.Jobs
namespace ReportingPortalBLL.Jobs
{
 public class CRMCalledMoreThanOneJob:IJob
 { .
   .
 }
}

After i changed it to ReportingPortalBLL.Jobs.CRMCalledMoreThanOneJob, ReportingPortalBLL (without .Job) it worked well.
I looked at the documentation but couldn't find what is represented at the second value of job-type parameter. What should i write on the second parameter? What is the second value on the below representation means? I will be using Quartz on my other projects so it would be nice to know how to configure it easily.
<job-type>Namespace.Job1, secondValue</job-type>

A: The secondValue corresponds to assembly name.
If you go through the source code of quartz.net you can see that the job-type is being passed to Type.GetType as parameter and Type.GetType accepts a assembly qualified name. The assembly-qualified name of a type consists of the type name, including its namespace, followed by a comma, followed by the display name of the assembly.
refer to these links for more info
http://msdn.microsoft.com/en-us/library/c5cf8k43.aspx
http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx


text:
Q: How to update users with Socket.io when a database has been updated? We are putting together a webgame where you can play rock, paper, scissors with someone else in real time. Game information (like what the player threw, their score, username, etc.) gets inserted into Sqlite3 when that player makes a move.
We need Socket.io to communicate from the server back to the users when certain conditions are met in the database. To let P1 know what P2 threw and if their hand won, for example.
Everything I've seen online so far is either a loop that periodically checks the database (like long-polling) or including socket.io on each individual function that updates the database.
I feel like I'm missing the point here and that I've overlooked something basic. Is there a better way to do this?


text:
Q: Vue Quassar Standalone example not working I am trying a simple standalone vue/quasar example by copy pasting all code from code pen into a single html file,
but its not working.

  <link href="https://cdn.jsdelivr.net/npm/quasar@1.12.13/dist/quasar.css" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons" rel="stylesheet" type="text/css">

      <q-btn style="background: #FF0080; color: white" label="Fuchsia"></q-btn>
      <q-btn flat style="color: #FF0080" label="Fuchsia Flat"></q-btn>
      <q-btn style="background: goldenrod; color: white" label="Goldenrod"></q-btn>
      <q-btn outline style="color: goldenrod;" label="Goldenrod"></q-btn>
      <q-btn color="grey-4" text-color="purple" glossy unelevated icon="camera_enhance" label="Purple text"></q-btn>

A: Here its working!
Head tag loads all style and script before Body and its HTML and QUASSAR or any other stand alone library which need to put application/plugin into a HTML element that must load after Body because.
Body and its element loads before script so script will be able to access those Html.
Here in your case the QUASSAR script needs   to boot app inside that

  <link href="https://cdn.jsdelivr.net/npm/quasar@1.12.13/dist/quasar.css" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons" rel="stylesheet" type="text/css">

      <q-btn style="background: #FF0080; color: white" label="Fuchsia"></q-btn>
      <q-btn flat style="color: #FF0080" label="Fuchsia Flat"></q-btn>
      <q-btn style="background: goldenrod; color: white" label="Goldenrod"></q-btn>
      <q-btn outline style="color: goldenrod;" label="Goldenrod"></q-btn>
      <q-btn color="grey-4" text-color="purple" glossy unelevated icon="camera_enhance" label="Purple text"></q-btn>


text:
Q: imagepng in combination with include does not work anymore Why does this script not work anymore? The script has been working with previous php versions (before 5.6) and default encoding for the database connection:
include('connect-to-database-with-utf8.php');

header('Content-Type: image/png');
$im = imagecreatetruecolor(45, 22);
$text_color = imagecolorallocate($im, 255, 0, 0);
imagestring($im, 10, 5, 3, '1234', $text_color);
imagepng($im);
imagedestroy($im);

The webbrowser says that the image cannot be displayed because it contains errors... But if I don't use any includes by copying the code into file directly, it will work. Very strange.
The include file 'connect-to-database-with-utf8.php' contains:
$mysqli = new mysqli('db_host', 'db_user', 'db_password');
$mysqli->select_db('db_name');

// set charset to utf-8 for database requests
$mysqli->set_charset('utf-8');

$stmt = $mysqli->prepare('SET NAMES \'utf8\'');
$stmt->execute();
$stmt->close();

$stmt = $mysqli->prepare('SET CHARACTER SET \'utf8\'');
$stmt->execute();
$stmt->close();


text:
Q: Binary search problem with my code....please look into my following problem? #include<iostream>
#include<string>

using namespace std;

int main()
{
int list[25],vote[25];
bool found;
int count,first,mid,last;
char condition;
double high = 0,total=0;
string searchitem,name[25],winner;
cout <<"How many names?" <<endl;
cin>>count;
cout <<" Enter the "<<count<< " candidates last name and the number of votes received " <<endl;
for (int i=0;i<count;i++)
{
    cin >>name[i];
    cin >> vote[i];
    total = total+vote[i];

}

cout <<"Candidate names ,number of votes and their percentage of votes are ..."<<endl;
for (int i=0;i<count;i++)
{
    cout << name[i]<<endl;
    cout << vote[i]<<endl;
    cout << (vote[i]*100)/total<<endl;
    if(vote[i]>high)
    {
        high = vote[i];
     winner = name[i];
    }

}
cout << " The winner of the election is " << winner << endl;

cout << "Do you have anything more to do?y/n?" << endl;
cin >> condition;
while (condition=='y' || condition=='Y')
{
found = false;
cout<<"Enter name you want to search \n";
cin>>searchitem;
first=0;
last=count-1;
while ((first<=count)&&!found)
{
    mid=(first+last)/2;
    if (name[mid]==searchitem)
    {
        found=true;
        total =  total-vote[mid];
        cout << "Enter the new number of votes for " << name[mid] << endl;
        cin >> vote[mid];
        total = total + vote[mid];
    }
    else if (name[mid]>searchitem)
    {
        last=mid-1;
    }
    else first=mid+1;
}
if (!found)
{
    cout<<" Sorry that name was not found \n";
}

cout <<"Candidate names ,number of votes and their percentage of votes are ..."<<endl;
high = 0;
for (int i=0;i<count;i++)
{
    cout << name[i]<<endl;
    cout << vote[i]<<endl;
    cout << (vote[i]*100)/total<<endl;
    if(vote[i]>high)
    {
        high = vote[i];
     winner = name[i];
    }
}
cout << " The winner is " << winner << endl;

cout << "Do you have anything more to do?y/n? "<<endl;
cin >> condition;
}
}

Alright.Now I have been trying to experiment with this and when there are 5 names involved, Im able to alter the third and the fourth name's votes and display the results.
But when I try searching for the first,second and the last name my program just halts!
Why is this happening???And a solution can help save me time from trying to break a wall with bare hands.

A: while ((first<=count)&&!found)

should be
while ((first<=last)&&!found)


text:
Q: MVC ASP.NET Return response.GetResponseStream() as FileResultStream I am trying to write a controller that creates and makes a HttpWebRequest to a service that returns an Image. I then want to return this image as a FileResult. How do I go about doing that.  I have tried the code below but it returns a corrupted image instead of the full image:
public FileResult SomeAction()
{
    var request = Make some request here

    using (var response = (HttpWebResponse)request.GetResponse())
    {
        string contentType = response.ContentType;
        return File(response.GetResponseStream(),contentType);
    }
}

Thanks

A: Since you fail to mention how "it doesn't work", all I can tell you is that in general what you're doing should work.  However, i'm unsure of where the response stream is actually read.  Since you're placing a return inside a using, it may be that the stream is being disposed of before the stream is actually read.  Try removing the using statement, and just doing something like this:
var response = request.GetResponse();
File(response.GetResponseStream(), response.ContentType);

if that doesn't work, then verify that response is actually returning a content type, and a valid stream.
EDIT:
It would seem that I was correct, the filestream gets closed before it's read if you wrap it in a using.  You don't have to worry about disposing of the stream as File will dispose of it when it's done with it.
See this other question:
How do I dispose my filestream when implementing a file download in ASP.NET?


text:
Q: FluorineFx solution to read response Here is class to read response from netConnection.Call:
    public class getCompleteParkOfUser : IPendingServiceCallback
    {
        public void ResultReceived(IPendingServiceCall call)
        {
            object result = call.Result;
            MessageBox.Show("Server response: " + result);
            ArrayCollection items = result as ArrayCollection;
            foreach (object item in items)
            {
                MessageBox.Show("");
            }

        }
    }

result is good: http://scr.hu/0tgp/6yxdi
but result won't be saved as ArrayCollection:
http://scr.hu/0tgp/ovghm
In effect i can't read response.
Response/Request is AMF

A: Try this..
object item = call.Result;
IEnumerable enumerable = (IEnumerable)item;
foreach (object element in enumerable)
{
    // do something with element
}


text:
Q: Returning Undefined const https = require('https');
const request = require('request');
process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

function readLine() {
    return inputString[currentLine++];
}

async function getCountryName(code) {
    for (var i = 1; i<26; i++)
    {
    const url= 'https://jsonmock.hackerrank.com/api/countries?page='+i
     await request({url,json:true}, (error,{body})=>{
         for(var i=0; i<10 ; i++)
         {
             if (body.data[i].alpha2Code == code)
             {
                console.log(body.data[i].name)
                return body.data[i].name
                break
             }
         }
     })}
    //  return name
}

async function main() {
  const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

  const code = readLine().trim();

  const name = await getCountryName(code);

  ws.write(`${name}\n`);

}

when i run this program,  it showing undefined as a result instead of  place name. But when I log it  showing correct value.
Below is the intelligence when I keep my cursor on getCounrtyName function.
function getCountryName(code: any): Promise<void>
I think it should be sent as a response to the promise and I don't know that.


text:
Q: Codeigniter Session - Access Userdata value for all users from DB I am using Codeigniter's Session class to store session values in the database. Contained within the userdata field is the user's username and other values.
I want to get the username from each userdata field where the lastactivity is >= let's say 5 minutes.
The only way I can think to accomplish this is:

*

*search for users active in last 5 minutes

*get the userdata for each row returned

*unserialise userdata

*extract username

However this seems like the long way. Is there a cleaner/better way to do this?

A: Try this code.
$query = $this->db->select('user_data')->get('ci_sessions');

$user = array(); /* array to store the user data we fetch */

foreach ($query->result() as $row)
{
    $udata = unserialize($row->user_data);

    /* put data in array using username as key */
    $user[$udata['user_name']] = $udata['user_role'];
}

from the result array, u can fetch needed information.


text:
Q: Terminology: Compact subset of a subset Example: $P$ is tight, that is, $\exists K, P(K)>1-\epsilon, \forall \epsilon>0$ where $K$ is compact subset of $X$, if and only if for every subset $A$, $P(A)=\sup_K P(K)$ where sup is over all compact subset $K$ of $A$.
Is "compact subset $K$ of $A$" here (i) a compact subset of $X$ that is contained in subset $A$ or (ii) intersection of a compact subset of $X$ with $A$?

A: compactness is absolute. There is no compact "in $X$", but just compact (always considered as a space in its own right, so in the subspace topology).
So a compact subset of $A$ is just a set $K \subseteq A$ that is compact (as a space on its own).


text:
Q: how to set the form-data for http request in Android This is the REST Api for uploading a document
Request URL

http:upload_url/{userid}/file

Method Type

POST

Header

Content-Type:application/json

Url Variables

1.{userid} - Unique id of the logged in user (e.g. VB000V)

form-data

{
                   key: "file",value: ,type: "file"
                   key: "filepath",value: "",type: "text"}

Code:
public class HttpUploadDoc extends AsyncTask<File, Void, String>{
    private HttpClient client;
    private HttpPost post;
    private HttpResponse response;
    private HttpEntity entity;
    private ProgressDialog mProgressDialog;
    private SharedPreferences sharedPreferences;

    int serverResponseCode=0;
    //for uploading..//
    String end = "\r\n";
    String twoHyphens = "--";
    String boundary = "******";

    private Context con;
    StringBuffer buffer=new StringBuffer();

    public HttpUploadDoc(Context con){
        this.con=con;
    }
    @Override
    protected void onPreExecute() {
        mProgressDialog=new ProgressDialog(con);
        mProgressDialog.setMessage("Loading");
        mProgressDialog.show();
        super.onPreExecute();
    }

    protected String doInBackground(File... params) {

        File file=params[0];

        String path=file.getAbsolutePath();

        FileBody fileBody=new FileBody(file);
        sharedPreferences=con.getSharedPreferences("LoginPref",Context.MODE_PRIVATE);
        String userId=sharedPreferences.getString("userid", "");

        client=new DefaultHttpClient();

        try {
            String filename=path.substring(path.lastIndexOf("/")+1);
            URL url = new URL(AllRestApiUrls.UploadDocument+userId+"/file");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setChunkedStreamingMode(128 * 1024);

            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/pdf");
            httpURLConnection.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            httpURLConnection.setRequestProperty("file",filename);
            httpURLConnection.setRequestProperty("filepath", path);

            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());

            String formdata="key=\"file\", value=\""
                    + filen+"\""+end
                +"key=\"filepath\",value=\""+path+"\"";
            dos.writeBytes(twoHyphens + boundary + end);
            dos.writeBytes("Content-Disposition: form-data; "+formdata);
            dos.writeBytes(end);

           FileInputStream fis = new FileInputStream(path);

            int bufferSize = 8 * 1024; // The size of the buffer, 8KB.
            byte[] buffer = new byte[bufferSize];
            int length = 0;

            while ((length = fis.read(buffer)) != -1) {

                // Write data to DataOutputStream
                dos.write(buffer, 0, length);
            }

            dos.writeBytes(end);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + end);

            fis.close(); // Close the FileInputStream.
            dos.flush(); // Flush the data to DataOutputStream.

            serverResponseCode = httpURLConnection.getResponseCode();
            String serverResponseMessage = httpURLConnection.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

            entity.addPart("file", fileBody);
            FileInputStream input=new FileInputStream(f.getPath());
            entity.addPart("filepath", new StringBody(f.getAbsolutePath()));

            post.setEntity(entity);

             Intent intent = new Intent();
             intent.setAction(Intent.ACTION_VIEW);
             Uri uri = Uri.fromFile(f);
             intent.setDataAndType(uri, "application/pdf");
             con.startActivity(intent);

        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        }
        catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mProgressDialog.dismiss();

        return null;
    }

}


text:
Q: how to use gif_lib encode RGB to gif If I run RGB2GIF like:
RGB2GIF(true, 1, "../tests/porsche.rgb", ExpNumOfColors, 320, 200);

the output is like original image

but when I use another rgb file:
RGB2GIF(true, 1, "D:\\rgb.yuv", ExpNumOfColors, 1280, 720);`

the out gif file missing colors.

Is it relative to global color map? local color map?
static void SaveGif(GifByteType *OutputBuffer, int Width, int Height, int ExpColorMapSize, ColorMapObject *OutputColorMap){int i, Error;
GifFileType *GifFile;
GifByteType *Ptr = OutputBuffer;

/* Open stdout for the output file: */
gfile = fopen("D:\\out_my.gif", "wb+");
if ((GifFile = EGifOpen(gfile, writeGifData, &Error)) == NULL) {
    PrintGifError(Error);
    exit(EXIT_FAILURE);
}

if (EGifPutScreenDesc(GifFile,
    Width, Height, ExpColorMapSize, 0,
    OutputColorMap) == GIF_ERROR ||
    EGifPutImageDesc(GifFile,
    0, 0, Width, Height, false, OutputColorMap) ==
    GIF_ERROR){
    PrintGifError(Error);
    printf("error\n");
    exit(EXIT_FAILURE);
}

GifQprintf("\n%s: Image 1 at (%d, %d) [%dx%d]:     ",
    PROGRAM_NAME, GifFile->Image.Left, GifFile->Image.Top,
    GifFile->Image.Width, GifFile->Image.Height);

for (i = 0; i < Height; i++) {
    if (EGifPutLine(GifFile, Ptr, Width) == GIF_ERROR)
        exit(EXIT_FAILURE);
    GifQprintf("\b\b\b\b%-4d", Height - i - 1);

    Ptr += Width;
}
printf("\n");
printf("close file\n");
if (EGifCloseFile(GifFile, &Error) == GIF_ERROR)
    PrintGifError(Error);
fclose(gfile);
exit(EXIT_FAILURE);
}

static void RGB2GIF(bool OneFileFlag, int NumFiles, char *FileName, int
ExpNumOfColors, int Width, int Height)
{
    int ColorMapSize;
    GifByteType *RedBuffer = NULL, *GreenBuffer = NULL, *BlueBuffer = NULL,
    *OutputBuffer = NULL;
    ColorMapObject *OutputColorMap = NULL;
    ColorMapSize = 1 << ExpNumOfColors;

if (NumFiles == 1) {
    LoadRGB(FileName, OneFileFlag,
        &RedBuffer, &GreenBuffer, &BlueBuffer, Width, Height);
}
else {
    LoadRGB(NULL, OneFileFlag,
        &RedBuffer, &GreenBuffer, &BlueBuffer, Width, Height);
}

if ((OutputColorMap = GifMakeMapObject(ColorMapSize, NULL)) == NULL ||
    (OutputBuffer = (GifByteType *)malloc(Width * Height *
    sizeof(GifByteType))) == NULL)
    GIF_EXIT("Failed to allocate memory required, aborted.");
printf("GifQuantizeBuffer\n");
if (GifQuantizeBuffer(Width, Height, &ColorMapSize,
    RedBuffer, GreenBuffer, BlueBuffer,
    OutputBuffer, OutputColorMap->Colors) == GIF_ERROR)
    exit(EXIT_FAILURE);
free((char *)RedBuffer);
free((char *)GreenBuffer);
free((char *)BlueBuffer);

SaveGif(OutputBuffer, Width, Height, ExpNumOfColors, OutputColorMap);
}

A: nobody use this lib encode gif? is there some other libs to encode gif, except gif.h.


text:
Q: CSS line-spacing: Not Applied in  Element I have an intractable, at least for me, HTML/CSS problem.  Here is a bit of a web page I'm currently developing:

(The whole page is here: http://www.professorbrown.net/ but has now been changed as suggested in the accepted answer.)
Note that the "fine print" at the bottom has the same line spacing as the body copy, and I can't fix it.  It looks the same in Chrome, Firefox, and Edge, so it has to be an error in my work.
The CSS is: .fine {font-size: 1rem; line-height: 1.1;}  The markup is <span class="fine">.
Using the inspector function of both Chrome and Firefox shows the computed CSS for font-size as 10px, which is correct, and the line-height as 11px, which is what I intended, but clearly not what's displayed.  Measurement says the displayed line height is about 32px, which is the same as the body copy above the fine print.  Margin, border, and padding for the fine print are all zero. HTML and CSS validate using validator.nu and Jigsaw.  There are style sheets from Skeleton, Superfish, and Slick linked in.  I've commented them out one by one with no change in the error.
Please tell me what I've done wrong or give me some help with further debugging.
(Note: This is still a development project, so TLS is not enabled and the images have watermarks because I haven't licensed them yet.  I know both things must be done before "production.")

A: A span won't take on line-height correctly due to how its display property works if it is inside a div with defined font-size or line-height css. You can either change your span to a div or, you can add display:block to your .line's css class to change the display behavior.
e.g.
.fine {font-size: 1rem; line-height: 1.1; display:block;}


text:
Q: ASPX Bootstrap tab class accessing problem I'm using bootstrap nav-tabs and I have a problem: From code-behind, I cannot get the value of attribute 'class' of the [li] tag when it's selected. It's always returned null.
Here's my aspx:

            Personal

            Employment

            This is Personal Information Tab

            This is Employment Information Tab

<asp:Button ID="Button1" Text="Submit" runat="server" CssClass="btn btn-primary" OnClick="Button1_Click" />
<asp:HiddenField ID="TabName" runat="server" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

*

*Code-behind:

protected void Button1_Click(object sender, EventArgs e)
{
    string cl1 = Tab1.Attributes["class"];
    string ro1 = Tab1.Attributes["role"];
    Label1.Text = "class of tab1: " + cl1 + "
role: " + ro1;
}

- When I click button1 while Tab1 is selected --> My result displays on Label1:

class of tab1: {nothing}
role: tab

From the same tag [li], attribute 'role' can be retrieved, but 'class' is null.
I have no idea about this indeed, because when I inspect the element, the class of that [li] is 'active'
I tried googling around but unable to find similar questions.
Please help me with this, thanks!!!

A:

Add the  runat="server" attribute to your li element, then call the id of the li from your code behind like e.g yourid.Attributes and you can add or remove classes for the element


text:
Q: How can I split a string and take only one from the separated string in Python? I have a string which includes ":", it shows like this:
: SHOES

and I want to split the colon and SHOES, then make a variable that contains only "SHOES"
I have split them used df.split(':') but then how should I create a variable with "SHOES" only?

A: You can use the list slicing function. and then use lstrip and rstrip to remove excess spaces before and after the word.
df=": shoes"
d=df.split(":")[-1].lstrip().rstrip()
print(d)

A: You can use 'apply' method to execute a loop over all dataset and split the column with 'split()'.
This is an example:
import pandas as pd

df=pd.DataFrame({'A':[':abd', ':cda', ':vfe', ':brg']})

    # First we create a new column just named a new column -> df['new_column']
    # Second, we loop dataset with apply
    # Third, we execute a lambda with split function, getting only text after ':'
df['new_column']=df['A'].apply(lambda x: x.split(':')[1] )

df
        A   new_column
0   :abd    abd
1   :cda    cda
2   :vfe    vfe
3   :brg    brg

A: Here is a small working sample. Both stripValue and newString return the same value. It is matter cleaner code vs verbose code:
    # set initial string
    myString = "string : value"

    # split it which will return an array [0,1,2,3...]
    stripValue = myString.split(":")

    # you can create a new var with the value you want/need from the array
    newString = (stripValue[1])

    # or you can short hand it
    print(stripValue[1])

    # calling the new var
    print(newString)

A: If your original strings always start with ": " then you could just remove the first two characters using:
myString[2:]


text:
Q: I use a method from a superclass, fragmentActivity, but eclipse says the method can't be found Before, when I hovered over the FragmentActivity, I would get "Note: This element neither has attached source nor attached Javadoc and hence no Javadoc could be found." I went to the location of the android-support-v4.jar in my package and imported the source and javadoc and got rid of that, but eclipse still cannot find the method in the superclass when I try to use it or override it.
 @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
        Session session = Session.getActiveSession();

        if (session != null && session.isOpened()) {
            // if the session is already open,
            // try to show the selection fragment
            showFragment(SELECTION, false);
        } else {
            // otherwise present the splash screen
            // and ask the person to login.
            showFragment(SPLASH, false);
        }
    }


text:
Q: how to cache response of a POST request using workbox is it possible to cache the response of POST request using workbox? my application uses POST request instead of GET to fetch list data , since user credentials are sent along with the request.

A: Let me clarify S. Esteves' answer.
Browser cache storage doesn't has an ability to persist POST requests as a keys (see spec here).

If innerRequest's url's scheme is not one of "http" and "https", or
  innerRequest's method is not GET, return a promise rejected with a
  TypeError.

Workbox lets you intercept POST requests (as service worker does on fetch event with GET requests) by passing 'POST' as third parameter to registerRoute function, then you can put some custom logic into handler (but even manually you still unable to save response into cache storage, as it is not supported).
So direct use of Workbox strategies which do cache responses will end up with error (see example here).
So options here are:

*

*(preferable) If you are in touch with backend maintainers ask them to change desired endpoint from POST to GET if it is possible and if POST request is effectively idempotent (so it makes sense to cache it). Modern browsers support get size from 100Kb to 200Kb, so in many cases this option is possible. If POST is not idempotent option is not to cache it.

Quote from here:

HTTP caching is applicable only to idempotent requests, which makes a
  lot of sense; only idempotent and nullipotent requests yield the same
  result when run multiple times. In the HTTP world, this fact means
  that GET requests can be cached but POST requests cannot
However, there can be cases where an idempotent request cannot be sent
  using GET simply because that request exceeds the limits imposed by
  popular Internet software.

*Alternatively you can try this (credits to jeffposnick) using Workbox:

*

*Get POST request in workbox route handler

*Convert it manually to GET request (which is allowed as cache storage keys)

*Use this GET request as a key to save cached response in cache storage

*Check in the same handler if a request is already saved and respond with cached response

*Also I think it is possible to save responses in IndexedDB using requests digests as keys.

workbox.routing.registerRoute(
  /api/, // Change to match your endpoint URL.
  async ({event, url}) => {
    // See https://developers.google.com/web/tools/workbox/guides/route-requests#handling_a_route_with_a_custom_callback
    // Do something here. What it is up to you.
    // Eventually, return a Response object, or else your request will fail.
    return response;
  },
  'POST' // Opt-in to matching POST requests. Only GET is matched by default.
);

A: You can cache POST request with the following syntax:
workbox.routing.registerRoute(
    <url>,
    <workbox strategy>,
   'POST'
);

Official Documentation: https://developer.chrome.com/docs/workbox/modules/workbox-routing/#defining-a-route-for-non-get-requests


text:
Q: Java, "a[1] *= a[1] = b[n + 1]" not working as expected? So as the title shows, I've got a function that uses a temporary array, and I want to write a value into it from another array, and then multiply the two value with itself.
Example:
float[] a = {0, 0}

a[0] *= a[0] = b[n    ];
a[1] *= a[1] = b[n + 1];

I would expect the above would do the following:
a[0] = b[n    ];
a[0] *= a[0]; //(aka: a[0] = a[0] * a[0])

a[1] = b[n + 1];
a[1] *= a[1];

Though that behavior doesn't seem to be whats happening. Instead it seems just multiply whatever the original value held in "a" was with whatever value was held in "b" like so:
a[0] = a[0] * b[n    ];
a[1] = a[1] * b[n + 1];

It was always my understanding that whatever comes after the "=" is evaluated first, as seen when you do:
float a, b;
a = b = 5;
//"a" and "b" both equal "5" now.

Being that that is the case, would it not show that my original example should work?
Can anyone explain whats going on and why this code doesn't work as intended?

A: I think the answers so far are not correct. What comes into play is the evaluation of compound expressions like a *= b. In short, the value of the left hand side is computed before the right hand side. From the JLS (emphasis mine):

At run time, the expression is evaluated in one of two ways.
If the left-hand operand expression is not an array access expression,
  then:
First, the left-hand operand is evaluated to produce a variable. If
  this evaluation completes abruptly, then the assignment expression
  completes abruptly for the same reason; the right-hand operand is not
  evaluated and no assignment occurs.
Otherwise, the value of the left-hand operand is saved and then the
  right-hand operand is evaluated. If this evaluation completes
  abruptly, then the assignment expression completes abruptly for the
  same reason and no assignment occurs.
Otherwise, the saved value of the left-hand variable and the value of
  the right-hand operand are used to perform the binary operation
  indicated by the compound assignment operator. If this operation
  completes abruptly, then the assignment expression completes abruptly
  for the same reason and no assignment occurs.
Otherwise, the result of the binary operation is converted to the type
  of the left-hand variable, subjected to value set conversion (§5.1.13)
  to the appropriate standard value set (not an extended-exponent value
  set), and the result of the conversion is stored into the variable.

In your example:
a[0] *= a[0] = b[n    ];

*

*value of a[0] is computed and stored in say tmp

*a[0] = b[n] is evaluated, giving the value of b[n] (and changing the value of a[0] to b[n])

*tmp * a[0] is computed

*the result of the last step is assigned to a[0]
So, what you get is effectively a[0] *= b[n].
EDIT: About the confusion about right-to-left-evaluation of assignments: I did not find that terminology used in the JLS, and IMHO it is not correct (although it is used in the Java tutorials). It is called right-**associative* assThe JLS says this about assignments:

There are 12 assignment operators; all are syntactically
  right-associative (they group right-to-left). Thus, a=b=c means
  a=(b=c), which assigns the value of c to b and then assigns the value
  of b to a.

A: Referring to the Java documentation:

All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

So what is happening in your case of a[0] *= a[0] = b[n    ]; is that you assign a[0] the value of b[n] and then you multiply the original a[0] by that new value. So your expression is effectively a[0] *= b[n].
Personally, I don't use an assignment operator twice on a single line, it can be confusing to read.

A: Assignment operators (unlike most other operators) are evaluated from right to left in Java (documentation).  This means that the following:
a[0] *= a[0] = b[n];

is actually evaluated as:
a[0] *= (a[0] = b[n]);

The quantity in parentheses is an assignment, and returns the value b[n], but does not change the value of a[0].  Then, the following final assignment is made:
a[0] = a[0] * b[n]

Both *= and = are assignment operators, and have the same level of precedence.  So in this case, the right to left rule applies.

A: A key point that doesn't seem to have been pointed out in the answers yet is that *= isn't merely an assignment operator, but rather a compound assignment operator.
The language spec says that the following are equivalent:
E1 op= E2
    <=>
E1 = (T) ((E1) op (E2))

where op= is something like *=, += etc.
As such:
a[0] *= a[0] = b[n    ];

is equivalent to:
a[0] = a[0] * (a[0] = b[n]);

and the a[0] is evaluated before the (a[0] = b[n]), because of the left-to-right evaluation order.
So:

*

*This reads the value from a[0] (call this "A")

*It reads the value from b[n] (call this "B")

*It assigns B to a[0]  (*)

*And then multiplies A * B (call this "C")

*And then stores C back in a[0].

So yes, this is equivalent to multiplying whatever is in a[0] by b[n], because the step marked (*) above is redundant: the value assigned there is never read before it is reassigned.


text:
Q: Telerik RadEditor's ImageManager broken, even no css applied I'm using Tererik:RadEditor in asp.net. When I click ImageManger it is shown totally broken. I have not applied any CSS to the page or any control.

How to resolve this issue?

A: Hi this issue comes because of some missing handlers. Please add the following to your handlers in Web.config file to fix the above issue.
<httpHandlers>
  <add verb="*" path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource, Telerik.Web.UI" validate="false" />
  <add verb="*" path="Telerik.Web.UI.DialogHandler.aspx" type="Telerik.Web.UI.DialogHandler, Telerik.Web.UI" validate="false" />
</httpHandlers>

<system.webServer>
    <handlers>
     <add name="Telerik_Web_UI_DialogHandler_aspx" path="Telerik.Web.UI.DialogHandler.aspx" type="Telerik.Web.UI.DialogHandler" verb="*" preCondition="integratedMode"/>
    </handlers>
</system.webServer>

This should fix the issue.

A: This happens exactly because you didn't apply Telerik Css file to your control.
To fix this, you need to add css file for editor control to your page. you can do it in markup or design mode by selecting skin.
If you're going to inspect your code, you should see 404 errors. Do you see them?


text:
Q: Проблема с проверкой наличия текста элемента в Selenium Как получить текст элемента на старнице?
Я попробовал несколько способов, но первые 2 передают недостоверную информацию о содержании, а третий выглядит, как костыль.
Цель: Выйти из браузера как только элемент перестанет быть пустым
Код:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from bs4 import BeautifulSoup
from time import sleep

def document_initialised(driver):
    return driver.execute_script("return 'initialised'")

options = webdriver.ChromeOptions()
options.add_argument('--headless')
browser = webdriver.Chrome(chrome_options=options)

browser.get('https://www.deepl.com/translator#en/ru/Text')
WebDriverWait(browser, 10).until(document_initialised)

for i in range(10):
    print('fnd:', browser.find_element(value='target-dummydiv').text)
    print('src:', browser.execute_script("return document.getElementById('target-dummydiv');").text)

    soup = BeautifulSoup(browser.page_source, 'lxml')
    el = soup.find('div', id='target-dummydiv')
    translation = str(el.text).strip()

    print('bs4:', translation)

    if translation != '':
        break
    sleep(0.5)

generated_html = browser.page_source
browser.quit()

Вывод:
fnd:
src:
bs4:

fnd:
src:
bs4:

fnd:
src:
bs4:

fnd:
src:
bs4: Текст


text:
Q: part after '_' in data returned is PascalCase even though I set camelCase as the default naming convention I have this line of code before I create my entity manager:
breeze.NamingConvention.camelCase.setAsDefault();
and this query:
var query = entityQuery.from('vehicle')
                .expand("engine, driveType")
                .select("engine.friendlyEngineName, driveType.friendlyDrivetrain")

The data comes back like so:
driveType_FriendlyDriveTrain = "Rear Wheel"
engine_FriendlyEngineName = "6.2L V8"

Why are "FriendlyDriveTrain" and "FriendlyEngineName" PascalCase? This seems clearly wrong since I set camelCase before I created the EntityManager and the query. How do I make it so that the parts after the '_' are camelCase as well?
note: I made sure to remove any web api json formatting configurations so that breeze is the only one managing the translation.
edit: The weird thing is that this same query returns properties that are camelCase after the '_' when it hits the cache. So same query, two different results.

A: Please review the documentation on NamingConvention. If that doesn't clear it up, you can come back and ask a more specific question. Thanks.
Edit 2 Sept 2014 (morning)
Please also explain what you think Breeze should be doing with the "_" character. The Breeze convention treats it like any other identifier character (e.g., a-z,A-Z,0-9) and does nothing with it. It seems you want your convention to skip over leading underscores and lower the case of the first char thereafter if it is alpha. I think you also want to drop the underscores ... but I'm not sure.
That's cool. You can write your own NamingConvention that does what you want. And you can make it the default too. In fact, the noUnderscoreConvention shown on the NamingConvention documentation page is more than half way home for you.
I will say you threw me for a loop with your mix of periods and underscores in the select statement and returned data. I have no idea how you got the select to work or got that kind of result.
Edit 2 Sept 2014 (afternoon)
Ok ... I overlooked the fact that you are doing a projection!
The projection flattens dotted property path values (whether ComplexType or EntityType navigations). It creates projected property names for these "flattened properties" by using "_" as the separator character. Yes, it applies the applicable MetadataStore's naming convention to those "_" separated names and, yes, the Breeze camelCase convention doesn't do anything special with the underscore. So you get back flattened projection property names such as "engine_FriendlyEngineName".
You can call this a bug if you like. I don't. I don't because (a) it seems to me a matter of opinion as to what a camelCase convention should do in this situation; (b) it's been this way forever; and (c) I don't think it is important enough to risk breaking existing applications that might rely on the current behavior ... not when your remedy is so simple.
And that remedy is to write your own camelCase convention that handles these projected property names differently.

Please include it here when you write it so that others who share your perspective may benefit from it.

I'm not sure what you mean when you write: "this same query returns properties that are camelCase after the '_' when it hits the cache". What query is that? Not the one you wrote here.
Projection results don't "hit the cache" ... unless the projected property value is itself an entity ... and that is NOT the case here. What do you mean by "this same query". I await your response.


text:
Q: Date Time difference between hour of the day and time now Time = datetime.datetime.now().time()

I wanted to find the difference in seconds between the Time above^ and the hour of the day:
for example if the Time = 15:07:25.097519, so the hour of the day is 15:00:00, i want to store 445.097519 seconds to a variable.
How can I do that?
I am an amateur at this please help!!

A: import datetime

now = datetime.datetime.now()
hour = now.replace(minute=0, second=0, microsecond=0)
seconds = (now - hour).seconds + (now - hour).microseconds / 1000000

A: Here is one way to do it. Extract the hour from current time, and initialize a new datetime.time object with hour as input. Then you convert both of the timestamps to datetime and then do the subtraction. Code below does that
Time = datetime.datetime.now().time()
hour = str(Time).split(":")[0]
currentHourTime = datetime.datetime(2019,10,31,int(hour),0,0,0).time()

dateTimeCurr = datetime.datetime.combine(datetime.date.today(), Time)
dateTimeCurrHour = datetime.datetime.combine(datetime.date.today(), currentHourTime)

dateTimeDifference = dateTimeCurr - dateTimeCurrHour

dateTimeDifferenceInSeconds = dateTimeDifference.total_seconds()

print(dateTimeDifferenceInSeconds)


text:
Q: dblink from remote server into a Google Cloud SQL instance using .pgpass I'm trying to connect to a Google Cloud SQL instance using dblink, which works well when setting up my username and password in the connection string, but I would like to save my Client credentials in the SQL instance not to have the need to explicitly put my password in the connection.

A: The .pgpass file which will used is the one that belongs to the OS user which is running the local database ('~/postgres/.pgpass', in most cases).  And then for security reasons, it works only if you are locally a superuser.  Can you meet those criteria?

but I would like to save my Client credentials in the SQL instance

What does "SQL instance" mean?  I would not think that .pgpass would count as being inside the SQL instance.
An alternative solution is create a foreign server with "postgres_fdw".  This doesn't seem to be documented (edit: it is documented here, but uses dblink_fdw not postgresql_fdw), but you can pass the name of a "postgres_fdw" foreign server (in single quotes) to dblink functions as the connection string.  It will then pull the password to be used from the USER MAPPING for that server and user.  I would think the USER MAPPING counts as inside the "SQL instance".