text:
Q: Loading events in ionic2-calendar from firestore async issue? I'm building an app with ionic6 and just starting with it.
I want to display in a calendar events that I stored in firestore.
I'm using angular and ionic2-calendar.
I'm really starting with Angular and js so be kind :)
With the following code, the items are loaded after the page to be initialized :
resa-calend-view.page.ts:29 constructor
resa-calend-view.page.ts:33 Begin ngonInit
resa-calend-view.page.ts:42 onInit 0 items

I tried a lot of configurations with async/await (you can see some traces of them :( but without any success.
My events are not loaded when the page loads.
Do you have any clue or something that I have done wrong ?
Perhaps I'm mistaken from the beginning.
Here are my files:
resa-calend-view.page.ts
import { Component, OnInit, Inject, LOCALE_ID, ViewChild } from '@angular/core';
import { CrudService } from '../../services/crud.service';
import { AlertController, IonDatetime, ModalController } from '@ionic/angular';
import { CalendarComponent } from "ionic2-calendar";
import { start } from 'repl';
import { map, Observable } from 'rxjs';

@Component({
  selector: 'app-resa-calend-view',
  templateUrl: './resa-calend-view.page.html',
  styleUrls: ['./resa-calend-view.page.scss'],
})
export class ResaCalendViewPage implements OnInit {
  @ViewChild(CalendarComponent) myCal: CalendarComponent | undefined;
  eventSource: any[] = [];
  viewTitle: string = "";

  calendar = {
    mode: 'month',
    currentDate: new Date(),
  };

  selectedDate: Date = new Date();
  items: any[] = [];
  //@ViewChild(CalendarComponent) myCal: CalendarComponent;
  constructor(public db: CrudService, private alertCtrl: AlertController,
    @Inject(LOCALE_ID) private locale: string,
    private modalCtrl: ModalController) { console.log("constructor");
     }

  ngOnInit() {
    console.log("Begin ngonInit");
    this.db.ResaRef.snapshotChanges()
        .subscribe(resas => {
          resas.forEach(resa => {
            console.log('Item: ' + resa.payload.doc.data());
            this.items.push(resa.payload.doc.data())
          });
    });
    this.initResas();
    console.log("onInit " + this.items.length + " items")
  }
initResas(){
  var startTime;
  var endTime;
  for (var i = 0; i < this.items.length; i += 1) {
    console.log("init " + this.items[i].nom);
    //start date
    startTime = new Date(
      Date.UTC(
        this.items[i].date_arrivee.substring(0, 4),
        this.items[i].date_arrivee.substring(5, 7),
        this.items[i].date_arrivee.substring(8, 10)
      ));
    endTime = new Date(
      Date.UTC(
        this.items[i].date_depart.substring(0, 4),
        this.items[i].date_depart.substring(5, 7),
        this.items[i].date_depart.substring(8, 10)
      ));
      this.eventSource.push({
        title: this.items[i].nom,
        startTime: startTime,
        endTime: endTime,
        allDay: true,
      });
  }
  this.myCal?.loadEvents();
}
// Change current month/week/day
next() {
  this.myCal?.slideNext();
}

back() {
  this.myCal?.slidePrev();
}

}

resa-calend-view.page.html
<ion-header>
  <ion-toolbar color="primary">
    <ion-title>
      Ionic Calendar
    </ion-title>
    <ion-buttons slot="end">
      <ion-button>
        <ion-icon name="add" slot="icon-only"></ion-icon>
      </ion-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-segment [(ngModel)]="calendar.mode">
    <ion-segment-button value="month">
      <ion-label>Month</ion-label>
    </ion-segment-button>
    <ion-segment-button value="week">
      <ion-label>Week</ion-label>
    </ion-segment-button>
  </ion-segment>

  <ion-row>
    <ion-col size="6">
      <ion-button (click)="createRandomEvents()" expand="block" fill="outline">
        Add random events
      </ion-button>
    </ion-col>
    <ion-col size="6">
      <ion-button (click)="removeEvents()" expand="block" fill="outline">
        Remove all events
      </ion-button>
    </ion-col>
  </ion-row>

  <ion-row>
    <!-- Move back one screen of the slides -->
    <ion-col size="2">
      <ion-button (click)=back() fill="clear">
        <ion-icon name="arrow-back" slot="icon-only"></ion-icon>
      </ion-button>
    </ion-col>

    <ion-col size="8" class="ion-text-center">
      <h2>{{ viewTitle }}</h2>
    </ion-col>

    <!-- Move forward one screen of the slides -->
    <ion-col size="2">
      <ion-button (click)=next() fill="clear">
        <ion-icon name="arrow-forward" slot="icon-only"></ion-icon>
      </ion-button>
    </ion-col>
  </ion-row>

  <calendar
    [eventSource]="eventSource"
    [calendarMode]="calendar.mode"
    [currentDate]="calendar.currentDate"
    startHour="6"
    endHour="20"
    step="30"
    startingDayWeek="1"
  >
  </calendar>

</ion-content>

crud.service.ts
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/compat/firestore';
import { Router } from "@angular/router";

export class Resa {
  nom: string ="";
  prenom: string = "";
  date_arrivee: string=""
  date_depart: string=""
  mail: string=""
  prix: string=""
  source: string=""
  telephone: string=""
  funpass: string=""
}

@Injectable({
  providedIn: 'root'
})

export class CrudService {
  items:any[] = []
  ResaRef!: AngularFirestoreCollection<Resa>;
  myResa:Resa = new Resa();
  resas!: Promise<any[]>;
  constructor(
    private db: AngularFirestore,
    private router: Router
  ) {
    console.log("Constructor service")
    this.ResaRef = db.collection("reservations");
  }

  getAll(): AngularFirestoreCollection<Resa> {
    return this.ResaRef;
  }
  getItems(){
    console.log("Getting Items")
    this.items = []
    let test = this.db.collection('reservations').get().subscribe((ss) => {
      ss.docs.forEach((doc) => {
                        this.items.push(doc.data());
                        console.log("browsing results" + doc.id)
                      });
    });

    return this.items
  }
  async getResas(){
    console.log("Getting Items async")
    this.items = []
    let test = this.db.collection('reservations').get().subscribe((ss) => {
      ss.docs.forEach((doc) => {
        this.items.push(doc.data());
        console.log("browsing results" + doc.id);
      });
    });

    return this.items
  }

  async saveResa(resa:any){
    let date_a = new Date(resa.date_a_str)
    let date_a_str = date_a.getDate() +"-"+date_a.getMonth() + "-" + date_a.getFullYear()
    const idResa= resa.nom +"-" + resa.date_arrivee
    console.log("Saving Resa" + idResa)
    const res = await this.db.collection('reservations').doc(idResa).set(resa);

    return this.items
  }

  getTasks() {
    return this.db.collection('tasks').snapshotChanges();
  }

  delete(id: string) {
    this.db.doc('tasks/' + id).delete();
  }

}

Thanks for your help !


text:
Q: How to prevent to write , and ' in form textbox VB.Net? I want to prevent users to write/put ' (single quote) or , (comma) in my form textbox?
I already tried:
If Asc(e.KeyChar) = 188 Or Asc(e.KeyChar) = 222 Then
    e.Handled = True
End If

but in vain it did not work.

A: The reason why it didn't work for you, are the wrong character codes.
The ASCII codes are like following:

*

*single quote ' = 39

*comma , = 44
If you change your code to this it will work:
If Asc(e.KeyChar) = 39 Or Asc(e.KeyChar) = 44 Then
    e.Handled = True
End If

Note: copy & paste of , and ' will still work.
If you want to disable copy & paste for the Textbox completely, you can set the ShortcutsEnabled-property to False.
If you don't want to disable copy & paste, you can additionally check the Textbox-content in the Validating-Event and replace the comma and singe qoute with an empty string:
Private Sub TextBox1_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
    TextBox1.Text = TextBox1.Text.Replace(",", "").Replace("'", "")
End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: Delegate passing data no response i've been advised to pass data using delegation, but it does not seem to show any log message of the string. i'm passing data from the frontViewController to the backViewController.
frontViewController.h
@protocol passIdDelegate <NSObject>

-(void)idPassed:(NSString*)idString;

@end

@interface FrontViewController : UIViewController {

    id<passIdDelegate> delegate;
}

@property(nonatomic,assign)id delegate;

@end

frontViewController.m passing data in didSelectRow
[delegate idPassed:[[homesDic objectAtIndex:indexPath.row] objectForKey:@"idString"]];

[self performSegueWithIdentifier:@"showHome" sender:self];

backViewController.h
@interface HomeProfileViewController : UIViewController <passIdDelegate>{

}

@end

backViewControlller.m
-(void)idPassed:(NSString*)idString{
    NSLog(@"%@", idString);
}

A: In this case, where you are trying to pass data to a new view controller that is being presented, delegation isn't the correct pattern.  All you need is a property on your destination view controller to receive the data.
BackViewController.h
@interface HomeProfileViewController : UIViewController{

@property (strong,nonatomic) NSString *idString;

}

@end

frontViewController.m passing data in didSelectRow
NSString *idString =  [[homesDic objectAtIndex:indexPath.row] objectForKey:@"idString"]];

[self performSegueWithIdentifier:@"showHome" sender:idString];

In frontViewController.m prepareForSegue
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"showHome"]) {
        HomeProfileViewController *hpvc = (HomeProfileViewController *)segue.destinationViewController;
        hpvc.idString=(NSString *)sender;
    }
}

A: In your backviewController.m you need something like frontViewController.delegate = self;

A: To pass data back from ViewControllerB to ViewControllerA you need to use Protocols and Delegates or Blocks, the latter can be used as a loosely coupled mechanism for callbacks.
To do this we will make ViewControllerA a delegate of ViewControllerB. This allows ViewControllerB to send a message back to ViewControllerA enabling us to send data back.
For ViewControllerA to be delegate of ViewControllerB it must conform to ViewControllerB's protocol which we have to specify. This tells ViewControllerA which methods it must implement.
In ViewControllerB.h, below the #import, but above @interface you specify the protocol.
@class ViewControllerB;

@protocol ViewControllerBDelegate <NSObject>
- (void)addItemViewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)item;
@end

next still in the ViewControllerB.h you need to setup a delegate property and synthesize in ViewControllerB.m
@property (nonatomic, weak) id <ViewControllerBDelegate> delegate;

In ViewControllerB we call a message on the delegate when we pop the view controller.
NSString *itemToPassBack = @"Pass this value back to ViewControllerA";
[self.delegate addItemViewController:self didFinishEnteringItem:itemToPassBack];

That's it for ViewControllerB. Now in ViewControllerA.h, tell ViewControllerA to import ViewControllerB and conform to its protocol.
#import "ViewControllerB.h"

@interface ViewControllerA : UIViewController <ViewControllerBDelegate>

In ViewControllerA.m implement the following method from our protocol
- (void)addItemViewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)item
{
    NSLog(@"This was returned from ViewControllerB %@",item);
}

The last thing we need to do is tell ViewControllerB that ViewControllerA is its delegate before we push ViewControllerB on to nav stack.
ViewControllerB *viewControllerB = [[ViewControllerB alloc] initWithNib:@"ViewControllerB" bundle:nil];
viewControllerB.delegate = self
[[self navigationController] pushViewController:viewControllerB animated:YES];


text:
Q: Collapse Expand tableRow by clicking on the row i have found a jfiddle with collapse/expand the row by clicking on the text:
JFiddle
Html:

            Cell 1
            Cell 2
            Cell 3
            Cell 4
            Show Extra

hidden row

hidden row

hidden row

Js
$("a[id^=show_]").click(function(event) {
    $("#extra_" + $(this).attr('id').substr(5)).slideToggle("slow");
    event.preventDefault();
})

But now i want to click on the Row to expand and not on the Show Extra.
But i cant figure it out how.
Can somebody please help me?
Thanks

A: http://jsfiddle.net/kbcm5fL4/1/ see this fiddle.

  $(function(){

        $("a[id^=show_]").click(function(event) {
          $("#extra_" + $(this).attr('id').substr(5)).slideToggle("slow");
          event.preventDefault();
        })
        $('.row').click(function(){
          $("#extra_1").slideToggle("slow");
          event.preventDefault();
        });
    });

        Cell 1
        Cell 2
        Cell 3
        Cell 4
        Show Extra

hidden row

hidden row

hidden row


text:
Q: RangeSelector with MultipleSeries I understand that the range selector shows the average for multiple series. Is there a way to choose a particular series as the range selector series. Is there a method i can override to modify the behaviour of the range selector drawing.

A: There isn't an option for this, but there is a feature request.
A workaround would be to have two synchronized charts, one which is all range slider and one which is all chart. http://dygraphs.com/tests/synchronize.html can point you in the right direction.


text:
Q: How to extract city and state code from an address I have a string var looks like this:
str = "1234 South St, Boston, MA"

Is there any way that I can extract only the city and state code?
So I want this result:
extractedStr = "Boston, MA"

A: You can use NSDataDetector for CheckingType.address and get city and state NSTextCheckingKeys from its addressComponents:
let str = "1234 South St, Boston, MA"
do {
    if let addressComponents = try NSDataDetector(types: NSTextCheckingResult.CheckingType.address.rawValue)
        .matches(in: str, range: NSRange(location: 0, length: str.utf16.count)).first?.addressComponents,
        let city = addressComponents[.city],
        let state = addressComponents[.state] {

        print("city:", city)
        print("state:", state)

        let result = "\(city), \(state)"
        print(result)
    }
} catch {
    print(error)
}

This will print

city: Boston
state: MA
Boston, MA

A: If you are sure about the structure of the string: (swift 4.0 +)
var str = "1234 South St, Boston, MA"
let splitted = str.components(separatedBy: ",")
splitted.map{ $0.replacingOccurrences(of: " ", with: "") }
var city = splitted[1]
var state = splitted[2]

print("City:\(city), State:\(state)")


text: Q: Idempotents in Group Algebras What is known about idempotents in Lie group algebras (such as on the classical Lie groups)? Specifically the self-adjoint ones. Is there anything interesting to say? I haven't been able to find much written about non-discrete ones.  It could be about either one of the C*-algebras or just the L^1 convolution algebra.


text:
Q: PHP preg_replace replacing line break When renumbering an array using
$arr=array_values($arr); // Renumber array

I realized that a line break is being introduced into one of the array strings, which I don't want.
My string is going from:
Property
Type
to Property
Type
In any case I am using:
$newelement = preg_replace("/[^A-Za-z0-9\s\s+]/", " ", $element);

already to remove unwanted characters prior to database insertion, so I tried to change it to:
 $newelement = preg_replace("/[^A-Za-z0-9\s\s+'
''
''/n''/cr']/", " ", $element);

But there is no change, and the ?line feed/line break/carriage return is still there.
Am I doing the preg_replace call correctly?

A: This should work too:
// char(32) is whitespace
// For CR
$element = strtr($element, chr(13), chr(32));

// For LF
$element = strtr($element, chr(10), chr(32));

A: That preg looks a bit complicated. And then you have ^ in the beginning as not A-Z... or linefeed. So you don't want to replace linefeed?
How about
$newelement = preg_replace("/[\n\r]/", "", $element);

or
$newelement = preg_replace("/[^A-Za-z ]/", "", $element);

\s also matches linefeed (\n).

A: This thing worked for me.
preg_replace("/\r\n\r\n|\r\r|\n\n/", "
", $element);

A: It's a hack, but you can do something like this:
    $email_body_string  = preg_replace("/\=\r\n$/", "", $email_body_string);

The replacement says find a line that ends with an equals sign and has the standard carriage return and line feed characters afterwards. Replace those characters with nothing ("") and the equals sign will disappear. The line below it will be pulled up to join the first line.
Now, this implies that you will never have a line that ends with an equals sign, which is a risk. If you want to do it one better, check the line length where the wrap (with the equals sign) appears. It's usually about 73 characters in from the beginning of the line. Then you could say:
    if (strlen(equals sign) == 73)
       $email_body_string  = preg_replace("/\=\r\n$/", "", $email_body_string);


text:
Q: How to easy switch db in Django 1.9.x across multiple servers I have one application in Django 1.9.x, and I want to use multidb.
Have any configuration on the settings that I can enter multiple databases, and when it is on a specific server it uses the correct database. For example:
When I'm programming localhost use default, When I put in test serve, automatically switch to testserverdb and when I put in production server use productiondb, I tried use multi-db documentation but it's not what I want 'cuze this case is to work with legacy database, not my case.
How I do it?

A: In your settings file:
try:
    from [app_name].local_settings import *
except ImportError:
    pass

Changes you make in this local_settings file will be overridden. So now you can have a different local_settings file for your localhost, development or production. You can specify a separate db in these files separately.

A: It sounds like you want to have environment specific databases, not necessarily a single app that connects to many databases.  You can easily accomplish this with a custom settings module for each of these environments.
You might have a structure like the following :
myproject/
   - settings/
       - __init__.py
       - common.py

You'll want to put all your common settings under common.py.  This will serve as the basis for all your other environment settings.  From here,there are a few setups that you can use to do what you want, but I'm going to suggest that you use common.py as a base settings module that can be overridden locall.y
To do this, you can set your DJANGO_SETTINGS_MODULE to by myproject.settings, and in your __init__.py,
from .common import *

try:
    from .local import *
except ImportError:
    pass

Then on each environment (production/development/etc), you'll want to include a file named local.py in myproject/settings.  Any settings you put in that local.py file will override your common.py when your settings module gets loaded up.


text:
Q: Get me to calculate displacement. I don't how what will be the formula according to this program class Vehicle;
class Point {
private:
    float x, y;
public:
    Point(float x = 0,float y = 0){
        this->x = x;
        this->y = y;
    }
    void move_north(float num){
        y = y + num;
    }
    void move_south(float num){
        y = y - num;
    }
    void move_west(float num){
        x = x - num;
    }
    void move_east(float num){
        x = x + num;
    }
    float getX(){
        return x;
    }
    float getY(){
        return y;
    }
    void print() const {
        cout << fixed << setprecision(2) << x << " " << y << endl;
    }

    friend class Vehicle;
};

class Vehicle {
private:
    Point starting_position;
    Point current_position;
    float distance_covered = 0;
    float calculate_displacement() const {
       ** how to calculate it I dont understand **
    }
    public:
    Vehicle(Point p) {
        starting_position.x = p.x;
        starting_position.y = p.y;
        current_position.x = p.x;
        current_position.y = p.y;
    }
    void move_north(float num){
        distance_covered = distance_covered + num;
        current_position.y = current_position.y + num;
    }
    void move_south(float num){
        distance_covered = distance_covered + num;
        current_position.y = current_position.y - num;
    }
    void move_west(float num){
        distance_covered = distance_covered + num;
        current_position.x = current_position.x - num;
    }
    void move_east(float num){
        distance_covered = distance_covered + num;
        current_position.x = current_position.x + num;
    }
    void print() const {
        cout << "Starting position: ";
        starting_position.print();
        cout << "current_position: ";
        current_position.print();
        cout << "Distance covered: " << fixed << setprecision(2) << distance_covered << endl;
        **Here calling calculate_displacement()**
        cout << "Displacement: " << fixed << setprecision(2) << calculate_displacement() << endl;
    }
};

int main() {
    float initial_x, initial_y;
    cin >> initial_x >> initial_y;
    Point starting_position(initial_x, initial_y);
    Vehicle vehicle(starting_position);
    int number_of_moves;
    char direction;
    float units;
    cin >> number_of_moves;
    for(int i = 0; i < number_of_moves; i++) {
        getchar();
        cin >> direction >> units;
        switch(direction) {
            case 'N':
                vehicle.move_north(units);
                break;
            case 'S':
                vehicle.move_south(units);
                break;
            case 'W':
                vehicle.move_west(units);
                break;
            case 'E':
                vehicle.move_east(units);
                break;
        }
    }
    vehicle.print();
}

Explaination : I want to know the displacment formula to calculate it between two points on graph
               the input is :
               1.1 3.3
               5
               N 2.1 W 2.5 S 2.1 E 3.1 N 0.6
               output expected
               Starting position: 1.10 3.30
               current_position: 1.70 3.90
               Distance covered: 10.40
               Displacement: 0.85
So i want some one to help me guide further

A: The distance between two points no matter the dimension is called Euclidean_distance

so your method is
float calculate_displacement() const
{
    return sqrt (delta_x*delta_x + delta_y*delta_y);
}

and
delta_x = starting_position.x - current_position.x
delta_y = starting_position.y - current_position.y


text:
Q: Passing complex parameters to a GET Action I need to pass parameters for filtering to ASP.NET Core REST API Server using HttpClient.
Filter contains complex data type. I used to pass data by HttpPost, but it not suitable for CRUD concept.
How can I send complex data type as json object in HttpGet request?

A: You can do it by defining your own Get method
e.g.:
static async Task<HttpResponseMessage> GetAsync(this HttpClient client, string uri, HttpContent content, CancellationToken cancelToken)
{
    var request = new HttpRequestMessage(new HttpMethod("GET"), uri)
    {
        Content = content
    };
    return await client.SendAsync(request, cancelToken);
}

However! It is not recommended to do so, read about it here: HTTP GET with request body
The better solution would be to convert your complex object into URL parameters


text:
Q: How do I authorize Tweepy to post on Twitter? I'm trying to make a Twitter post, but I keep getting tweepy.errors.Unauthorized: 401 Unauthorized. So I decided to use api.verify_credentials() to check if I'm able to connect and voila: Authentication Successful. But even so, the post is still not authorized.
How do I authorize Tweepy to post to Twitter?
import tweepy

def main():
    consumer_key = '...'
    consumer_secret = '...'
    access_token = '...'
    access_token_secret = '...'

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    api = tweepy.API(auth)

    try:
        api.verify_credentials()
        print("Authentication Successful")
    except:
        print("Authentication Error")

    status = "Another day, another cup of #coffee"

    api.update_status(status)

if __name__ == "__main__":
    main()

This is what I am getting:
Authentication Successful
Traceback (most recent call last):
  File "/Users/arnon/Downloads/mail_read/post_tweet.py", line 34, in <module>
    main()
  File "/Users/arnon/Downloads/mail_read/post_tweet.py", line 30, in main
    api.update_status(status)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/tweepy/api.py", line 46, in wrapper
    return method(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/tweepy/api.py", line 1121, in update_status
    return self.request(
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/tweepy/api.py", line 257, in request
    raise Unauthorized(resp)
tweepy.errors.Unauthorized: 401 Unauthorized

A: Found this in Twitter Community:

When creating your application, do not click the "create your access token" until you first click on Settings and change the Application Type to "Read, Write and Access direct messages".
After your Twitter application has been updated to "Read, Write and Access direct messages", click on the Home tab, and "create your access token".
This should do the trick =)

Source: https://twittercommunity.com/t/error-401-unauthorized/367/13

A: I had the same issue and that's how I managed to fix it:
the problem is probably that your access tokens do not have the needed permissions.
STEP BY STEP SOLUTION

*

*Go to https://developer.twitter.com/en/portal/projects-and-apps

*Go to Keys and tokens tab of the app that you want

*Check the permissions of your app checking what it writes below of the "Access Token and Secret"

*If it has only the Read permission go to the Settings tab of your app

*Click to Set Up the user authentication settings

*Enable the "OAuth 1.0a" and change the app permission to "Read and write and Direct message"

*Regenerate the tokens

A: Check the keys and tokens, make sure they are correct. According to https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401,
The HTTP 401 Unauthorized client error status response code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource.
This might also help:
https://docs.tweepy.org/en/stable/auth_tutorial.html#oauth-1a-authentication


text:
Q: How do I delete specific row of records on gridview? again.
On the gridview markup, I have these:
   <asp:TemplateField HeaderText="Dates">
     <ItemTemplate>
      <asp:Label ID="dates_label runat="server" Text='<%# Bind("shipDates","{0:M/dd/yyyy}") %>'></asp:Label>
    </ItemTemplate>
   </asp:TemplateField>

   <asp:TemplateField>
    <ItemTemplate>
     <asp:HiddenField ID="ehide" Value='<%# Eval("eventId") %>' runat="server" />
    </ItemTemplate>
   </asp:TemplateField>

The gridview displays several rows of records and using hidden form field, I am able to associate a row with its specific eventid from the events table.
Then below is the codebehind that attempts to delete each row of records.
    For Each row As GridViewRow In GridView1.Rows
        Dim dates_label = DirectCast(row.FindControl("dates_label"), Label)
        Dim shipDates = Date.ParseExact(dates_label.Value, "M/dd/yyyy", Nothing)

        Dim ehide = DirectCast(row.FindControl("ehide"), HiddenField)
        Dim eventid = ehide.Value

        Dim myConnectionString As [String] = ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString
        Dim myConnection As New SqlConnection(myConnectionString)
        Try
            myConnection.Open()
            strSQL = "Delete from tblEvents where username=@UserName and eventid = @eventid"
            com = New SqlCommand(strSQL, myConnection)
            com.Parameters.AddWithValue("@username", Session("username"))
            com.Parameters.AddWithValue("@eventid", eventid)
            Response.Write(strSQL)
            Response.End()
            com.ExecuteNonQuery()
            myConnection.Close()
            Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Information Saved successfully')</SCRIPT>")
            Response.Redirect("~/default.aspx")
        Catch ex As SqlException
            Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('" + ex.Message + "')</SCRIPT>")
        Finally
            myConnection.Close()
        End Try
    Next

When I run a debugger on this sub, it attempts to delete any row with the first eventid.
For instance, assume that there are 5 row of records on the event table and the eventIDs are 1,2,3,4,5. These are made up numbers for brevity.
If I try to delete the first record with eventId 1, I get:
delete from tblEvents where eventId = 1
If I try to delete the row with eventId 5, I still get:
Delete from tblEvents where eventId = 1
How do I resolve this in such that each row gets deleted by its rowId?
Thanks in advance.

A: Assumptions based on our discussion.

*

*You have a gridview that has row selection enabled

*You also have Delete Rows enabled. (EDIT: Just rememberd this option won't be available until you place the delete command in the SqlDataSource control)

*That eventid is coming from a database

If this is all true then deleteing rows is ridiculously easy:

*

*Place the eventid in GridView1 DataKeyNames via the Property page.

*From the designer select the SqlDataSource control connected to GridView1

*In the SqlDataSource Property List

*

*a. find DeleteQuery and select it's (Query)

*b. This will open the Command and Parameter Editor dialog box

*

*DELETE command: "DELETE FROM tblEvents WHERE (username = @UserName) AND (eventid = @eventid)

*click the Refresh Parameters button in the dialog

*Username: Parameter Source is Session, with SessionField as appropriate

*eventid: Parameter Source is Control, with ControlID of GridView1

*Save it all
Now the Delete command is "wired" to your primary key (eventid) and delete should just work


text:
Q: Installed Tensorflow but it failed to load on Python Here is the error I get:
Error trace is provided
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

import tensorflow as tf
      Traceback (most recent call last):
        File "C:\Python3.7.0\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in
          from tensorflow.python.pywrap_tensorflow_internal import *
        File "C:\Python3.7.0\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in
          _pywrap_tensorflow_internal = swig_import_helper()
        File "C:\Python3.7.0\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
          _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
        File "C:\Python3.7.0\lib\imp.py", line 243, in load_module
          return load_dynamic(name, filename, file)
        File "C:\Python3.7.0\lib\imp.py", line 343, in load_dynamic
          return _load(spec)
      ImportError: DLL load failed: The specified module could not be found.

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "", line 1, in
  File "C:\Python3.7.0\lib\site-packages\tensorflow__init__.py", line 24, in
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "C:\Python3.7.0\lib\site-packages\tensorflow\python__init__.py", line 49, in
    from tensorflow.python import pywrap_tensorflow
  File "C:\Python3.7.0\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Python3.7.0\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Python3.7.0\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Python3.7.0\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Python3.7.0\lib\imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Python3.7.0\lib\imp.py", line 343, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.

A: Try checking if tensorflow is really installed by

pip3 list

if so I recommend you install python 3.7.2.
Make sure you remove the file python from this directory  C:\Users\Your_user_name\appdata\local\programs\python before installing the new version of python. I tried it. It's working for me. I hope it helped.


text:
Q: how can i play youtube video with php like a proxy this is site
www.proxfree.net
i live in pakistan. youtube blocked here. so i watch the youtube from this site
www.proxfree.net
kindly anybody php expert help me how can make a youtube watch script like proxfree.net. waiting for help. Thanks in advance

A: In short (since this question doesn't deserve any better answer as it shows absolutely no effort):

*

*Rent a server in a country that doesn't block YouTube

*Make sure the webhost allows proxy-like functionality

*Create a form you'll use to input the external website URL

*Use cURL to communicate with that external website

There are tons of resources about this. Here's one: http://www.makeuseof.com/tag/create-online-proxy-server-minutes/


text:
Q: Obtener String vacio '' al buscar en xpath /text() cuando el nodo está vacío Tengo un HTML de la forma:
$3,480.00
Ingreso
Vigente

que recorro con XPath:
doc.xpath('//td/span/text()')

Pero a veces hay celdas vacías, las cuales no tienen nodo text(), del tipo:

entonces cuando uso:
dict(zip(cabeceras, datos))

quedan todos los datos revueltos.
Actualmente estoy usando replace para evitar que el XPath se salte los nodos vacíos, llenándolos con '_'.
cadena=lxml.html.tostring(data[row])
cadena=cadena.replace(">", ">_")
doc = lxml.html.fromstring(cadena)
datos=doc.xpath('//td/span/text()')

¿Hay alguna manera más elegante de resolver esto?

A: Se puede utilizar la función de XPath string( [object] ).

string()
Convierte el argumento dado en una cadena de texto.

lxml (Python):
Como comentó @JorgeArturoJuarez, la librería lxml solo permite usar la función string() sobre un elemento. Siguiendo su código, seleccionamos primero todos los nodos, y luego volvemos a usar otro predicado para llevar a string.
datos=[x.xpath('string()') for x in doc.xpath('//td/span')]

Código:
from lxml import html

cadena = '''

                $3,480.00
                Ingreso
                Vigente

                Otro

         '''
doc   = html.fromstring(cadena)

datos = [x.xpath('string()') for x in doc.xpath('//td/span')]

print(datos)

Salida:
['$3,480.00', 'Ingreso', 'Vigente', '', 'Otro']

Demo en ideone

XPath (en general1):
//td/span/string(text())

Aternativas que quizás también te interesen:

*

*//td/span/string()
Convierte a string todo el nodo del contexto, por lo que si el  tiene hijos, también convertirá a string todos los nodos de texto de los hijos.

*//td/span/normalize-space()
normalize-space() elimina el espacio antes y después del texto (~trim), o múltiples espacios en blanco los convierte en un espacio. En este caso también te devolverá un string vacío.

1: Para otras librerías que lo acepten o si lxml lo llega a incorporar.


text:
Q: How to configure nginx ingress in kubernetes for HTTPS backends with custom CA? I want to expose an HTTPS K8s service that uses a certificate derived from a custom root CA, outside the cluster using nginx ingress controller. Are the following configurations supported and if yes, how?

*

*client -- (HTTP) -- ingress -- (HTTPS) -- k8s service

*client -- (HTTPS) -- ingress -- (HTTPS) -- k8s service

Is it possible to configure nginx ingress controller such that it can do TLS and mutual-TLS with the HTTPS backend service?
How do I provision a root certificate for backend server certificate validation to nginx ingress?
Is it possible to do SSL termination on the ingress and do mutual-TLS with the backend?

A: I was able to provision the backend server certificates using the nginx.ingress.kubernetes.io/proxy-ssl-secret annotation.


text:
Q: From QString to Class type I have quite a good amount of classes all derived from the same parent and am in need of instantiating any of those from a simple QString
I imagined using a QMap with a QString key and "reference" to the class as value would do the trick
class Feat : public QObject { ... } // Base class

QMap<QString, ...> feats;

But i don't how where to go from here, what is the syntax to get what i want.

A: Given that your classes inherit from QObject, you could use the QMetaType system to construct instances from their name as a string. The meta-object system is a crucial part of Qt, and provides a mapping between type names and type IDs.
You need to first register your type, so that the meta-object system knows how to handle it, using:
Q_DECLARE_METATYPE(Feat)

Then, whenever you want to construct an object by its name, you would use:
int type_id = QMetaType::type("Feat");
void *obj = QMetaType::create(type_id);

Now obj points to a dynamically-allocated instance of Feat. Note that you'll need to release the object when you are finished (using QMetaType::destroy(type_id, obj);); wrap it in a guarded pointer of some kind (std::unique_ptr, QPointer, etc.); or ensure that it has a QObject parent which will automatically release it.
Also, note that you need to register each type that you'd like to use in this way.

A: As the constructor isn't a "normal" function, you need something like the factory pattern, i.e. to store functions that return a new instance of the given type; a trivial C++11+ way to do this is to map a QString to an std::function returning the new instance (as a pointer to the base class):
QMap<QString, std::function<Feat *()>> feats;
feats["Feat1"] = []() { return new Feat1; };
feats["Feat2"] = []() { return new Feat2; };

adjust as required if you need to pass in parameters to construct, or if you'd prefer to return some smart pointer (e.g. a unique_ptr). Also, depending on your taste you may or may not prefer to hide this code behind a macro.
#define REGISTER_FEAT(FeatClass) feats[#FeatClass] = []() { return new FeatClass;}
// to be used as
REGISTER_FEAT(Feat1);
REGISTER_FEAT(Feat2);

You may also avoid the std::function overhead if you are sure you won't need to capture anything in those lambdas, but I wouldn't worry about this unless you have some real reason (build times? runtime overhead?) to avoid it.

Incidentally, Qt containers are acknowledged even by Digia as in "life support mode", so, unless you have cogent reasons to use them (e.g. stable binary interface, more consistent performance across different compilers - albeit usually worse), you are generally better served by the builtin, "STL" counterparts (such as std::map or std::unordered_map).


text:
Q: log4j & Apache Kafka - Disabling specific log output So, I'm supposed to disable a repated logger-warning from my works code.
As I'm not working on it primarily, I don't know the necessary function.
It's a KafkaClient Application, Initialising two Consumers. But in the case of working on it locally, which they / I do, it cannot connect to a broker.
That means org.apache.kafka.clients.NetworkClient repeatedly logs two warnings each for each of the Consumers
Connection to node -1 (localhost: {IP}) could not be established. Broker
may not be available.

Bootstrap broker {ip} (id = -1 rack = null) disconnected.

I can easily pinpoint which two methods cause the logger to give this output.
Is there anyway, such as a config file, to supress this warning?
I haven't yet worked with loggers (IT Student), so all the solutions or tips I've found are just confusing to me.
Thanks in advance.

A: You can try filtering WARN logs using the below snippet in log4j.xml
    <category name="org.apache.kafka.clients.NetworkClient">
        <priority value="ERROR"/>
        <appender-ref ref=[your appender name]/>
    </category>

This will filter the WARN logs and will print only the ERROR logs.


text:
Q: First order variation and total variation of a function/stochastic process The notions of first-order variation and total variation of a function or a stochastic process are equated in this book.
However, I found their definitions different from two other sources:

*

*In Wikipedia the total variation of a function $f$ from time $0$ to time
$T$ is defined as $$
        \sup_\Pi \sum_{i=0}^{n-1} | f(t_{i+1})-f(t_i) | .  $$

*In Stochastic Calculus for Finance II: Continuous-time Models by
Steve Shreve, the first-order variation of a function or stochastic
process $f$ from time $0$ to time $T$ is defined as: $$ \lim_{||\Pi|| \to
    0} \sum_{j=0}^{n-1} [f(t_{j+1}) - f(t_j)] $$ where $$\Pi=[t_0, t_1,
    \dots, t_n] \text{ and } 0 \leq t_0 < t_1 < \cdots  < t_n = T$$ and
$$||\Pi||= \max_{j=0,\dots, n-1} (t_{j+1} -t_j).$$

Are they two different definitions, or equivalent? Thanks!


text:
Q: How to send an automatic email or sms from android application? I am creating an android application with the android studio in which I want to include the functionality that as soon as a customer places an order and it gets saved in the Firebase database, the user should either get an email regarding the order details or an SMS for the same.

A: For sending email automatically you can use firebase function which send email by calling its pre-defined URL. I found one example may be this on will help you:
cloud functions for firebase sending E-mail


text:
Q: How do you unbind a keyboard shortcut I'm wondering how I can unbind Ctrl+Space to bring up desktop/minimize windows. Whenever I jump and crouch in an FPS it minimizes the game. I searched and found people saying to edit lubuntu-rc.xml but I couldn't find Ctrl and Space bindings in there (I might have missed it, could be wrong)
Btw, this only happens when I hold them both down for a second, as opposed to alt tab when I press alt+tab at the same time it changes windows instantly. Also this only happens in the FPS game which is weird. I just switched to Lubuntu from Ubuntu so I don't know why this suddenly started happening it didn't do this on Ubuntu
EDIT; no need to answer, I solved it. I'm not sure why this only happened in game but in case someone has this same problem I went to Menu > Preferences > Keyboard Input Methods and where it says Next Input Method I deleted the bind to control space.

A: As the user seems to have been off-line for quite a while, answering the question for it, so that other people will not try to solve "unsolved" questions:
In Lubuntu, go to Menu > Preferences > Keyboard Input Methods and where it says Next Input Method delete the bind to Ctrl+space.


text:
Q: How to use plot3D::persp3D() to see plot in rgl device as with rgl::persp3d()? I would like to plot my 3D function in a rgl device window using plot3D package. It allows me to rotate on x, y, z axis and scale. This is basic example with rgl package:
x <- seq(-10, 10, length = 30)
y <- x
z <- outer(x, y, function(x, y) { r <- sqrt(x^2 + y^2); 10 * sin(r)/r })
z[is.na(z)] <- 1
rgl::persp3d(x, y, z)

Unfortunately this one is not open in rgl device:
plot3D::persp3D(x, y, z)

I am pretty sure that I have see it somewhere (maybe even in my experiments with that package). Can someone help me please?

A: tl;dr maybe you were looking for the plot3Drgl package?
I don't think this is possible. ?plot3D::persp3D says

'persp3D' is an extension to the default persp plot

(emphasis added). The "default persp plot" is built on the base R graphics, which uses a static "canvas-style" model - it cannot be dynamically rotated/zoomed.
Let's try looking for other packages with "3D" in their name ...
a1 <- available.packages()
grep("3D",rownames(a1),value=TRUE)
## [1] "arf3DS4"         "BaTFLED3D"       "DGVM3D"          "FPCA3D"
## [5] "plot3D"          "plot3Drgl"       "VecStatGraphs3D"

We can try plot3Drgl, whose documentation (?plot3Drgl) says

It will plot most (but not all) features from plots generated with
       'plot3D', except for the color keys and polygons.

On the other hand, it looks from experimentation as though it does handle color keys ...
plot3Drgl::persp3Drgl(x,y,z)


text:
Q: How can I change a number in a interface object from a variable in Java using something like Reflection or Javassist I have a variable, which is a new interface. I would like to change something inside of that.
I am not sure if this is possible with something like Reflection or Javassist.
This is fairly hard to explain, but if you look at the example you might understand me a bit better.
If you need more information, please ask because I really need to know this.
(this is code from ProtocolLib, which uses Netty. I want to patch something in ProtocolLib at runtime; hence I want to use something like Reflection or Javassist)
Actually; I just noticed that with some spaghetti code I can get this to work using Reflection. I will edit this post once again to let you know if this worked and then share my solution for others that might encounter the same issue as me.
Here is an example:
final ChannelInboundHandler endInitProtocol = new ChannelInitializer<Channel>() {
    @Override
    protected void initChannel(final Channel channel) throws Exception {
        try {
synchronized (networkManagers) {
    if (MinecraftVersion.getCurrentVersion().getMinor() >= 12 /* I want to change this 12 to an 8 using Reflection or something like Javassist */) {
    channel.eventLoop().submit(() ->
injectionFactory.fromChannel(channel, ProtocolInjector.this, playerFactory).inject());
    } else {
        injectionFactory.fromChannel(channel, ProtocolInjector.this, playerFactory).inject();
    }
}
        } catch (Exception ex) {
reporter.reportDetailed(ProtocolInjector.this, Report.newBuilder(REPORT_CANNOT_INJECT_INCOMING_CHANNEL).messageParam(channel).error(ex));
        }
    }
};

A: I completely forgot to tell that this question has been solved.
My solution:
I downloaded the ProtocolLib source code, then I made my changes to get it to work. I then compiled ProtocolLib, opened it with WinRAR, and extracted the anonymous class (ProtocolInjector$1). I added that class to my resources folder. I then used Javassist to create a new class out of the compiled class file (.class) at runtime and then I replaced the broken ProtocolInjector$1 class with the compiled fixed one.
You can see my commit here on how I fixed that: GitHub


text:
Q: Single Sign On from custom app to ADB2C application I have a web application that needs to connect to a SaaS application that used ADB2C. Once user logs in to my web application and does to the third-part integrated pages they should be automatically authenticated in the SaaS application (given they have been authenticated in my web app).
By adding my web app into the third-party ADB2C OIDC provider will it work ? I am not able to figure out how users in my web app will be able to "pass-through" the other application (federation ?).
Any pointers would be helpful.


text:
Q: NSURLConnection (initWithRequest vs sendAsyncRequest) If both initWithRequest and sendAsyncRequest are Asynchronous ways of connections then whats the major difference ?
Other than completion Handler and Queue concept in sendAsyncReq what else ?
Which 1 is more advantageous ??

A: The sendAsynchronousRequest is simpler and easier to use, saving you from implementing NSURLConnectionDataDelegate and NSURLConnectionDelegate methods. But if you need richness of delegate approach (e.g. challenge-based authentication, need cancelable requests, etc.), then sendAsynchronousRequest is not up to the job.
If targeting iOS 7 and later, consider NSURLSession, instead, too. You can enjoy simplicity of block-based networking and still enjoy delegate methods if and when needed. Also requests are always cancelable. It also opens new opportunities (e.g. background sessions that continue operating even if your app is no longer active).


text:
Q: How to get individually made dendrograms from dendextend to consesnus tree analysis? I am pretty new to R  so I am struggling with the following:
I have a dataset where I am  clustering several organ`s expresion values per patient. Like this I build 10 individual dendrograms. NOW, I would  like to  perform a consensus analysis and see how these individually built trees agree.
For the individual trees I have been using dendextend package. And I wanted to use the ape consensus function but I dont know how to transform my outcome from dendextend such that it is accepted in the consensus.
Like this I can plot the 10 individual trees
dend <- RawData[,4:ncol(RawData)] %>%
  dist %>%
  hclust(method = "average")%>%
  as.dendrogram

labels(dend) <- TMA_TT
dev.new()
dend %>% plot(main="dend")

I d like to use this:
consensus(..., p = 1, check.labels = TRUE)

....either (i) a single object of class "phylo", (ii) a series of such objects separated by commas, or (iii) a list containing such objects.

But I am not sure how to get my dendextend results to this format.


text:
Q: How would you speed up a for loop like this in R? My code has a for loop that is taking ages for running. I was wondering how can speed up it by using one of the apply family functions available in R.
The for loop that I want to change would look like this:
for (i in range(1:200000)){
    a[i] = gsub(pattern[i],new_pattern[i])
}

Where pattern and new_pattern are both lists. What I want to achieve is to change a character pattern in each line for a new one. I have tried the following:
sapply(c(1:200000),function(x) gsub(pattern[x],new_pattern[x], a[x]))

But it is taking very long too. Any suggestions of how can I improve my code to be faster?

A: You can proceed with str_replace_all from stringr package using a named vector:
library(stringr)

x = 'dog likes cat very much'
str_replace_all(x, setNames(c('babyboy','babygirl'), c('dog','cat')))

#[1] "babyboy likes babygirl very much"

Performance: 7-8 times faster
set.seed(1)
x = paste0(sample(c(letters,' '), 100000, replace=T, prob=c(rep(1/39, 26), 1/3)), collapse='')

patt = apply(df, 1, paste0, collapse='')
repl = as.character(1:456976)

system.time({
    for (i in 1:456976){
        x = gsub(patt[i],repl[i], x)
    }
})
#   user  system elapsed
#1574.41    2.41 1582.71

system.time(str_replace_all(x, setNames(repl, patt)))
#   user  system elapsed
# 194.04    0.14  194.36


text:
Q: No puedo guardar todo el archivo html No puedo guardar el archivo html de manera completa.
Porfavor da click en el siguiente enlace
https://www.bitfinex.com/order_book/BTCUSD
despues usa el atajo CTRL+S y guarda el archivo en formato html , abre el archivo guardado y podras ver que solo hay un fragmento de la pagina.
Necesito saber el porque y si conoces alguna solucion tambien seria de ayuda.
Gracias  =D
Nota: no es algun ajax que funcione segun lo que se esta visualizando porque si te desconectas de internet y revisas el sitio (ya cargado) la informacion sigue ahi , inclusive si sombreas todo el sitio , lo copias y lo guardas , solo podras guardar un fragmento de el sitio¡¡ =S

A: El problema es que los <div> se van generando en la posición que estas dinámicamente y cuando intentas guardar la página solo se van a imprimir los que se han generado previamente en la web.

Si te fijas el primer div generado esta en la posición 0px:

Pero si vas bajando vas a ver que el div de 0px desaparece.
En definitiva la clase ReactVirtualized__Grid__innerScrollContainer es la clave de todo este problema. Un grid hace que las celdas sean necesarias para llenarse en función de la posición de desplazamiento horizontal y vertical actual.

Espero que hayas entendido cual era el problema.
Saludos!


text:
Q: not getting response from virtualhosts apache2 ubuntu14 Hi I have a file geometrixxig.com.conf under my sites-enabled folder. After enabling that file i reloaded the apache service. I used the commands :
 sudo a2ensite geometrixxig.com

Below is my conf file :
<VirtualHost *:80>
      ServerAdmin webmaster@example.com
   ServerName geometrixxig.com
   ServerAlias www.geometrixxig.com
   DocumentRoot "/opt/communique/dispatcher/cache/content/geometrixx"
   RewriteEngine On
   RewriteRule ^/$ /content/geometrixx/en.html [PT,L]
   RewriteCond %{REQUEST_URI} !^/apps
   RewriteCond %{REQUEST_URI} !^/content
   RewriteCond %{REQUEST_URI} !^/etc
   RewriteCond %{REQUEST_URI} !^/home
   RewriteCond %{REQUEST_URI} !^/libs
   RewriteCond %{REQUEST_URI} !^/tmp
   RewriteCond %{REQUEST_URI} !^/var
   RewriteRule ^/(.*)$ /content/geometrixx/en/$1 [PT]
    <Directory "/opt/communique/dispatcher/cache/content/geometrixx">
     <IfModule disp_apache2.c>
           SetHandler dispatcher-handler
           ModMimeUsePathInfo On
         </IfModule>
         Options Indexes FollowSymLinks MultiViews
         AllowOverride all
         Order Allow,Deny
         Allow from all
 </Directory>
 </VirtualHost>

When i hit http://geometrixxig.com/ I am getting an error : You don't have permission to access /content/geometrixx/en.html on this server.
I have checked permission all are 777, but not getting why its not working.
If i hit http://localhost/content/geometrixx/en.html i get the page
Thanks

A: Have you tried changing ownership recursively?

chown -R www-data:www-data
  /opt/communique/dispatcher/cache/content/geometrixx


text:
Q: Data missing when use limits in ggplot [R] I am making a time series using bars in ggplot. For some reason the data isn't plotting for the first and last month. I think this is something to do with the limits - presumably the boundaries of the limits are excluded. However, when I extend the limits (so they go from December 2015 to January 2019 in this example), while there isn't any data for those months, the labels now start at December.
I introduced the limits originally because different plots were starting in different months (I don't know why - one was line and one was bar, so might be to do with different arguments, but still seemed odd to me). I want these to match, so thought having control over the limits would help. They do now match, but the bar version has the issues outlined.
I am looking for a solution where:

*

*The data for the first and last month of the data is shown.

*The labels on the x axis start with the first month.

*The labels on the x axis do not extend past the last month (even if the last month itself is not labelled).

Here is my code:
library(ggplot2)
library(lubridate)

num_month <- seq(from = as.Date("2016-01-01"), to = Sys.Date(), by='month')
month_data <- as.data.frame(matrix(0, ncol = 0, nrow = length(num_month)))
month_data$month <- as.POSIXct(num_month)
month_data$freq <- sample(100, size = nrow(month_data), replace = TRUE)
today <- as.POSIXct(Sys.Date())
date_lims <- c(as.POSIXct("2016-01-01", format = "%Y-%m-%d"), today)
ggplot(month_data, aes(x = month, y = freq)) +
  geom_bar(stat = "identity") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5, size = 12)) +
  scale_x_datetime(labels = date_format("%b-%y"), breaks = date_breaks("2 months"),
                   limits = date_lims)

Here is what it looks like:

Thanks for your help!

A: ggplot(month_data, aes(x = month, y = freq)) +
  geom_bar(stat = "identity") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5, size = 12)) +
  scale_x_datetime(date_labels = "%b-%y", date_breaks = "2 months",
                   limits = date_lims, expand = c(0,0))

This seems to work for me. I think the expand = c(0,0) part is what you were missing; this tells ggplot not to add any padding to the sides, as is default.


text:
Q: Parenthesis after field name in VB.Net I always work in C#, but I've been asked to work on a legacy VB.Net solution. In the legacy code, I am seeing this:
Private transactionListField() As TransactionInfoForStatement

This makes no sense to me! If it was C#, I'd expect this:
private List<Transaction> _transactions;

Can someone please explain to me what that VB code does? The parenthesis after the name makes me think it is calling a method, but when I Go To Definition in Visual Studio, I just end up on the same line!

A: That's an array declaration, you could also use this syntax that i prefer:
TransactionListField As TransactionInfoForStatement() ' array which is declared but Nothing

Arrays or indexers always use () in VB.NET as opposed to C# where you use [].
There's one advantage if you use the braces-first-syntax, you can specify the size:
TransactionListField(10) As TransactionInfoForStatement ' array that contains 11 Nothing


text:
Q: Is it true that all paths between two vertices share a common point? I'm stuck on following graph theory problem:
suppose for two vertices $u$ and $v$ in an undirected graph $G$, any pair of paths between $u$ and $v$ share a common vertex (different from $u$ and $v$), then there exists vertex $w$ ($w\neq u,v$), which lies on all paths between $u$ and $v$.
I don't know if this statement is true, but can't come up with any counterexamples. how can I approach this problem?

A: This is a special case of Menger's theorem.
If any two $u,v$-paths share a common vertex, then the maximum number of vertex-disjoint $u,v$-paths we can find is at $1$; therefore by Menger's theorem, there is a $u,v$-cut of size $1$, which is the vertex $w$.
This is assuming we're not in one of several trivial cases:

*

*If there are no $u,v$-paths, then it's vacuously true that any two share a vertex. Let $w$ be any vertex other than $u$ and $v$, and the conclusion still holds.

*But if there are no vertices other than $u$ and $v$, we're in trouble.

*If $u$ and $v$ are adjacent, and there are no other $u,v$-paths, it's still vacuously true that any two $u,v$-paths share a vertex. But there is no vertex $w$ other than $u$ and $v$ which lies on the path consisting only of the edge $uv$, so in this case the conclusion does not hold.

A: If the property is not true there would be three paths $\alpha$, $\beta$ and $\gamma$ each meeting the other two in at least a vertex but not having a common vertex, except the end points.
Let $G^\prime$ be the subgraph consisting only of the vertices and edges that make up the paths $\alpha$, $\beta$ and $\gamma$.
This graph $G^\prime$ is planar because it contains no $K_{3,3}$ and no $S_5$. So embed it in $\Bbb R^2$.
The external region $F$ has the property that $\Bbb R^2\setminus\overline F$ is a connected open set in $\Bbb R^2$. Indeed the only way that it couldn't be connected is that there existed a point $w\in\Bbb R^2\setminus F$ disconnecting it, but this point would be common to the three paths and different from the end points.
Thus the boundary of $w\in\Bbb R^2\setminus F$ is a cycle including $u$ and $v$ and never passing through the same vertices twice. But any such cycle defines two paths (the "upper" path and the "lower" path, if we lay $G^\prime$ horizontally in the plane) that meet only at endpoints.


text:
Q: Does GroovyShell cache the compiled scripts? I plan to embed groovy in my application and use GroovyShell programatically - I will run the same script several times with different parameters.
Does GroovyShell caches the compiled script or does it work only as a stateless interpreter?

A: I don't think it caches the scripts.  Take a look at the code.  Unless the comments are wrong, the scripts are not cached.  Line 511.


text:
Q: Does Spark Graphx have visualization like Gephi I am new to graph world. I have been assigned to work on graph processing. Now I know Apache Spark, so thought of using it Graphx to process large graph. Then I came across Gephi provides nice GUI to manipulate graphs.
Does Graphx have such tools or it is mainly parallel graph processing library. Can I import json graph data came from Gephi into graphx?

A: Adding to that you can as well try Graphlab
https://dato.com/products/create/open_source.html
It directly support Spark RDD
https://dato.com/learn/userguide/data_formats_and_sources/spark_integration.html
Not much work required after that
from pyspark import SparkContext
import graphlab as gl

sc = SparkContext('yarn-client')

t = sc.textFile("hdfs://some/large/file")
sf = gl.SFrame.from_rdd(t)

# do stuff...

out_rdd = sf.to_rdd(sc)

A: No, Apache Spark Graphx have no visualization, it's just a processing engine but you can import data from gephi to graphx using Gephi's API.


text:
Q: How to make Reachability.m in iOS to work with the full path of the resource? I wanted to check is device connoted to internet, and to check for my webpage.
So I found this answer: How to check for an active Internet connection on iOS or OSX?
In it code example was:
internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];

So I puted:
internetReachableFoo = [Reachability reachabilityWithHostname:@"www.weborcode.com/apps/gdjesumojepare/"];

What was not working, it would say that there is no internet connection, even when I was on internet.
So by some miracle I manage to understand that it is only working with domain name weborcode.com or www.weborcode.com.
But not with the the full path of the resource.
Is there any war to make it work with the full path of the resource ?

A: If you re-asses your code, you are calling reachabilityWithHostname, this will only check the hostname, that consist of two part, local part i.e www and the domain part i.e weborcode.com, So if you are trying to check a specific URL page then i would suggest you to look into NSURLConnection
Simple example:
NSURL *myURL = [NSURL URLWithString: @"www.example.org/apps/gdjesumojepare/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: myURL];
NSURLResponse *response;
NSError *error;
NSData *pageData = [NSURLConnection sendSynchronousRequest: request returningResponse:    &response error: &error];

If pageData return nil, this means that the webpage is down, If you receive back a non-nil pageData, this mean there is connectivity.  response and error will tell you what the server responded to you.


text:
Q: how to make AdMob on top? i have question about AdMob ,
i want to make it on top as autolayout
see the picture

 Banner = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
        Banner.adUnitID = "*********"
        Banner.rootViewController = self
        let req: GADRequest = GADRequest()
        Banner.loadRequest(req)
        Banner.frame = CGRectMake(0, view.bounds.height - Banner.frame.size.height, Banner.frame.size.width, Banner.frame.size.height)
        self.view.addSubview(Banner)

A:     Banner.frame = CGRectMake(0, 0, Banner.frame.size.width, Banner.frame.size.height)
    self.view.addSubview(Banner)
    self.view.sendSubviewToBack(Banner)

A: change this
    self.view.addSubview(Banner)

into
      navigationBar.addSubview(Banner)

or use
   self.navigationController!.navigationBar.addSubview(Banner)

for additional information see this
Update
change the frame of Banner, reason it occupy the full width of the navigation bar. change the X and Width and try for example
Banner.frame = CGRectMake(50, 0, Banner.frame.size.width - 50, Banner.frame.size.height)


text:
Q: How to send in an input to a running command in cmd? I am trying to send a signal to a cash drawer to make it open the drawer.
Its document says that the step is to:

*

*Type "TYPE CON>COM1" in command prompt and then ENTER.

*Type any character(s) and then ENTER.

The problem is that when the first command get executed, the command prompt window waits for an input from user to type anything into it and then ENTER, but tried

*

*echo open & TYPE CON>COM1

*echo open && TYPE CON>COM1

*echo open | TYPE CON>COM1

*using the 1-3 choices but with batch files.

Still, I can't achieve what I want. I just want to automate the steps into a single batch file.

A: I finally got a solution for this.
I use
ECHO>COM1

and it just works.


text:
Q: ¿porque me sale este error? bad operand types for binary operator "-" firs type:String second type: String ¿es que me sale el siguiente error y no entiendo porque me sale?
ME SALE

"bad operand types for binary operator "-""

hay especifico con una flechita el error.gracias
class triangulo {

    public void creartriangulo(int a, String b, String c) {
          if(c.length()==a){
          System.out.println(""+c);

          }
           else{
             System.out.println(""+c);
             c-= b; -----> este es el error
             c= (c-b); ----> así tampoco me sale ("pero cuando ponga el + si me sirve")

             creartriangulo(a,b,c);

        }
   }
}

A: Tu error es simple, no puedes hacer operaciones matemáticas a una variable de tipo string y en tu código c y b son de ese tipo por lo que siempre te mandara ese error, tienes la opción ya sea de cambiarlo a tipo int o hacer una conversión de la variable y devolver el valor.
Cambio a int
class triangulo {

public void creartriangulo(int a, int b, int c) {
      if(c==a){
      System.out.println(""+c);

      }
       else{
         System.out.println(""+c);
         c-= b;

         creartriangulo(a,b,c);
      }

  }
}

Conversión de variables
class triangulo {

public void creartriangulo(int a, String b, String c) {
      if(c.length()==a){
      System.out.println(""+c);

      } else {
         System.out.println(""+c);
         int parseInt = Integer.parseInt(c);
         parseInt -= Integer.parseInt(b);

         creartriangulo(a,b,Integer.toString(parseInt);
      }
  }
}


text:
Q: How to encode x264 remotely but build file locally? Eg

*

*.avs script created on local Windows machine.

*Video source is also on local machine.

*But encoding is done on remote Linux machine? And the new encoded file is not stored on Linux machine, but is sent over/built in the Windows machine.
Is something like that possible? My problem is that I have local Windows machine with enough storage, but not enough resources for CPU encoding and vice versa with the remote Linux machine enough CPU, but no storage.

A: It is possible you would have to most probably write a script on the linux machine.
If you use handbrake the watch folder could come in handy.

*

*Share a folder on the Windows Machine (Storage) and mount it on
your Linux Machine(Encoder), create two directories within that share.

*Use cron and rsync to monitor the Storage share every X mins and
copy them to the handbrake watch directory. (Make sure you have set
handbrake up to encode automatically to your preferred presets)

*Use cron and rsync to monitor the handbrake converted directory every
x mins and copy it over to the windows completed share folder    and
delete the files from the handbrake converted folder.
I hope this helps.
It is simple to do but I am assuming you know some basic scripting.


text:
Q: Is it possible to only screenshare a specific UIView using AppScreenSource? Is it possible to only screenshare a specific UIView using AppScreenSource?
I'm creating an iOS app which is using RealityKit to place virtual objects on screen. I'd like to share this video with the other connected user in the room.  AppScreensource seems like an almost perfect solution, but I don't want to share the entire screen - just my ARView.  Is there a way to do this?  Or do I need to go another route?

A: After going through the doc. I don't find any solution for capturing a portion of the screen. AppScreensource will the whole screen.
Link to the docs - https://www.twilio.com/docs/video/ios-v4-screen-capture

A: maybe you can use ARView's instance method snapshot(saveToHDR:completion:). There is a working example mentioned in this blog.


text:
Q: How to implement notification app badge icon in flutter using FCM? I have been using Firebase push notification , and it all works. I want to show notification in app launcher icon with its count. I have seen many examples regarding this but unfortunately i could not achieve it.
  I have read to give badge permission. But where to give those permission and how? I have tried using the below package too
 flutter_app_badger: ^1.1.2

but failed. Can somebody find me a solution.
It would be more helpful to get a solution regarding FCM badge permission.


text:
Q: Gradle - declare one dependency to pull from m2 repo I have a gradle project, but my actual work is in a dependency to that project.  I'm trying to have my gradle project pull my local work contained in my m2 repo, but I only want to pull THAT particular dependency from my local environment, everything else I want to be pulled as it would be from my deployed test environment, so I want to avoid just declaring mavenLocal() in my build script.  Is there a way to specify for gradle to pull one dependency from my local maven cache, and everything else should be as is?

A: There is a thing called repository filtering:
mavenLocal().content {
  // this repository *only* contains artifacts with group "my.company"
  includeGroup "my.company"
}

More info can be found on gradle's website.


text:
Q: Create Temporary Function in Hive i have a query like this
CREATE TEMPORARY MACRO AAA (input VARCHAR(16))
input||
SUBSTR(
LPAD(
(CASE WHEN SUBSTR(LPAD(input,16,0),15,1) = 1 THEN 2
WHEN SUBSTR(LPAD(input,16,0),15,1) = 2 THEN 4
WHEN SUBSTR(LPAD(input,16,0),15,1) = 3 THEN 6
WHEN SUBSTR(LPAD(input,16,0),15,1) = 4 THEN 8
WHEN SUBSTR(LPAD(input,16,0),15,1) = 5 THEN 10
WHEN SUBSTR(LPAD(input,16,0),15,1) = 6 THEN 1
WHEN SUBSTR(LPAD(input,16,0),15,1) = 7 THEN 3
WHEN SUBSTR(LPAD(input,16,0),15,1) = 8 THEN 5
WHEN SUBSTR(LPAD(input,16,0),15,1) = 9 THEN 7
ELSE 0
END) +
(CASE WHEN SUBSTR(LPAD(input,16,0),16,1) = 1 THEN 1
WHEN SUBSTR(LPAD(input,16,0),16,1) = 2 THEN 2
WHEN SUBSTR(LPAD(input,16,0),16,1) = 3 THEN 3
WHEN SUBSTR(LPAD(input,16,0),16,1) = 4 THEN 4
WHEN SUBSTR(LPAD(input,16,0),16,1) = 5 THEN 5
WHEN SUBSTR(LPAD(input,16,0),16,1) = 6 THEN 6
WHEN SUBSTR(LPAD(input,16,0),16,1) = 7 THEN 7
WHEN SUBSTR(LPAD(input,16,0),16,1) = 8 THEN 8
WHEN SUBSTR(LPAD(input,16,0),16,1) = 9 THEN 9
ELSE 0
END)
,3,0), 3, 1);

but I want to create a temporary function for hive.
What needs to be changed and what format is it in to create a temporary function?

A: You will have to write your own UDF.
Ref : https://cwiki.apache.org/confluence/display/Hive/HivePlugins
Once you have jar file with custom logic you can create function like below:
Tested in Hive version apache-hive-4.0.0-alpha-1
CREATE TEMPORARY FUNCTION aa_fun as 'AAA' using jar 'hdfs://localhost:9000/user/hive/aaa_func.jar';

select aa_fun('fwfrgwre12a3') fun_res, AAA('fwfrgwre12a3') macro_res;

+----------------+----------------+
|    fun_res     |   macro_res    |
+----------------+----------------+
| fwfrgwre12a33  | fwfrgwre12a33  |
+----------------+----------------+


text:
Q: Limit query time on Azure Synapse Analytics On Azure Synapse Analytics, users can inadvertently run very resource-consuming queries over potentially large amounts of data.
On SQL Server, it's possible to configure a server-wide remote query timeout to limit this. Ideally, a database will provide an option to do this on an ad-hoc basis (i.e. query by query).
Is this possible on Azure Synapse Analytics (pool and/or serverless).

A: The simple answer is yes, it is possible to do it on Azure Syanapse Analytics. You can use a feature similar to Resource Governor on SQL Server called Work Load Management {1}. Using a workload group, you can set a parameter called QUERY_EXECUTION_TIMEOUT_SEC to define how long a query can run. Using the workload group you can define the parameter for a user, group of user, label, context, etc. {2}{3}. Please, take a look at the documentation below:
CREATE WORKLOAD GROUP group_name
 WITH
 (   MIN_PERCENTAGE_RESOURCE = value
   , CAP_PERCENTAGE_RESOURCE = value
   , REQUEST_MIN_RESOURCE_GRANT_PERCENT = value
  [ [ , ] REQUEST_MAX_RESOURCE_GRANT_PERCENT = value ]
  [ [ , ] IMPORTANCE = { LOW | BELOW_NORMAL | NORMAL | ABOVE_NORMAL | HIGH } ]
  [ [ , ] QUERY_EXECUTION_TIMEOUT_SEC = value ] )
  [ ; ]

{1}
https://learn.microsoft.com/en-us/azure/synapse-analytics/sql-data-warehouse/sql-data-warehouse-workload-management
{2}
https://learn.microsoft.com/en-us/azure/synapse-analytics/sql-data-warehouse/sql-data-warehouse-workload-classification
{3}
https://learn.microsoft.com/en-us/sql/t-sql/statements/create-workload-group-transact-sql?toc=%2Fazure%2Fsynapse-analytics%2Fsql-data-warehouse%2Ftoc.json&bc=%2Fazure%2Fsynapse-analytics%2Fsql-data-warehouse%2Fbreadcrumb%2Ftoc.json&view=azure-sqldw-latest&preserve-view=true
{4}
https://learn.microsoft.com/en-us/azure/synapse-analytics/sql-data-warehouse/sql-data-warehouse-workload-isolation#execution-rules


text:
Q: need help understanding what this code does line by line import random

random_numbers = [random.randint(1,100) for r in range(10)]

print(random_numbers)

for i in range(len(random_numbers)):
    min_index = i
    for j in range(i+1, len(random_numbers)):
        if random_numbers[min_index] > random_numbers[j]:
            min_index = j

    random_numbers[i], random_numbers[min_index] = random_numbers[min_index], random_numbers[i]
print(random_numbers)

i struggle to completly understand this code, and some help whould be highly appreciated

A: This code creates a list of random numbers and then sorts them, from lowest to highest.
When you're a little more used to coding you'll be able to use a debugger to see how these changes work. Until then, the best thing to do load the thing up with print statements, and see how you go.
We'll do three little cheats first though.

*

*We'll choose random numbers from 1 to 10 instead of 1 to 100.

*We'll  have a list of four elements, rather than ten. These changes make things more managable to when you're trying to figure out how things work.

*We're going to create a dummy variable, _, and set it to _ = input(). This means you have to hit a key on every iteration of the code, so you can control what's happen. Just hit return each time the prompt comes up, and that'll move you on to the next iteration of the loop.
OK, here we go. First, we create our list of random numbers and get a look at them.
random_numbers = [random.randint(1,10) for r in range(4)]

print(random_numbers)

Next we have two loops - an outer loop, and an inner.
for i in range(len(random_numbers)):
    min_index = i
    for j in range(i+1, len(random_numbers)):
        print(f"i: {i}, j: {j}")

When the i loop starts, the min_Index variable to set to whatever the i value is, and the j is set to i+1. So first time out, i=0, min_index=0, and j=1. We'll print those to the screen, so we always know where we are.
Every time the j loop runs, it compares the value at random_numbers[min_index] to the value at random_numbers[j]. We're printing those values.
print(f"The random number at min_index {min_index} is {random_numbers[min_index]}.")
print(f"random number at j {j} is {random_numbers[j]}.")

On every run of the inner, j, loop, we check to see if random_numbers[min_index] > random_numbers[j]. If it is, we change min_index to j, If it isn't, we just roll along.
Now. At the end of the that j loop, we swap the values of   random_numbers[i] and random_numbers[min_index] . That awkward-looking random_numbers[i], random_numbers[min_index] = random_numbers[min_index], random_numbers[i] is syntactic sugar. If we didn't use it, we'd have to use a third, temporary variable, like this:
temp = random_numbers[i]
random_numbers[i] = random_numbers[min_index]
random_numbers[min_index] = temp

So a, b = b, a just means "swap a and b's values."
Now, if  random_numbers[min_index] > random_numbers[j] was true, those values swap around. If it wasn't, nothing happens because min_index and j are the same - we're saying a, b = a, b.
As the outer loop rolls along, the lower values are progressively moved along to the front of the the list until, by the end of the loop, all the random numbers are sorted. I know this seems very verbose, but it'll make more sense when you run the full code:
for i in range(len(random_numbers)):
    min_index = i
    for j in range(i+1, len(random_numbers)):
        print(f"\ni: {i}, j: {j}, min_index: {min_index}.")
        print(f"The random number at min_index {min_index} is {random_numbers[min_index]}.")
        print(f"random number at j {j} is {random_numbers[j]}.")
        if random_numbers[min_index] > random_numbers[j]:
            print(f"Because {random_numbers[min_index]} is greater than {random_numbers[j]} I'm going to set the min_index value to j")
            min_index = j

        _ = input() # pause button

    print("And that's the end of inner loop.")

    print("random numbers[i] was", random_numbers[i])
    print("random numbers[min_index] was", random_numbers[min_index])

    random_numbers[i], random_numbers[min_index] = random_numbers[min_index], random_numbers[i]
    print("random numbers[i] is", random_numbers[i])
    print("random numbers[min_index] is", random_numbers[min_index])

print(random_numbers)

Hope this helps.


text:
Q: Ubuntu locks up at "Started Clean php session files" I am having an issue with my server box..
MSI Tomahawk B350 MB BIOS 1.60
AMD Ryzen x1800
64GB 3300 Ram
Samsung 960 Pro 1TB M.2 SSD
Plain Jane video card
500w Gold Power supply
I have tried Ubuntu 16, 17 and 18.. all do the same thing..  This is a fresh install, nothing running on the box except default LAMP..
It will run fine for 2 to 3 weeks, then freeze on me.. In the logs, it is always after:
May  2 03:42:24 SRV3 systemd[1]: Started Message of the Day.
May  2 04:09:01 SRV3 CRON[1718]: (root) CMD (  [ -x /usr/lib/php/sessionclean ] && if [ ! -d /run/systemd/system ]; then /usr/lib/php/sessionclean; fi)
May  2 04:09:23 SRV3 systemd[1]: Starting Clean php session files...
May  2 04:09:23 SRV3 systemd[1]: Started Clean php session files.
May  9 07:17:40 SRV3 systemd-modules-load[557]: Inserted module 'iscsi_tcp'

Anyone else ever run into this or heard of the same issue?


text:
Q: Return Parameters from a Recursive function in python sorry if this is a noob question, I wasn't able to find a solution online (maybe I just don't know what to search for).
How do I return the "found" dictionary from this recursive function
(I am only able to return the nth number)
Note: simply returning found at the end does not work for multiple reasons
# Nth Fibonacci number generator
def nth_Rfib(n, found = {0:1, 1:1}):
    if n in found:
        return found[n]
    else:
        found[n] =  nth_Rfib(n-1, found) + nth_Rfib(n-2, found)
    #print(found)
    return found[n] # return found ** Doesn't Work **

print(nth_Rfib(5))  # 8
# instead, it should return: {0: 1, 1: 1, 2: 2, 3: 3, 4: 5, 5: 8}

Thank you.

A: In both cases, you need to return found. But as your function returns dictionary, you need to access a needed value when you call it recursevly:
def nth_Rfib(n, found = {0:1, 1:1}):
    if n in found:
        return found
    else:
        found[n] =  nth_Rfib(n-1, found)[n-1] + nth_Rfib(n-2, found)[n-2]
    return found

print(nth_Rfib(5))

this returns:
{0: 1, 1: 1, 2: 2, 3: 3, 4: 5, 5: 8}

Note a possible issue with default mutable arguments like your found = {0:1, 1:1}, for example:
>>> print(nth_Rfib(3))
{0: 1, 1: 1, 2: 2, 3: 3}
>>> print(nth_Rfib(5))
{0: 1, 1: 1, 2: 2, 3: 3, 4: 5, 5: 8}
>>> print(nth_Rfib(3))
{0: 1, 1: 1, 2: 2, 3: 3, 4: 5, 5: 8}

nth_Rfib(3) after nth_Rfib(5) returns the same dictionary, because you never reset it to the default {0:1, 1:1}.

A: You need a function that returns a number, so that the recursive expression
found[n] = fib(n-1) + fib(n-2)

can make sense; and you also need a function that returns a dictionary, since that's what you want to return, ultimately.
Hence it makes sense to define two distinct functions, one that returns a number, and one that returns a dict.
def nth_Rfib(n):
    found = {0: 0, 1: 1}
    def fib(n):
        if n not in found:
            found[n] = fib(n-1) + fib(n-2)
        return found[n]
    fib(n)
    return found

This makes found a variable which is local to nth_Rfib, but acts like a global variable during the recursive calls of fib.
It also completely eliminates any oddities of mutable default arguments.
>>> nth_Rfib(10)
{0: 0, 1: 1, 2: 1, 3: 2, 4: 3, 5: 5, 6: 8, 7: 13, 8: 21, 9: 34, 10: 55}
>>> nth_Rfib(3)
{0: 0, 1: 1, 2: 1, 3: 2}


text:
Q: Set a default Scale value for Xcode 7.2.1's iOS Simulator I just started an online course for learning Swift using Xcode to develop iOS apps. I'm using Xcode 7.2.1 and 10.11.4 on my Mac Mini Server. I use a 23" monitor. When the simulator window displays while running an application the default scale size is 100% which is really huge for my monitor. I would like to set the default scale to a lower percentage without having to hit keys on the keyboard every time I open a simulator window. I'm sure I will never need to have the scale at 100% because of the size of my monitor. I could not find anything in the Xcode Preferences to change the value. I do not see a Preferences option in the Simulator.
I found How do I resize the iOS simulator? with a solution posted by Slipp Thompson in December 2015. I do not have the filename com.apple.iphonesimulator.plist or any similarly names plists in /Library/Preferences or ~/Library/Preferences. I also attempted to search the developer documentation but did not find anything.
If this is what I need to do to set the preferences, where can I find sample plist files? Or has this completely changed?


text:
Q: Please what does mean this : if (a && b == c){};? Please what does mean this:
if (a && b == c){};

I did not understand the logic of the condition statement

A: && has lower precedence than ==, so it's equivalent to:
if (a && (b == c))

It means if a has a truthy value and also the value of b is equal to the value of c.

A: The condition (a && b == c) has two operators. The Logical AND Operator and the Equality Operator.
The operation foo && bar returns true, if both operands foo and bar have truthy values.
foo == bar returns true, if foo equals bar.

The equality operator converts the operands if they are not of the same type, then applies strict comparison. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

If an expression contains more than one operator, the operator precedence is of the utmost importance.

Operator precedence determines the way in which operators are parsed with respect to each other. Operators with higher precedence become the operands of operators with lower precedence.

The == operator has a higher prededence than the && operator. Therefor the above condition will check b == c first. If the result is true and the value of a is truthy, the result of the condition will be true.
The Grouping operator ( ) has the highest precedence and therefor can be used to force a specific order of operations.
If you're not absolutely sure in which order operations will be processed, use the grouping operator!
The result of
(a && (b == c))

will be the same as the result of
(a && b == c)

but is better readable. Of course you should learn and know the precedence of operators. But if in doubt and especially in a really hairy line with lots of operators, the value that a few brackets add to readability can easlily outperform the costs of a few bits of additional code.


text:
Q: Why is LVS dropping packets? I am currently trying to get down to the core of a problem where my
LVS-director seems to drop a packet coming from a client from time to
time. We have this problem on our production systems and can reproduce
the problem on staging.
I posted this problem on the lvs-users-mailing-list and got no response so far.
Our setup:
We are using ipvsadm with Linux CentOS5 x86_64 in a PV XEN-DomU.
Current Version details:

*

*Kernel: 2.6.18-348.1.1.el5xen

*ipvsadm: 1.24-13.el5

LVS-Setup:
We use IPVS in DR-mode, for managing the running connections we use
lvs-kiss.
ipvsadm is running in a heartbeat-v1-cluster (two virtual nodes), master
and backup are running constantly on both nodes.
For the LVS-services we use logical IPs being setup by heartbeat
(active/passive-clustermode)
The real-servers are physical Linux-machines.
Network-Setup:
The VM acting as director is running as XEN-PV-DomU on a Dom0 using bridged networks.
Networks "in play":

*

*abn-network (staging-network, used to connect the client to the director),
used by the real-servers to send the answer to the clients (direct routing approach),
used for ipvsadm slave/master multicast-traffic

*lvs-network: This is a dedicated VLAN which connects director and real-servers

*DR-arp-problem: solved my suppressing arp-answers on the real-servers for the service-ip

*The service-IP is configured as logical IP on the lvs-interface on the real-servers.

*In this setup ip_forwarding is not needed anywhere (neither on
director, nor on real-server).

VM details:
1 GB RAM, 2 vCPUs, system-load almost 0, memory 73M free, 224M buffers, 536M cache, no swap.
top shows almost always 100% idle, 0% us/sy/ni/wa/hi/si/st.
Configuration details:
ipvsadm -Ln for the service in question shows:
TCP  x.y.183.217:12405 wrr persistent 7200
 -> 192.168.83.234:12405   Route   1000   0          0
 -> 192.168.83.235:12405   Route   1000   0          0

x.y first two octets are from our internal class-B-range.
We use 192.168.83.x as lvs-network for staging.
Persistent ipvsadm-configuration:
/etc/sysconfig/ipvsadm: --set 20 20 20
Cluster-configuration:
/etc/ha.d/haresources: $primary_directorname lvs-kiss x.y.183.217
lvs-kiss-configuration-snippet for the service above:
<VirtualServer idm-abn:12405>
  ServiceType       tcp
  Scheduler         wrr
  DynamicScheduler    0
  Persistance         7200
  QueueSize           2
  Fuzz              0.1
  <RealServer rs1-lvs:12405>
    PacketForwardingMethod  gatewaying
    Test ping -c 1 -nq -W 1 rs1-lvs >/dev/null
    RunOnFailure   "/sbin/ipvsadm -d -t idm-abn:12405 -r rs1-lvs"
    RunOnRecovery   "/sbin/ipvsadm -a -t idm-abn:12405 -r rs1-lvs"
  </RealServer>
  <RealServer rs2-lvs:12405>
    PacketForwardingMethod  gatewaying
    Test ping -c 1 -nq -W 1 rs2-lvs >/dev/null
    RunOnFailure   "/sbin/ipvsadm -d -t idm-abn:12405 -r rs2-lvs"
    RunOnRecovery   "/sbin/ipvsadm -a -t idm-abn:12405 -r rs2-lvs"
  </RealServer>
</VirtualServer>

idm-abn, rs1 and rs2 resolve via /etc/hosts.
About the service:
This is a soa-web-service.
How we reproduce the error:
From a client we run constant calls to the web-service at an interval of one call in three seconds.
From time to time there will be a connection reset from the director to the client.
Interesting: This happens on n x 100th + 1 tries - interesting is the one.
What we did to trace down the problem:

*

*Checked /proc/sys/net/ipv4/vs: all values are set to default, so drop_packet is NOT in place (=0)

*tcpdump on client, fronted/abn of the director, backend/lvs of the directory, lvs and abn of the real-servers

In this tcpdump we could see a request from the client, answered by a
connection-reset by the director.
The packet was NOT forwarded via LVS.
I welcome any ideas on how to track this problem further down.
If any information is unclear/missing to drill down the problem - please
ask.

A: Do you have any stateful iptables rules on the LVS-DR director? As I can see you are using port 12405, so if you have a rule like this:
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 12405 -j ACCEPT

In LVS-DR real servers are replying to requests from clients (and not the director), the director won't add those connections in the connection tracking table and the FIN packets won't be detected on the director's iptables with the rules ESTABLISHED,RELATED. Since you only allow NEW (SYN) packets on port 12405, FIN will be blocked. You have to use a stateless firewall on an LVS-DR director for load balanced services:
iptables -A INPUT -m tcp -p tcp --dport 12405 -j ACCEPT


text:
Q: How to find a 4x4 invertible Matrix and a 4x4 real diagonal matrix? I am taking a Linear Algebra course and I came across this problem.

Find a 4 × 4 invertible real matrix P and a 4 × 4 real diagonal matrix Λ such that:
$P^{−1}AP = Λ$.
A note is given that $P^{-1}$ does not need to be calculated.

I am having difficulty with it, I have come across the form $PAP^{−1} = Λ$ before but never $P^{−1}AP= Λ$. Any advice would be greatly appreciated.

Edit: I missed part of the question that provides context. Full question below.

In following the following problem u,v,w will be the following vectors:
  $$u = \begin{pmatrix}1 \\\ 0\\3 \end{pmatrix}, v = \begin{pmatrix}2 \\-1\\1 \end{pmatrix}, q = \begin{pmatrix}3 \\\ 1\\2 \end{pmatrix}$$
If a 3×3 matrix M is such that Mu=−5u, Mv=0 and Mw=3w,
Find a 4 × 4 invertible real matrix P and a 4 × 4 real diagonal matrix Λ such that:
P^{−1}AP = Λ.
A note is given that $P^{-1}$ does not need to be calculated.

I attempted to solve this problem, but I do think not that my attempts are correct:

Starting out I used the vectors u, v,w to form an invertible matrix (and checked for linear independence).
That gave the matrix P:
$ \begin{pmatrix}
1&2&3\\\
0&-1&1\\\
3&1&2\\\
\end{pmatrix} $
Using the info from Mu = -5u, Mv = 0v, Mw = 3w
=$\lambda  = -5, 0, 3$ to make a real diagonal matrix M:
$ \begin{pmatrix}
-5&0&0\\\
0&0&0\\\
0&0&3\\\
\end{pmatrix} $
$\Rightarrow P^{-1}MP = \Lambda $
$ \begin{pmatrix}
1&2&3\\\
0&-1&1\\\
3&1&2\\\
\end{pmatrix}^{-1} \cdot \begin{pmatrix}
-5&0&0\\\
0&0&0\\\
0&0&3\\\
\end{pmatrix} \cdot \ \begin{pmatrix}
1&2&3\\\
0&-1&1\\\
3&1&2\\\
\end{pmatrix} =  $ $\Lambda $

A: For $$P^{−1}AP= Λ$$ your matrix $P$ is the matrix whose columns are the eigenvectors of $A$ and Λ is the diagonal matrix of eigenvalues.
Note that we need linearly independent eigenvectors in order for the matrix $P$ to be invertible.


text:
Q: how to make my button pick a random word and then after again I've written a program to print out a random word and its definition to a text field when the button is pressed once. I want to have it to print another random word and definition when The button is pressed repeatedly. Any Ideas?
I am new to coding so please take that into consideration.
This is what I have so far:
public class RandomWord extends JFrame{
private JTextField wordField;
private JTextField defField;
private JButton nextButton;
private String words[] = {"Petrichor:",//0
                        "Iterate:",//1
                        "Absquatulate:",//2
                        "Anhuiliform:",//3
                        "Argle-bargle:","Argus-eyed:",//4
                        "Automy:",//5
                        "Benthos:",//6
                        "Bibliopole:",//7
                        "Bilboes:",//8
                        "Bruxism:",//9
                        "Borborygmus:",//10
                        "Calipygian:",//11
                        "Callithumpian:",//12
                        "Cereology:",//13
                        "Chad:",//14
                        "Chiliad:"};//15

private String def[] = {"The smell of earth after rain.",//0
                        "To utter or perform repeatedly.",//1
                        "To leave somewhere abruptly.",//2
                        "Resembling an eel.",//3
                        "Copious but meaningless talk or writing.",//4
                        "Vigilant, refering to Argos a Greek mythological watchman with a hundred eyes.",//5
                        "The casting off of a limb or other part of the body by an animal under threat, such as a lizard.",//6
                        "The flora and faunda on the bottom of a sea or lake.",//7
                        "A person who buys and sells books, especially rare ones",//8
                        "An iron bar with sliding shackles, used to fasten prisoners' ankles.",//9
                        "Involantary and habitual grinding of the teeth.",//10
                        "A rumbling or gurgling noise in the intestines.",//11
                        "Having shapely buttocks.","Like a discordant band or a noisy parade.",//12
                        "The study or investigation of crop circles.",//13
                        "A piece of waste paper produced by punching a hole.",//14
                        "A thousand things or a thousand years."};//15

public RandomWord(){
    super("Cool Words -1.5");
    setLayout(new FlowLayout());

    int idx = new Random().nextInt(words.length);
    final String randomWord = words[idx];
    final String randomDef = def[idx];

    wordField = new JTextField("Petrichor",20);
    add(wordField);
    defField = new JTextField("The smell of earth after rain",20);
    add(defField);
    nextButton = new JButton("Next");
    add(nextButton);

    nextButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {
            wordField.setText(randomWord);
            defField.setText(randomDef);

        }
    });
}

}

A: You are choosing the random word and definition at the constructor was called.
You must to change this to choose the random word and definition when you are click with mouse (inside actionPerformed method).
Try with this:
public RandomWord(){
    super("Cool Words -1.5");
    setLayout(new FlowLayout());

    wordField = new JTextField("Petrichor",20);
    add(wordField);
    defField = new JTextField("The smell of earth after rain",20);
    add(defField);
    nextButton = new JButton("Next");
    add(nextButton);

    nextButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {

            // this method is executed when you clicked;
            // The random word and definition must be choose at this moment.
            int idx = new Random().nextInt(words.length);
            wordField.setText(words[idx];);
            defField.setText(def[idx]);

        }
    });
}

A: Try removing the final keyword in your Strings. Final denotes that the String value cannot be changed after its declaration:
   String randomWord = words[idx];

   String randomDef = def[idx];


text:
Q: Rectangle shape drawable won't show as checkbox selector item I have defined a rectangle drawable like this:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <corners android:radius="4dip"/>
    <solid android:color="#FF000000" />
    <stroke android:width="1dip" android:color="@color/service_checkbox_disabled_unchecked_stroke" />

</shape>

I can display the drawble as imageView without problems. However, it is supposed to be a drawble for one state of a checkbox. My selector for the checkbox button is defined like this:
<selector xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:state_checked="true" android:drawable="@drawable/bg_services_tick_unchecked_disabled" />
    <item android:state_checked="false" android:drawable="@drawable/bg_services_tick_unchecked_disabled" />

</selector>

And finally my checkbox:
<CheckBox
    android:id="@+id/cb_tariff_3_next_month_checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:button="@drawable/checkbox_services"
    android:layout_centerHorizontal="true"/>

Can anyone tell, why does that not work? Thank you very much.

A: You must add a size node to the shape:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    >
    <size android:width="30dp" android:height="30dp" />
    <solid android:color="@color/blueBase"/>
    <stroke
        android:width="1dp"
        android:color="@color/blueDark" />
</shape>


text:
Q: How to back up a table and remove old data using cron in kohana I want to run a cron which will take back up of data of a particular table for last three months and then it will delete the data which has been saved to the backup file. I have not done this before. Can I have some guidelines how to accomplish it ?
I have studied how to set cron, but confused with the backup process.
My project is in Kohana 3.0.7 and uses Mysql.

A: You could either point your cron at a php script on the server and do whatever you need to do from there.
OR
Directly from the cron script itself you could use the mysql client commands as follows (not tested!):
0 0 * * * mysqldump -t -u[username] -p[password] dbname table_name --where="date_field>xyz" > /home/username/data.sql
0 0 * * * mysql -u[username] -p[password] dbname -e 'delete from...'


text:
Q: Apache Rewrite if file not found to another file? I am trying to rewrite my urls to another file if they do not already exist. I have an .htaccess file in the root of my site that looks like this.
RewriteEngine on

# Add slash to end of request
RewriteCond %{REQUEST_URI} !(/$|\.)
RewriteRule (.*) %{REQUEST_URI}/ [R=301,L]

# API redirect
RewriteCond %{REQUEST_URI} ^/api
RewriteRule . api/v1.php [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST} ^ secondary\.
RewriteRule . sites/secondary [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . sites/main.php [L]

My intention is to serve two sites from the same folder and use the rewrites to point to the appropriate routers. The api redirect works great. However, the main and secondary redirect do not work unless I specify a route other than example.com (example.com/test/ correctly rewrites).
Any insight is greatly appreciated.

A: Use:
RewriteEngine on

# Add slash to end of request
RewriteCond %{REQUEST_URI} !(/$|\.)
RewriteRule ^ %{REQUEST_URI}/ [R=301,L]

# API redirect
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^api api/v1.php [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST} ^ secondary\.
RewriteRule ^ sites/secondary [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ sites/main.php [L]

Because . is at least equal to one character.